0
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;

}

它到达连接部分并需要很长时间才能最终打印错误语句“错误:无法连接!\n”

4

1 回答 1

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.

于 2013-10-16T00:36:44.820 回答