I'm studing c++ socket programming... The server program binds to a socket and starts listening for connection requests...ok now how can I list the IP addreses of the listened requests? I know I can get the IP addresses after accepting the connections but lets say I don't wanna accept a connection from an specific IP address...
-
1Shouldn't you use a firewall to manage this type of requirement?– Eric J.Commented May 23, 2012 at 20:24
-
1Dude I'm programming !!!– MortieCommented May 23, 2012 at 20:29
-
I agree. This is what the multitudes of router/switch security provisions are for. I think the best you could do is close the connection right away if the IP is on your blacklist.– chrisCommented May 23, 2012 at 20:29
3 Answers
On Windows only, you can use the conditional callback feature of WinSock2's WSAAccept()
function to access client information before accepting a connection, and to even reject the connection before it is accepted.
-
Wow, I wasn't aware of this (though I thought I know winsock2 very well). But I believe this specific things isn't supported natively by the TCP driver.– valdoCommented May 24, 2012 at 4:06
This can't be done in terms of the standard socket API. On all platforms I know, the system actually accepts the connection (i.e. responds with SYN+ACK TCP datagram) before the application has a chance to monitor the pending request.
For optimum performance, this would be solved by filtering in the network stack, but the details of doing that will depend on the operating system (this is not part of the socket interface and your application may generally not even have the rights to configure your network stack this way.)
The other opportunity is after the accept
, by which time the connection is already accepted (CONNECT ACK) on TCP level.
I don't think you can do it in the middle phase where you would prefer that. That however would not be very different from doing it after accept
anyway.
-
I'm not an expert but isn't it dangerous to accept a connection just to get the IP address ?– MortieCommented May 23, 2012 at 20:34
-
@user1378573, at this point it's gone through the firewall and everything set up on the network that do all the checking on IP address etc.– chrisCommented May 23, 2012 at 20:38
-
2@user1378573 - The
accept
call grants no one any new rights. It just makes it possible to access an individual connection on your side through the socket API. The other side can do relatively little to harm you; a denial of service attack, or detecting that your port is open. But they could do the same even if you didn't "accept". You cannot simulate a firewall on app level. Commented May 23, 2012 at 20:49