does creating the socket even work?Code:SOCKET establish (unsigned short portnum) { char computer_name[256]; SOCKET new_sock; struct sockaddr_in sa; struct hostent *hp; memset (&sa, 0, sizeof (struct sockaddr_in)); gethostname (computer_name, sizeof (computer_name)); hp = gethostbyname (computer_name); if (hp == NULL) return INVALID_SOCKET; sa.sin_family = hp->h_addrtype; sa.sin_port = htons (portnum); new_sock = socket (AF_INET, SOCK_STREAM, 0); if (new_sock == INVALID_SOCKET) return INVALID_SOCKET; if (bind (new_sock, (struct sockaddr *) &sa, sizeof (struct sockaddr_in)) == SOCKET_ERROR) { closesocket (new_sock); return INVALID_SOCKET; } if (listen (new_sock, 20) == SOCKET_ERROR) { closesocket (new_sock); return INVALID_SOCKET; } cout << "Still ok at return"; return new_sock; }
About the red-marked parts:
What's that? Are you trying to get the servers hostname and resolve it? If that even works, you are not passing the resolved address anywhere, so you can clear that.
But I doubt, this even works
About the blue-marked parts:
Look closer, its obvious why this can not work.
1. pass AF_INET to sin_family. If youre coding the server for the internet or other IP-networks, this is always right.
2. I can't see any assignment to sin_addr here ... despite the fact that you were trying to resolve the address above, I recommend you to use this:
This is needed to tell the machine, which interfaces to use. INADDR_ANY would be 0.0.0.0, but you could also assign the ip address of a NIC or even the loopback interface (127.0.0.1) to restrict the server to listen on that NICs (or the loopback adapter)Code:sa.sin_addr.s_addr = INADDR_ANY;
3. This is actually not a big deal, but socket() is supposed to get passed PF_INET, not AF_INET. This still works, because they are identical. Though they were both supposed to have different purposes. So I think it's more correct to use PF_INET, but that's your choice
(This doesn't apply to the struct sockaddr_in!)
I hope this helps solving