Java socket block connected to the server
I'm trying to connect to the server using java sockets I'm trying to connect from port 80 to port 90
int port; Socket clientsocket; String hostname = "www.google.com"; for(port = 80;port<=90; port++){ try{ clientsocket = new Socket(hostname,port); System.out.println("Connection at port " + port + "\t" + clientsocket.isConnected()); clientsocket.close(); } catch(Exception e){ System.out.println(e.getMessage()); } }
When I try to connect to any website, such as Google Com or W3Schools COM, my program hangs the socket () call port number, except 80 Since these websites are not running on port 81-90, it should throw an exception, but it will be blocked For port 80, it works normally When I try to connect to the Apache server installed on my machine, it will not block any port number and give me a connection rejection error, which is an obvious behavior So why? Thank you in advance
Solution
This is almost certainly not Java practice
When you call the socket (string, int) constructor, the JVM will ask the operating system to try to establish a connection with the IP address corresponding to the provided name using the provided port number Suppose we are discussing TCP / IP, the operating system will send a TCP "syn" message and wait for a response:
>If the response is' syn-ack ', continue to establish the connection according to the protocol; see http://en.wikipedia.org/wiki/Transmission_Control_Protocol#Connection_establishment. >If the response is' RST '(reset), the connection fails, which will cause a Java "connection rejected" exception (this usually happens when 'syn' enters the remote server, but it is found that there is no "listening" Application on the port you are trying to connect.) > If the response is an ICMP message (for example, ICMP target unreachable), it will usually cause the connection request to fail immediately and cause a Java exception. > If there is no response, the operating system will try again and try again Depending on the Java default connection timeout (or explicit timeout), this process may take a long time
So the most likely thing to happen is to filter out "syn" messages on a fashionable port and simply discard them It may be the local firewall software on the PC, the firewall software in the gateway, or the network of the ISP, or the software in the remote system you are trying to communicate with Or this may happen in the 'syn - ack' message that comes back
Either way, blocking / timeout behavior is inherent in TCP / IP networks and cannot be accurately diagnosed at the OS or Java level You just need to adjust your expectations (or set a shorter connection timeout...)