title: Cannot connect Java socket server and client
body: <p>I am learning about socket programming with Java. Using Java 8, have this simple server:</p>
  
  <pre><code>import java.net.InetAddress;
  import java.net.ServerSocket;
  import java.net.Socket;
  
  public class Main {
      public static void main(String[] args) throws Exception {
          System.out.println("MY IP address is " + InetAddress.getLocalHost().getHostAddress());
          ServerSocket server     = new ServerSocket(4031);
          Socket socket           = server.accept();
          System.out.println("Yay somebody connected! " + socket);
          socket.close();
          server.close();
      }
  }
  </code></pre>
  
  <p>All it does is show the host's address and then wait for a socket to connect.</p>
  
  <p>And have this client:</p>
  
  <pre><code>import java.net.Socket;
  
  public class Main {
      public static void main(String[] args) throws Exception {
          System.out.println("Trying to connect...");
          Socket s = new Socket("123.456.7.890", 4031);
          System.out.println("Cool");
          s.close();
      }
  }
  </code></pre>
  
  <hr>
  
  <p>When I run the server and the client in my house (in two different computers), this works: I simply grab the IP address displayed by the server, supply it to the client, and the connection is established.</p>
  
  <p>Now I have this same server in my house, whereas I am running my client in the office. Under the same process, I supplied the IP address printed by the server to my client. However, the connection is never established: neither the server or the client generate a socket.</p>
  
  <ul>
  <li>Happens with both Java 7 and 8.</li>
  <li>Tried several different ports.</li>
  <li>No exceptions are thrown. Both programs just hang in there, waiting.</li>
  <li>I am using Mac OSX Mavericks 10.9.5 on both machines.</li>
  <li>The firewalls are turned off on both machines.</li>
  <li>They are indeed connected to the internet. In fact, I used Chrome Remote Desktop to control the server and check its status.</li>
  <li>This works fine when both machines are in the same house. But not when one is in the house and another somewhere else.</li>
  <li>And yes, this works for localhost too.</li>
  </ul>
  
  <p>The above points seem to suggest that the issue is with the IP address I used to connect to my server. Maybe <code>InetAddress.getLocalHost().getHostAddress()</code> is not suitable for this - although it puzzles me why does this work with two machines in the same house.</p>
  
  <p>What is it that I'm doing wrong?</p>