Home » Extra libraries, Code snippets, applications etc. » U++ users applications in progress and useful code snippets, including reference examples! » Find an available/free port - code snippet (TcpSocket, port)
Find an available/free port - code snippet [message #57943] |
Fri, 31 December 2021 13:18  |
Mountacir
Messages: 42 Registered: November 2021
|
Member |
|
|
Hello,
I needed to get an available/free port for localhost, so I used the code below with a derived TcpSocket class.
I'm wondering if it is possible to implement it in TcpSocket?
int TcpSocket::GetFreePort(){
socklen_t addrLen;
int s = ::socket(AF_INET, SOCK_STREAM, 0);
if (s == -1) {
LOG("Failed to create socket");
}
sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = 0;
// INADDR_ANY as the default parameter?
//sin.sin_addr.s_addr = htonl(INADDR_ANY);
sin.sin_addr.s_addr = inet_addr("127.0.0.1");
if (bind(s, (const sockaddr *)&sin, sizeof(sin)) == -1) {
LOG("Failed to bind");
}
addrLen = sizeof(sin);
if (getsockname(s, (struct sockaddr *)&sin, &addrLen) == -1) {
LOG("getsockname() failed");
}
LOG("port : " << sin.sin_port);
return sin.sin_port;
}
Thanks!
[Updated on: Sun, 23 January 2022 19:05] by Moderator Report message to a moderator
|
|
|
Re: Find an available/free port [message #58035 is a reply to message #57943] |
Sat, 22 January 2022 19:14   |
 |
mirek
Messages: 13964 Registered: November 2005
|
Ultimate Member |
|
|
Ausin2029 wrote on Fri, 31 December 2021 13:18Hello,
I needed to get an available/free port for localhost, so I used the code below with a derived TcpSocket class.
I'm wondering if it is possible to implement it in TcpSocket?
int TcpSocket::GetFreePort(){
socklen_t addrLen;
int s = ::socket(AF_INET, SOCK_STREAM, 0);
if (s == -1) {
LOG("Failed to create socket");
}
sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = 0;
// INADDR_ANY as the default parameter?
//sin.sin_addr.s_addr = htonl(INADDR_ANY);
sin.sin_addr.s_addr = inet_addr("127.0.0.1");
if (bind(s, (const sockaddr *)&sin, sizeof(sin)) == -1) {
LOG("Failed to bind");
}
addrLen = sizeof(sin);
if (getsockname(s, (struct sockaddr *)&sin, &addrLen) == -1) {
LOG("getsockname() failed");
}
LOG("port : " << sin.sin_port);
return sin.sin_port;
}
Thanks!
This is a good snippet of core, but I am not quite sure how is it related to TcpSocket instance?
|
|
|
|
|
Goto Forum:
Current Time: Thu Dec 07 11:54:24 CET 2023
Total time taken to generate the page: 0.01288 seconds
|