0

I have a problem binding the socket. There is no error as such, not sure why if fails on if condition.

int result = WSAStartup(MAKEWORD(2,2), &wsadata);
if(result != NO_ERROR)
{
    printf("\nThere is a problem at WSAStartup");
}
else
{
    printf("\nWSAStartup was ok");
}
list_sock = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
if(list_sock == -1)
{
    printf("\n Socket not created %d\n", list_sock);
}
else
{
    printf("\nSocket was created Succesfully");
}
HOSTENT *thishost;
char *ip;
u_short port;
port = 55555;
thishost = gethostbyname("localhost");
printf("\n");
printf("\nHost name is:%s ",thishost->h_name);
ip = inet_ntoa(*(struct in_addr*)*thishost->h_addr_list);
printf("\nip address is %s\n ", ip);
printf("Address type is:%i",thishost->h_addrtype);
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr(ip);
service.sin_port = htons(port);
if(bind(list_sock,(SOCKADDR *)&service,sizeof(service))== SOCKET_ERROR)
{
    printf("Error during bind %s", strerror(errno));
}
else
{
    printf("All done");
}
WSACleanup();

return 0;

I get error at line

if(bind(list_sock,(SOCKADDR *)&service,sizeof(service))== SOCKET_ERROR)

But strerror(errno)) gives me: "No error". But it still fails on if condition and does not bind.

Any help?

4

1 回答 1

1

10014 is WSAEFAULT, which bind() returns when:

The system detected an invalid pointer address in attempting to use a pointer argument in a call.

This error is returned if the name parameter is NULL, the name or namelen parameter is not a valid part of the user address space, the namelen parameter is too small, the name parameter contains an incorrect address format for the associated address family, or the first two bytes of the memory block specified by name do not match the address family associated with the socket descriptor s.

You are creating an IPv6 socket (AF_INET6), but you are trying to bind it to an IPv4 (AF_INET) address. That will not work. You need to either create an IPv4 socket, or bind to an IPv6 address, depending on what you are trying to accomplish.

Lastly, don't use gethostbyname("localhost"). First, it only supports IPv4. Second, if you want to bind to the loopback IP, explicitly bind to 127.0.0.1 (IPv4) or ::1 (IPv6), which you can hard-code or at least use the INETADDR_SETLOOPBACK() macro in mstcpip.h. If you want to bind to all available IPs, bind to INADDR_ANY (IPv4) or IN6ADDR_ANY (IPv6), which you can hard-code or at least use the INETADDR_SETANY() macro in mstcpip.h. If you really want to use a function call, use getaddrinfo() instead, which supports both IPv4 and IPv6.

于 2013-06-20T18:33:42.867 回答