当前位置: 技术问答>linux和unix
请问一个小程序!
来源: 互联网 发布时间:2016-03-13
本文导语: 我函数是这样的: int tcp_connect() { struct hostent *hp; struct sockaddr_in addr; int sock; char *ptr; struct in_addr *pipaddr; ptr=HOST; if(!inet_aton(ptr,hipaddr)) { printf("inet_aton...
我函数是这样的:
int tcp_connect()
{
struct hostent *hp;
struct sockaddr_in addr;
int sock;
char *ptr;
struct in_addr *pipaddr;
ptr=HOST;
if(!inet_aton(ptr,hipaddr))
{
printf("inet_aton errorn");
return 1;
}
if(!(hp=gethostbuaddr(hipaddr,4,AF_INET)))
berr_exit("couldn't resolve host!");
..............................
..............................
运行时出错:couldn't resolve host!
是啥原因呢?我把里linux的防火墙也关了,可就是不能调不过!
int tcp_connect()
{
struct hostent *hp;
struct sockaddr_in addr;
int sock;
char *ptr;
struct in_addr *pipaddr;
ptr=HOST;
if(!inet_aton(ptr,hipaddr))
{
printf("inet_aton errorn");
return 1;
}
if(!(hp=gethostbuaddr(hipaddr,4,AF_INET)))
berr_exit("couldn't resolve host!");
..............................
..............................
运行时出错:couldn't resolve host!
是啥原因呢?我把里linux的防火墙也关了,可就是不能调不过!
|
这个写法有很多问题啊.
int
tcp_connect(const char *host, const char *serv)
{
int sockfd, n;
struct addrinfo hints, *res, *ressave;
/*
* Initialize addrinfo struct, and specify a socket
* family and a socket type for our proxy connection.
*/
bzero(&hints, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ( (n = getaddrinfo(host, serv, &hints, &res)) != 0) {
syslog(LOG_ERR, "tcp_connect error for %s, %s", host, serv);
}
ressave = res;
/*
* Loop through, calling socket and connect for each IP, creating
* a linked list of addrinfo structures, once a successful connection
* has been made, break out of loop. We then free memory and return
* a socket descriptor.
*/
do {
sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (sockfd ai_addr, res->ai_addrlen) == 0)
break; /* Break on success */
close(sockfd);
} while ( (res = res->ai_next) != NULL); /* Build linked list */
if (res == NULL) {
syslog(LOG_ERR, "tcp_connect error for %s, %s", host, serv);
}
freeaddrinfo(ressave);
return (sockfd);
}
|
是很有有问题!