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
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <stdlib.h> | |
#include <stdio.h> | |
#include <string.h> | |
int main(int argc, char *argv[]) { | |
int sfd = socket(AF_INET, SOCK_STREAM, 0); | |
if (sfd == -1) { | |
perror("socket"); | |
return 1; | |
} | |
struct sockaddr_in saddr; | |
memset((char*)&saddr, 0, sizeof(saddr)); | |
saddr.sin_family = AF_INET; | |
saddr.sin_addr.s_addr = INADDR_ANY; | |
saddr.sin_port = htons(0); // bind port to zero explicitly. | |
if (bind(sfd, (struct sockaddr*)&saddr, sizeof(saddr)) < 0) { | |
perror("bind"); | |
return 1; | |
} | |
struct sockaddr_in infoaddr; | |
socklen_t infolen = sizeof(infoaddr); | |
memset((char*)&infoaddr, 0, sizeof(infoaddr)); | |
getsockname(sfd, (struct sockaddr*)&infoaddr, &infolen); | |
printf("%d", infoaddr.sin_port); // random port number | |
close(sfd); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment