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