English 中文(简体)
• 如何确定客户与INADDR-ANY听众在C中使用的IP
原标题:How to determine IP used by client connecting to INADDR_ANY listener socket in C

我的网络服务器应用在C中书写,听众必须使用INADDR_。 纽约市通过安装的东道国的任何IP地址接收连接。

我需要确定哪一个服务器的IP地址是客户在建立链接时使用的,实际上,我需要知道它们是否通过反馈地址127.0.0.1连接。

部分代码样本如下(如果能够帮助的话,我可以全文):

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

解决我的具体问题(如果任何人需要的话)如下:

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;
}
最佳回答

您可使用getsockname功能。

磁盘名称功能检索了特定袖珍名称的当地名称。

问题回答

摘自法典

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

分析返回的客户。 这是你们所需要的。





相关问题
Fastest method for running a binary search on a file in C?

For example, let s say I want to find a particular word or number in a file. The contents are in sorted order (obviously). Since I want to run a binary search on the file, it seems like a real waste ...

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

Tips for debugging a made-for-linux application on windows?

I m trying to find the source of a bug I have found in an open-source application. I have managed to get a build up and running on my Windows machine, but I m having trouble finding the spot in the ...

Trying to split by two delimiters and it doesn t work - C

I wrote below code to readin line by line from stdin ex. city=Boston;city=New York;city=Chicago and then split each line by ; delimiter and print each record. Then in yet another loop I try to ...

Good, free, easy-to-use C graphics libraries? [closed]

I was wondering if there were any good free graphics libraries for C that are easy to use? It s for plotting 2d and 3d graphs and then saving to a file. It s on a Linux system and there s no gnuplot ...

Encoding, decoding an integer to a char array

Please note that this is not homework and i did search before starting this new thread. I got Store an int in a char array? I was looking for an answer but didn t get any satisfactory answer in the ...

热门标签