开发者

How to determine IP used by client connecting to INADDR_ANY listener socket in C

开发者 https://www.devze.com 2023-01-03 18:45 出处:网络
I have a network server application written in C, the listener is bound using INADDR_ANY so it can accept connections via any of the IP addresses of the host on which it is installed.

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

I need to determine which of the server's IP addresses the client used when establishing its connection - actually I just need to know whether they connected via the loopback address 127.0.0.1 or not.

Partial code sample as follows (I can post the whole thing if it helps):

static struct sockaddr_in serverAddress;
serverAddress.sin_fam开发者_JAVA百科ily = 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 anyone 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;
}


You can use the getsockname function.

The getsockname() function retrieves the locally-bound name of the specified socket


From your code

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

Analyse the returned clientAddress. This is what you need.

0

精彩评论

暂无评论...
验证码 换一张
取 消