Linux TCP server: reading client's IP address before accepting connection

时光怂恿深爱的人放手 提交于 2019-12-30 09:29:07

问题


Related: C++ Winsock API how to get connecting client IP before accepting the connection?

Hi, when you are running a TCP server (written in C, using the Berkeley Socket API) is it possible to read a client's IP address/port before actually accepting the connection?

As far as I know you have to accept the connection first and shutdown it directly thereafter, if you don't want to communicate with a given client because of its IP address.

Pseudo-code (I am looking for the peek and refuse method):

 int serverfd = listen(...);
 for(;;) {
     struct sockaddr_in clientAddr;
     peek(serverfd, &clientAddr, sizeof(clientAddr));
     if(isLegit(&clientAddr)) {
         int clientfd = accept(serverfd, &clientAddr, sizeof(clientAddr));
         handleClient(clientfd);
     } else {
         refuse(serverfd, &clientAddr, sizeof(clientAddr));
     }
 }

回答1:


I think what your trying to do is prevent the TCP negotiation from occurring if it matches a specific IP. As far as I know, that is not possible at the sockets layer. The TCP negotiation will occur, and by the time you come to accept the socket, the negotiation has already happened.

Technically it is possible that you could somehow peek at that state information, but, it wouldn't be doing what you expect it to do. Accepting the socket is the interface between the kernel, which already did the work, and your program which would like to read the data. The easiest thing to do is accept the socket, and boot it if you don't want it.

If you want to prevent the TCP negotiation from occurring in the first place, you need to use iptables.




回答2:


No such API is available for TCP w/ BSD sockets. Suggestions: use tcp-wrappers or iptables to do the heavy lifting. One is more automatic than the other.

UDP allows you to use MSG_PEEK which might let you see who it is from with recvfrom, but you are still going to have to read the packet off anyway, so that is no win.



来源:https://stackoverflow.com/questions/6418603/linux-tcp-server-reading-clients-ip-address-before-accepting-connection

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