5
votes

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?

2
Sidenote: the socket handle is more or less just a typedef for an integer variable. On *nix the programmer uses an actual int to keep track of the handles.dutt
Nothing is "stored in the handle"; it's just a handle, not an object! It refers to an in-kernel object though (which you obviously can't access directly), and that does track the relevant IP addresses. getsockname/getpeername calls into the kernel and retrieves the field for the address corresponding to the handle passed in (the SOCKET int is mapped by WinSock to an underlying HANDLE, because Windows is barmy and can't just use fds and simple syscalls like everyone else).Nicholas Wilson

2 Answers

8
votes

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.

5
votes

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);