2

I am starting with JAVA Network programming. I have written a server class which uses ServerSocket to listen to port 3333. Following is the code snippet.

try {
            servSock = new ServerSocket(portNumber);
            //servSock.setSoTimeout(100000);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Socket link = null; //Step 2.

        while(true){
            try {
                link = servSock.accept();

This works fine, in that the accept call blocks the program correctly.

But when I connect to the same port from the same machine through the client, using the below code

Socket link = new Socket();
link.connect(new InetSocketAddress(InetAddress.getLocalHost(),3333), 50000);

It throws ConnectionTimedout after a while.

I am not able to connect to the server!. Please help someone.

4
  • 1
    try to print value of InetAddress.getLocalHost(). Also try replacing InetAddress.getLocalHost() with localhost Commented Apr 11, 2015 at 8:23
  • 1
    Wow that worked! :) was struggling with this for 3 hours now. Thanks a lot:) Commented Apr 11, 2015 at 8:29
  • 1
    What is the issue with InetAddress.getLocalhost? at least that is what is there in many tutorial texts. Commented Apr 11, 2015 at 8:30
  • i've mentioned the solution and explanation in an answer. Please accept it! Thanks Commented Apr 11, 2015 at 17:55

1 Answer 1

1

Try to replace InetAddress.getLocalHost() with localhost.

The reason is that InetAddress.getLocalHost() actually returns the hostname of the machine, and the IP address associated with that hostname.

As mentioned here:

InetAddress.getLocalHost() doesn't do what most people think that it does. It actually returns the hostname of the machine, and the IP address associated with that hostname. This may be the address used to connect to the outside world. It may not. It just depends on how you have your system configured.

The javadoc for InetAddress.getLocalHost() is mentioned here.

Hope this helps.

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

Comments

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.