简体   繁体   中英

Java - socket.isConnected returns true to ANY ip address using port 80

I am trying to establish communication with a device on my local network via the use of Socket , and verify the connection using the Socket.isConnected() method - seems simple enough, but I am getting some strange behavior.

Currently, I instantiate an unconnected socket with the no-arg Socket() constructor, and then, when ready, connect to the server (which is on port 80 for the device). Here is a snippet of the code:

deviceSocket = new Socket();
...
SocketAddress deviceSocketAddress = new InetSocketAddress(hostName, portNum);
deviceSocket.connect(deviceSocketAddress);
if (deviceSocket.isConnected()){
     System.out.println("Connected to "+hostName+":"+portNum);
}

As mentioned, the portNum that I must connect to on the device is 80, but regardless of the hostName that is provided, it always returns true . If I give an ip address of 10.0.1.115 (which is the address of the device), I get the same result as when I provide 10.0.1.114, or even something bogus like 13.2.5.2.

I've already done some research and have found that the Socket.isConnected() method will return true if the socket has ever been successfully connected, but that is not my issue, I've made sure that in each case I am starting with a brand-new unconnected socket.

I decided to take my issues to telnet, in which I noticed something very peculiar. If the command telnet xxx.xxx.xxx.xxx 80 is issued in the command prompt, it always opens a blank page, which hangs for a while and then exits back to command prompt, rather than giving the appropriate error message (assuming the endpoint really doesn't exist)

Connecting to 13.2.5.2... Could not open connection to the host, on port 82: Connect failed

(Also, something else strange, using port 81 behaves the same way, it is only when I used 82, or another random port, that the connection failed)

So I think I've stumbled upon an interesting issue, but we'll see soon enough...

Thanks in advance for any and all replies!

-M

I cannot replicate this behavior but here's a guess.

Your firewall allows port 80 (http) and 81 (often used as a http alternate). These ports try, then fail to connect after a timeout. Other ports that are not open in the firewall (like 82) are rejected immediately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM