Overview
Examples
Screenshots
Comparisons
Applications
Download
Documentation
Tutorials
Bazaar
Status & Roadmap
FAQ
Authors & License
Forums
Funding Ultimate++
Search on this site
Search in forums












SourceForge.net Logo
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)
icon3.gif  Find an available/free port - code snippet [message #57943] Fri, 31 December 2021 13:18 Go to previous message
Mountacir is currently offline  Mountacir
Messages: 49
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

 
Read Message icon3.gif
Read Message
Read Message
Read Message
Previous Topic: Horizontal Cursor for CodeEditor/LineEdit
Next Topic: SUniGuiCreator
Goto Forum:
  


Current Time: Thu May 23 22:35:31 CEST 2024

Total time taken to generate the page: 0.02369 seconds