Linux TCP Server: Read Client IP Address Before Accepting Connection

Related: C ++ Winsock API how to connect to an IP client before accepting a connection?

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

As far as I know, you should accept first connect and shutdown immediately after that, if you do not want to contact this client because of its IP address.

Pseudocode (I'm 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)); } } 
+4
source share
2 answers

I think you are trying to do this to prevent TCP negotiation if it matches a specific IP. As far as I know, this is not possible in the socket layer. TCP negotiations will take place, and by the time you arrive to accept the socket, negotiations have already taken place.

It is technically possible that you could somehow look into this state information, but this will not do what you expect from it. Accepting a socket is the interface between the kernel that was already doing the work and your program that would like to read the data. The simplest thing is to accept the socket and load it if you do not want it.

If you want to avoid TCP negotiation first, you need to use iptables.

+3
source

Such an API is not available for TCP sockets w / BSD. Suggestions: use tcp-wrappers or iptables for heavy lifting. One of them is more automatic than the other.

UDP allows you to use MSG_PEEK, which can allow you to see who it is happening to with recvfrom, but you still have to read the packet anyway, so this is not a win.

+1
source

All Articles