java socket: listen before accept?

2019-05-23 04:48发布

问题:

The context: I have a table of banned ip adresses, due to DOS attacks, in a collection somewhere in the memory of my program.

I use a TCP server socket, accepting every connection, then I check the ip address, and then I either close the connection or continue processing the client.

I'd like to know if it's possible, in Java, to listen for incomming connections on a TCP server socket, and accept or refuse somehow to establish the tcp link, given the ip address of the requesting client. I mean without having to accept & to close the client socket, which is what I'm already doing.

Thanks.

回答1:

Without using a SecurityManager, you can only accept, then check the incoming IP address, and drop the connection if it's on the banned list. With a SecurityManager, you can have it throw a SecurityException, and give it special handling (such as logging the connection request in a security log in the app).

If you don't want these connections to even hit your server (which I'm guessing is the point), you really want to block it at the firewall level. Once the connection hits your app, it's already taken up the memory and resources necessary to talk to your application, so at that point you've already lost the DOS/DDOS game.

Dropping it before or after an accept doesn't matter, because the connection has already hit the application level of your app. Even with a SecurityManager, it's still increasing the load on your server.



回答2:

You might be able to, but you wouldn't be able to stop them from accessing your system in your Java code anyway.

Your best bet would be, instead of using Java, use something like iptables or some other firewall to drop their packets right away.

The boys over at serverfault can probably help with that better than SO.



回答3:

You can use a SecurityManager with suitable accept SocketPermissions defined, if you can abide having the addresses defined in a .policy file, or writing your own Policy object.

EDIT: but I have to admit that a firewall would be a better solution.