Reputation: 63
Is it possible to create a ServerSocket where instead of using the ServerSocket#accept method for any connection, the ServerSocket waits and accepts a connection only from a specific IP?
Or, alternatively, is it possible to know the IP of a connection before accepting it so that I can reject it if it is not from that specific IP?
Upvotes: 1
Views: 1170
Reputation: 2303
Not sure in java, but in c or python it is possible. With level 3 raw socket, you can prevent a connection, by responding SYN
packets with RST
packet, before accepting it.
Upvotes: 0
Reputation: 614
You shouldn't rely on the source IP, as it is easy to send TCP/IP packets with the same IP from another host, see IP spoofing. You need to use SSL sockets and some authentication over it.
Upvotes: 1
Reputation: 83
Don't have a lot of experience with ServerSocket in specific, but have some with TCP sockets. I do not think this is possible, however what you can do is verify the IP address after an accept (both TCP and UDP sockets receive the IP of the other machine, since it is necessary to provide a response).
I do not see the reason you would do this (especially considering that IPs, usually, change dynamically over time for many reasons) and if there is another way to solve the problem you have.
Upvotes: 0
Reputation: 1132
No. The underlying communication stack does not support such a thing for TCP sockets.
The accept call itself returns a socket which can then be queried for the remote IP address. You can then immediately close the socket if the IP is not to your liking.
(By the way, what you accept is a 'connection', not a 'socket'. The socket is merely a local data structure, one at each endpoint; the socket is created on your machine in response to accepting a connection. It's the difference between your telephone and the conversation with the person at the other end.)
Upvotes: 1