Skip to content

Instantly share code, notes, and snippets.

@qiuchengxuan
Created March 17, 2015 05:23
Show Gist options
  • Save qiuchengxuan/55042746682098e5f536 to your computer and use it in GitHub Desktop.
Save qiuchengxuan/55042746682098e5f536 to your computer and use it in GitHub Desktop.
Winsock2 server side with random listening port
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