Chinaunix

标题: UNP上的 非阻塞connect Web客户程序,connect()函数出错!! [打印本页]

作者: Zhc1993    时间: 2012-10-14 15:43
标题: UNP上的 非阻塞connect Web客户程序,connect()函数出错!!
我是按照书上的代码写的,
在 home_page() 函数中的 tcp_connect()里,程序终止了

是 connect() 出现 Invalid arguments;

tcp_connect()就是 UNP P255页的代码。int tcp(const char *host,cosnt char * serv);
host 我写的是 "www.baidu.com"
serv "80"
connect() 无法成功,怎么解决??懂的人帮一下忙,感激不尽!!
作者: linux_c_py_php    时间: 2012-10-14 19:45
tcp_connect的代码你贴一下.
作者: Zhc1993    时间: 2012-10-14 21:53
  1. int tcp_connect(const char *host,const char *serv)
  2. {
  3.         int sockfd,n;
  4.         struct addrinfo hints,*res,*ressave;
  5.         bzero(&hints,sizeof(struct addrinfo));

  6.         hints.ai_family = AF_UNSPEC;
  7.         hints.ai_socktype = SOCK_STREAM;
  8.         if((n = getaddrinfo(host,serv,&hints,&res)) != 0)
  9.         {
  10.                 perror("get addrinfo error\n");
  11.                 exit(0);       
  12.         }
  13.         ressave = res;
  14.         if(ressave == NULL)
  15.         {
  16.                 printf("can't get the addrinfo\n");
  17.         }
  18.         do
  19.         {
  20.                 sockfd = socket(res->ai_family,res->ai_socktype,res->ai_protocol);
  21.                 if(sockfd < 0)
  22.                 continue;
  23.                
  24.                 if(connect(sockfd,res->ai_addr,res->ai_addrlen) == 0)
  25.                 break;
  26.                
  27.                 close(sockfd);       
  28.         }while((res = res->ai_next) != NULL);
  29.         if(res == NULL)
  30.         {
  31.                 perror("tcp connect error\n");
  32.                 exit(0);
  33.         }
  34.         freeaddrinfo(ressave);
  35.         return sockfd;
  36. }
复制代码

作者: Zhc1993    时间: 2012-10-14 21:59
真巧,我在csdn上也问了这个问题,第一个回答的人的头像也是这条蛇!

作者: linux_c_py_php    时间: 2012-10-14 22:26
还真没发现错误, 而且我试验也是可以正常连接的.

tcp        0      1 119.254.35.221:41980        220.181.111.147:80          FIN_WAIT1   -   

无效参数很费解, 不行你在hint里指定一下ai_family = AF_INET;吧。




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2