Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does winsock store ip address of a socket?

Tags:

c++

winsock

Suppose I have a simple winsock server that has a listening socket, and then when a 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?

like image 642
William Northern Avatar asked Mar 13 '13 10:03

William Northern


2 Answers

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

getsockname will give you local name (i.e. from your side of a pipe) getpeername will give you peer name (i.e. distant side of a pipe)

This information is available only when the socket is opened/connected, so it is good to to store it somewhere if it can be used after peer disconnects.

like image 110
Valeri Atamaniouk Avatar answered Sep 29 '22 16:09

Valeri Atamaniouk


Yes it is stored in the socketaddr_in struct, 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);
like image 30
Serdalis Avatar answered Sep 29 '22 15:09

Serdalis