int createclientsock(char * hostname, int port){
struct hostent * hp;
printf("Attempting to create client socket!\n");
memset(&client_addr,'0',sizeof(client_addr));
client_addr.sin_family = AF_INET;
client_addr.sin_port = htons(port); /* holds the remote port */
/* If internet "a.d.c.d" address is specified, use inet_addr()
* to convert it into real address. If host name is specified,
* use gethostbyname() to resolve its address */
client_addr.sin_addr.s_addr = inet_addr(hostname); /* If "a.b.c.d" addr */
if (client_addr.sin_addr.s_addr == -1) {
hp = gethostbyname(hostname);
/* Call method to create server socketyname(hostname);*/
/*printf("host name: %s",hp);*/
if (hp == NULL) {
printf("ERROR: Host name %s not found\n", hostname);
exit(1);
}
}
/* Create an Address Family (AF) stream socket, implying the use of tcp as the underlying protocol */
client_fd = socket(AF_INET, SOCK_STREAM, 0);
printf("Client_fd: %d\n",client_fd);/*ANDY: it gets to here without printing errors, the client_fd = 3 ...im not sure what that means*/
/* use the sockaddr_in struct in the to variable to connect */
if (connect(client_fd, (struct sockaddr *)&client_addr, sizeof(client_addr)) < 0) {
printf("ERROR: could not connect!\n");
exit(1);
}
return client_fd;
}
它到达连接部分并且需要很长时间才能最终打印错误语句“ERROR:无法连接!\ n”
答案 0 :(得分:0)
不确定这是否是您的实际问题,但行:
memset(&client_addr,'0',sizeof(client_addr));
可能不是你想要的。它使用字符 '0'
填充结构,而不是零字节。最好写成:
memset(&client_addr,'\0',sizeof(client_addr));
此外,如果您使用DNS名称而不是IP地址,则永远不会将其加载到client_addr
结构中。您返回hostent
指针,但应该使用该结构中的h_addr_list
字段填充client_addr.sin_addr.s_addr
。