服务器套接字-仅接受来自白名单中IP地址的连接 [英] Server socket - accept connections only from IP addresses in the whitelist

查看:189
本文介绍了服务器套接字-仅接受来自白名单中IP地址的连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个套接字服务器,它侦听并接受来自客户端的连接,其工作方式如下:

I have a socket server that listens and accepts connections from client, which works as follow:

... do some pre-processing (socket, binds, etc)
//listen to client
if (listen(sockfd, BACKLOG) == -1) {
        perror("listen");
        exit(1);
}

printf("server: waiting for connections...\n");

while(1) {  // main accept() loop
    sin_size = sizeof client_addr;
    new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
    if (new_fd == -1) {
        perror("accept");
        continue;
    }
     //do something .....
    .....
}

如何限制服务器,使其仅接受来自特定IP地址的连接?例如,我可以创建一个文本文件,其中包含要接受的IP地址白名单,格式如下:
202.168.2.5-202.168.2.127
92.104.3.1-92.104.4.254
//等等

How can I restrict the server so it only accepts connection from specific IP addresses? For instance, I can create a text file containing a white list of IP addresses to accept, in the following format:
202.168.2.5 - 202.168.2.127
92.104.3.1 - 92.104.4.254
//and so on

因此,基本上,我想拒绝来自白名单中未包含的所有IP地址的连接.如果套接字库API不支持此功能,那么我可以接受先接受连接的想法,如果对等地址不在白名单中,请立即关闭socketfd.但是如何执行此操作,如何检查特定IP地址是否在我的白名单中指定的范围内?任何示例将不胜感激.

So basically I want to reject connection from all the IP addresses not included in the whitelist. If the socket library API does not support this, I am okay with the idea of accepting the connections first, then just immediately close the socketfd if the peeraddress is not in the whitelist. But how to perform this, how can I check that a specific IP address is within the range specified in my whitelist? Any examples would be appreciated.

推荐答案

您要致电

You want to call getpeername to get the address information from the client. Then check if their IP address is found in the whitelist. If not, disconnect them.

为了检查其IP地址是否在给定范围内,您想将地址字节转换为一个数字.您可以执行以下操作:

In order to check that their ip address lies within a given range, you want to convert the address bytes into one number. You can do that with the following:

unsigned int n = bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3];

如果地址范围的下限是A,上限是B,并且客户端的ip地址是X,则它们被白名单列出if (A <= X && X <= B).

If the lower bound of the address range is A, and the upper bound is B, and the client's ip address is X, then they are white listed if (A <= X && X <= B).

如果每个IP地址范围测试为false,则它们不在白名单中,您应该断开它们的连接.

If each range of ip addresses tests false, then they aren't on the white list and you should disconnect them.

这篇关于服务器套接字-仅接受来自白名单中IP地址的连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆