Java socket blocks on connection to a server

When I try to connect to any website like google.com or w3schools.com my program hangs on the socket() call for port numbers except 80. Since those websites are not serving on ports 81-90 it should raise exception but instead it gets blocked.

This is almost certainly not Java's doing.

When you invoke the Socket(String, int) constructor, the JVM asks the OS to attempt to establish a connection to the IP address corresponding to the supplied name, using the supplied port number. Assuming that we're talking TCP/IP, the OS sends off a TCP 'SYN' message, and waits for a response:

  • If the response is a 'SYN-ACK', it proceeds to establish the connection as per the protocol; see http://en.wikipedia.org/wiki/Transmission_Control_Protocol#Connection_establishment.

  • If the response is an 'RST' (reset), the connect fails and this results in a Java "connection refused" exception. (This is typically what happens if the 'SYN' makes it to the remote server, only to discover that there is no application "listening" on the port you tried to connect on.)

  • If the response is an ICMP message of some kind (e.g. ICMP destination unreachable), this typically results in an immediate failure of the connection request, and a Java exception.

  • If there is no response, the OS tries again, and again, and again. Depending on the Java default connect timeout (or the explicit timeout), this process could continue for a long time.

So what is most likely happening is that something is filtering the 'SYN' messages on funky ports, and simply throwing them away. It could be the local firewall software on your PC, firewall software in your gateway, or your ISP's network, or software in the remote system you are attempting to talk to. Or this could be happening to the 'SYN-ACK' message coming back.

Either way, the blocking / timeout behavior is inherent to TCP/IP networking, and it is impossible to accurately diagnose at either the OS or Java levels. You simply need to adjust your expectations. (Or set a shorter connect timeout ...)