使用 winsock 我希望我的服务器应用程序只接受来自某个(比如说192.168.0.0/24
)子网的连接。
我正在考虑两种选择:
每次
accept
连接时检查客户端的地址。while (true) { SOCKET clientSocket = accept(serverSocket, (SOCKADDR *)&clientAddress, &addressLenght); if (clientSocket == INVALID_SOCKET || clientAddress.sin_addr.S_un.S_un_b.s_b1 != 192 || clientAddress.sin_addr.S_un.S_un_b.s_b2 != 168 || clientAddress.sin_addr.S_un.S_un_b.s_b3 != 0) { closesocket(clientSocket); continue; } ... }
找出相应网络的本地地址并将其用作
name
参数bind
SOCKADDR_IN serverAddress; serverAddress.sin_family = AF_INET; serverAddress.sin_port = htons(13666); serverAddress.sin_addr.S_un.S_addr = inet_addr("192.168.0.1"); result = bind(serverSocket, (SOCKADDR *)&serverAddress, sizeof(serverAddress));
我还有什么其他选择?
PS:有人告诉我有更好的解决方案。但我无法弄清楚。