#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
/****************************************************************************
*Description:
* it is used to connect to specified host with socket.
*
*Parameters:
* hostname: host name
* port: port
* sockfd: socket handle returned if success
*
*Returns:
* return 0 if success, 1 i failed.
*
****************************************************************************/
int sock_connect(char *hostname, int port, int *sockfd)
{
char tmpbuf[64];
int sfd = 0;
struct sockaddr_in addr;
struct hostent *ph = 0;
ph = gethostbyname(hostname);
if ( ph == NULL ) {
strcpy(tmpbuf, hostname);
} else {
strcpy(tmpbuf, (char*)inet_ntoa(*(struct in_addr*)ph->h_addr_list[0]));
}
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = inet_addr(tmpbuf);
if(addr.sin_addr.s_addr == INADDR_NONE) {
return 1;
}
sfd = socket(AF_INET,SOCK_STREAM,0);
if ( sfd < 0 ) {
return 1;
}
if ( connect(sfd, (struct sockaddr *)&addr, sizeof(addr)) ) {
return 1;
}
*sockfd = sfd;
return 0;
}
/****************************************************************************
*Description:
* it is used to get local ipaddress.
*
*Parameters:
* eth: device name, eg: "eth0"
* ipaddr: ipaddress returned if success
*
*Returns:
* return 0 if success, 1 if failed.
*
****************************************************************************/
int sock_ipaddr(char *eth, char *ipaddr)
{
struct ifreq req;
struct sockaddr_in *addr;
unsigned long ip = 0;
int sock = 0;
if ( (!eth) || (!ipaddr) ) {
return 1;
}
sock = socket(AF_INET, SOCK_STREAM, 0);
if ( sock < 0 ) {
return 1;
}
strcpy(req.ifr_name, eth);
if ( ioctl(sock,SIOCGIFADDR,&req) == -1 ) {
return 1;
}
addr = (struct sockaddr_in *)&req.ifr_addr;
ip = addr->sin_addr.s_addr;
sprintf(ipaddr, "%d.%d.%d.%d", ip&0xff, (ip>>8)&0xff, (ip>>16)&0xff, (ip>>24)&0xff);
return 0;
}
(stavy.sun) |