1

I am writing a messaging application in java using sockets and currently the server will wait for a request and just automatically accept it:

ServerSocket s = new ServerSocket(1254);
Socket s1 = s.accept();

If there any way in which I can detect requests to the server and allow the server to only accept certain requests?

9
  • How would you want to distinguish one request from another? Originating IP? Commented Jun 26, 2017 at 11:27
  • 3
    Not before you accept it. So accept it then filtrer it (based on your condition). Passing the Socket to a distinct Thread to let the ServerSocket accept the next one is better too. Commented Jun 26, 2017 at 11:28
  • It depends on your criteria. Commented Jun 26, 2017 at 11:29
  • servlet filters, for example Commented Jun 26, 2017 at 11:30
  • a socket is a low level object. Unless you are working with devices that can't support http, I would go other routes Commented Jun 26, 2017 at 11:32

2 Answers 2

1

It's unclear to me what you mean with "certain requests", however you can accept it, validate it and if it is not a "certain request" you simply drop the connection.

Sign up to request clarification or add additional context in comments.

3 Comments

this answer should have been a comment mate
@nafas Why? It provides a solution, and a solution that is also provided in another answer that you haven't commented on.
@iehrlich It does provide a solution: "you can accept it, validate it and if it is not a "certain request" you simply drop the connection."
1

AFAIK there is no way that you can deny request without accepting it, (until and unless you have some reverse proxy setup like nginx).

After accepting the socket you can check out the various parameters for example Socket's remote address (check for more info java.net.Socket), and close the socket if you don't want the connection to be established.

2 Comments

Just to add some context, if the idea is to secure your process to prevent an overflood by robot, you can always add some rules to your firewall to only accept some IP range, based on the application of this socket of course
@AxelH (+1) thanks for your comment but for that point only I edited my answer and added 'until and unless you have some reverse proxy setup like nginx,` and off course firewall can be one more option from so many others available....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.