I'm using lib winsock2 in Visual Studio community, using simple client example. After executing connect() function, would like to know how can I get/return self/source port number of open connection.
CodePudding user response:
In winsock2, when a connection is established you can bind socket port to some specific port you want to use. For example, let´s say you are creating an UDP or TCP socket and you want that a specific local port is used. In that case you can do that by calling bind function ( https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-bind )
if (port != 0) {
int rv = -1;
struct sockaddr_in recv_addr;
ZeroMemory(&recv_addr, sizeof(struct sockaddr_in));
recv_addr.sin_family = AF_INET;
recv_addr.sin_port = htons(port);
recv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
rv = bind(udp_channel->socket, (SOCKADDR *)& recv_addr, sizeof(recv_addr));
}
This is the same bind function you will use to set listening port when your socket will act as a server in UDP or TCP, it's the same.
In case you don't do socket binding, socket port will be assigned on connection. There seems to be the function getsockname that user207421 mentioned.
CodePudding user response:
getsockname() or getpeername()
- returning Structured data with
short sin_family
andchar sa_data[]
with different amount of data depending on the protocols used - after connection to server use fuction
getsockname()
orgetpeername()
to get the structured data we need to extract the data to get the port - you use function
ntohs()
for extracting the port data with macro functionSS_PORT
to convert struct tosockaddr_in
example:
sockaddr struc_;
int struc_len = sizeof(struc_);
/* connect function*/
getsockname(ConnectSocket, (LPSOCKADDR)&struc_, &struc_len);
int port_int_ = ntohs(SS_PORT(&struc_));
- or you can define a ready-made structure / create your own, with a pointer to port number data.