How to determine the IP address used by the client to connect to the INADDR_ANY listener socket in C

I have a network server application written in C, the listener is connected to INADDR_ANY, so it can accept connections through any of the IP addresses of the host on which it is installed.

I need to determine which of the server’s IP addresses is used by the client when establishing its connection - in fact, I just need to know whether they are connected through the loopback address 127.0.0.1 or not.

An example of partial code is as follows (I can post everything if that helps):

static struct sockaddr_in serverAddress;
serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.s_addr = INADDR_ANY;
serverAddress.sin_port = htons(port);

bind(listener, (struct sockaddr *) &serverAddress, sizeof(serverAddress));

listen(listener, CONNECTION_BACKLOG);

SOCKET socketfd;
static struct sockaddr_in clientAddress;
...
socketfd = accept(listener, (struct sockaddr *) &clientAddress, &length);

The solution to my specific problem (thanks to zildjohn01) in case someone needs it is shown below:

int isLocalConnection(int socket){
    struct sockaddr_in sa;
    int sa_len = sizeof(sa);
    if (getsockname(socket, &sa, &sa_len) == -1) {
        return 0;
    }
    // Local access means any IP in the 127.x.x.x range
    return (sa.sin_addr.s_addr & 0xff) == 127;
}
+3
source share
2

getsockname.

getsockname()

+8

socketfd = accept(listener, (struct sockaddr *) &clientAddress, &length);

clientAddress. , .

0

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


All Articles