Created
March 17, 2015 05:23
-
-
Save qiuchengxuan/55042746682098e5f536 to your computer and use it in GitHub Desktop.
Winsock2 server side with random listening port
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
WSADATA wsaData; | |
int iResult; | |
iResult = WSAStartup(MAKEWORD(2,2),&wsaData); | |
if (iResult != 0) { | |
return; | |
} | |
SOCKADDR_IN server; | |
server.sin_family = AF_INET; | |
server.sin_addr.s_addr = INADDR_ANY; | |
server.sin_port = 0; | |
SOCKET sock = INVALID_SOCKET; | |
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); | |
if (sock == INVALID_SOCKET) { | |
WSACleanup(); | |
return; | |
} | |
iResult = bind(sock, (SOCKADDR*)&server, sizeof server); | |
if (iResult == SOCKET_ERROR) { | |
closesocket(sock); | |
WSACleanup(); | |
return; | |
} | |
int len = sizeof server; | |
getsockname(sock, (SOCKADDR*)&server, &len); | |
listen(sock, 1); | |
int port = htons(server.sin_port); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment