Where does winsock store the socket ip address?

Suppose I have a simple winsock server that has a listening socket, and then when the connection is accepted, it stores the socket in an array of sockets (to allow multiple connections). How can I get the IP address of a specific connection? Is it stored in the socket handle?

+4
source share
2 answers

As long as the socket remains connected, you can get both your own socket address and peer.

getsockname will give you a local name (i.e. from the side of your channel) getpeername will give you a peer name (i.e. the remote side of the channel)

This information is available only when opening / connecting a socket, therefore it is useful to store it somewhere if it can be used after peer-to-peer disconnections.

+7
source

Yes, it is stored in the socketaddr_in structure, you can extract it using:

 SOCKADDR_IN client_info = {0}; int addrsize = sizeof(client_info); // get it during the accept call SOCKET client_sock = accept(serv, (struct sockaddr*)&client_info, &addrsize); // or get it from the socket itself at any time getpeername(client_sock, &client_info, sizeof(client_info)); char *ip = inet_ntoa(client_info.sin_addr); printf("%s", ip); 
+3
source

Source: https://habr.com/ru/post/1468932/


All Articles