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

一个人想着一个人 提交于 2020-01-02 08:06:06

问题


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_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 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;
}

回答1:


You can use the getsockname function.

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




回答2:


From your code

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

Analyse the returned clientAddress. This is what you need.



来源:https://stackoverflow.com/questions/3047704/how-to-determine-ip-used-by-client-connecting-to-inaddr-any-listener-socket-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!