Server socket - accept connections only from IP addresses in the whitelist

心不动则不痛 提交于 2019-12-07 02:15:31

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.

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

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

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

Not sure what the question is here, or rather what the problem is. The client's address will be in their_addr, so just search your whitelist for that. If not found, close. You will probably want to either convert their_addr into the same format as your whitelist entries, or possibly vice versa.

On Windows only, you can use WSAAccept() instead of accept(). WSAAccept() has a parameter that you can pass a callback function to. Before a new connection is accepted, the callback is invoked with the addresses and QOS values for that connection. The callback can then return CF_ACCEPT, CF_DEFER, or CF_REJECT as needed.

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