#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <netdb.h>//gethostbyname
//#include <cygwin/in.h>//struct in_addr(<linux/in.h>)
#include <netinet/in.h>
#include <sys/socket.h>
typedef struct sockaddr SA;
typedef struct sockaddr_in SIN;
int main()
{
int ip =0;
int name;
ip = open_clientfd("61.152.234.71",80,2);
name = open_clientfd("www.sohu.com",80,1);
//
printf("result is %d/n",name);
printf("result is %d/n",ip);
}
//type == 1 gethostbyname
//type == 2 gethostbyaddr
int open_clientfd(char * host,int port,int type)
{
int client_fd;
struct hostent *hp;
struct sockaddr_in serveraddr;
if ((client_fd = socket(AF_INET,SOCK_STREAM,0))<0)
{
return -1;
}
bzero((char *)&serveraddr,sizeof serveraddr);
serveraddr.sin_family = AF_INET;
if (type == 1)//通过机器名来获得hp
{
if ((hp = gethostbyname(host))==NULL)
{
return -2;
}
printf("the h_addr is %02X/n",hp->h_addr);
bcopy((char *)(hp->h_addr),(char *)&serveraddr.sin_addr.s_addr,hp->h_length);
}
if (type == 2)
{
//方法二
//serveraddr.sin_addr.s_addr = inet_addr(host);
//方法三
struct in_addr i;
inet_aton(host,&i);
serveraddr.sin_addr = i;
}
// 方法一
// if (type == 2)//通过IP来获得hp
// {
// if ((hp = gethostbyaddr(host,4,AF_INET))==NULL)
// {
// return -2;
// }
// bcopy((char *)(hp->h_addr),(char *)&serveraddr.sin_addr.s_addr,hp->h_length);
// }
serveraddr.sin_port = htons(port);
if (connect(client_fd,(SA *)&serveraddr,sizeof serveraddr)<0)
{
return -3;
}
return client_fd;
}