Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a socket's local port number? (Windows C++)

I'm new to Windows networking, and I am trying to find out which PORT number my socket is bound to (C++, Windows 7, Visual Studio 2010 Professional). It is a UDP socket, and from what I understand, using the following initial setup should bind it to a random available port/address:

sockaddr_in local;
local.sin_family = AF_INET;
local.sin_addr.s_addr = INADDR_ANY;
local.sin_port = 0; //randomly selected port
int result = bind(clientSock, (sockaddr*)&local, sizeof(local));
//result is always 0

As far as using this method, it works for sending data or binding it to a specific port (replacing the 0 with a desired port number). What I need is to bind it randomly, and then find out which port it was bound to afterwards. Is there any way I can do this? It seems that the "local" struct contains "0.0.0.0" as the IP address and "0" as the PORT number.

Thanks for any and all help! I appreciate it.

like image 953
Sefu Avatar asked Dec 03 '22 07:12

Sefu


1 Answers

Use getsockname. For example:

struct sockaddr_in sin;
int addrlen = sizeof(sin);
if(getsockname(clientSock, (struct sockaddr *)&sin, &addrlen) == 0 &&
   sin.sin_family == AF_INET &&
   addrlen == sizeof(sin))
{
    int local_port = ntohs(sin.sin_port);
}
else
    ; // handle error

This also works for *nix-based systems, but note that some systems define the third argument of getsockname to be of type socklen_t* instead of int*, so you might get warnings about pointers differing in signedness if you're writing cross-platform code.

like image 77
Adam Rosenfield Avatar answered Dec 25 '22 06:12

Adam Rosenfield