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

2

7

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));
     }
 }
Gracchus answered 20/6, 2011 at 23:11 Comment(1)
I did a bunch of research because I'm reasonably certain I once saw an ioctl for this. No dice. I don't think it can be done either.Describe
C
5

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.

Carillo answered 20/6, 2011 at 23:23 Comment(0)
E
1

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.

Ephesian answered 20/6, 2011 at 23:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.