Last active
September 29, 2015 05:58
-
-
Save leesei/a4a1de843ee507b9a2d4 to your computer and use it in GitHub Desktop.
code fragment for getting info of a dynamically bound port #c #socket
This file contains hidden or 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
// code fragment for getting info of a dynamically bound port | |
struct sockaddr_in s_in; | |
int len = sizeof(s_in); | |
s_in.sin_family = AF_INET; | |
s_in.sin_addr.s_addr = INADDR_ANY; | |
s_in.sin_port = htons(0); | |
//SOCKET s = socket(AF_INET, SOCK_STREAM, 0); // TCP | |
SOCKET s = socket(AF_INET, SOCK_DGRAM, 0); // UDP | |
bind(s, (SOCKADDR*) &s_in, sizeof(s_in)); | |
getsockname(s, (SOCKADDR*) &s_in, &len); | |
{ | |
char tmp[200]; | |
printf(tmp, "%d", ntohs(s_in.sin_port)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment