tags:

views:

1599

answers:

4

I am using the Winsock API (not CAsyncSocket) to make a socket that listens for incoming connections.

When somebody tries to connect, how can I get their IP address BEFORE accepting the connection? I am trying to make it only accept connections from certain IP addresses.

Thanks

+1  A: 

accept the connection, look at the IP, if it is not allowed, close the connection

Edit:

I'm assuming you're talking about TCP connection. When you listen to the port and a connection comes from a client, the API will perform the TCP 3-way handshake, and the client will know that this port is being listened to.

I am not sure if there is a way to prevent sending any packets (i.e. accepting the connection) so that you can look at the IP address first and then decide.

The only way I can think of is to do packet filtering based on the source IP at the network layer (using firewall, for example).

Aziz
A: 

Two reasons why I do not want to accept the connection in order to check the remote IP address:

1). The client would see that there is a listening socket on this port. If i decide to reject the client connection, I would not want them to know that there is a socket listening on this port.

2). This technique is not as efficient and requires more CPU, RAM, and network usage; so it is not good in case of a Denial Of Service attack.

A: 

When using ATM, the CONNECT ACK packet will come from the most recent switch, not the end client. So, you would have to call accept() on the socket, then look at the address (based on the passed addr_family), and at that point just close the socket. By the time it reaches the requester, it will probably just get a failure.

And I'm not sure how many resources you think this will take up, but accepting a connection is at a very low level, and will not really be an issue. It's pretty easy to drop them.

If you come under a DoS attack, your code CAN quit listening for a preset amount of time, so the attacker just gets failures, if you are so worried about it.

Does it really matter if the client knows there is a socket listening? Try using telnet to connect to your localhost on port 137 and see how fast the file sharing in windows drops the connection... (If you even have it enabled, and if I remembered the correct port number.. heh..)

But, at the SOCKET level, you are not going to be able to do what you want. You are talking about getting down to the TCP level, and looking at the incoming connection requests, and deal with them there.

This can be done, but you are talking about a Kernel driver to do it. I'm not sure you can do this in user-mode at all.

If you want Kernel help with this, let me know. I may be able to give you some examples, or guidance.

Just my own two cents, and IMVHO...

LarryF
A: 

SO_CONDITIONAL_ACCEPT socket option. Here

Also, pretty sure it's available in XP and Server 2003, not just Vista.

a_mole