- 论坛徽章:
- 0
|
在Linux下,可以ping通IP地址和网址,比如ping www.baidu.com 都ok的。但是我的下面代码在运行时,connect函数一直在connect,不能打印出下面的printf("connect result is %d\n",conn);语句。为什么connect一直在连接,就是连接不上去呢?求助高手!谢过先!(我的运行命令是./test www.baidu.com 80, test由下面的代码编译得出)
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <netdb.h>
#include <stdio.h>
#define BUFFSIZE 80
int
main(int argc, char **argv)
{
int sockfd, errno, conn;
char buf[BUFFSIZE];
ssize_t nread;
struct addrinfo hints, *res, *ressave;
bzero(&hints, sizeof(struct addrinfo));
hints.ai_family = AF_INET; /* IPv4 */
hints.ai_socktype = SOCK_STREAM; /* TCP */
if ((errno = getaddrinfo(argv[1], argv[2], &hints, &res)) != 0) {
printf("errno = %d\n",errno);
exit(1);
}
if (res == NULL){
printf("getaddrinfo has error\n");
exit(1);
}
ressave = res;
while (res != NULL) {
if ((sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1)
printf("socket error\n");
conn = connect(sockfd, res->ai_addr, res->ai_addrlen);
printf("connect result is %d\n",conn);
if (conn == 0)
break;
close(sockfd);
res = res->ai_next;
}
while ((nread = read(sockfd, buf, BUFFSIZE)) > 0) {
if (write(STDOUT_FILENO, buf, nread) == nread)
printf("write success\n");
else
printf("write error\n");
}
exit(0);
}
[ 本帖最后由 woodandwood 于 2007-7-25 10:30 编辑 ] |
|