服务器套接字 - 仅接受来自白名单中的 IP 地址的连接

2024-03-13

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

... 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
//等等

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


You want to call getpeername http://www.beej.us/guide/bgnet/output/html/multipage/getpeernameman.html to get the address information from the client. Then check if their IP address is found in the whitelist. If not, disconnect them.

为了检查它们的 IP 地址是否在给定范围内,您需要将地址字节转换为一个数字。您可以通过以下方式做到这一点:

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

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

服务器套接字 - 仅接受来自白名单中的 IP 地址的连接 的相关文章

随机推荐