-
-
Save fallback/32709e7c164f87e4a6e4b856c57aaf28 to your computer and use it in GitHub Desktop.
Returns available TCP Port in Objective-C / Cocoa
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
- (int) availableTcpPort | |
{ | |
struct sockaddr_in addr; | |
socklen_t len = sizeof(addr); | |
addr.sin_port = 0; | |
inet_aton("0.0.0.0", &addr.sin_addr); | |
int sock = socket(AF_INET, SOCK_STREAM, 0); | |
if (sock < 0) { | |
perror("socket()"); | |
return -1; | |
} | |
if (bind(sock, (struct sockaddr*) &addr, sizeof(addr)) != 0) { | |
perror("bind()"); | |
return -1; | |
} | |
if (getsockname(sock, (struct sockaddr*) &addr, &len) != 0) { | |
perror("getsockname()"); | |
return -1; | |
} | |
return (addr.sin_port); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment