Check for open ports using Java

Using Java, how to check if any TCP / IP port is open and not blocked by a firewall?

+1
source share
3 answers

If the "port is open", you mean that this port can be used by your server application, then you can simply do:

try { serverSocket = new ServerSocket(port); } catch (IOException e) { System.out.println("Could not listen on port: " + port); // ... } 

An IOException is thrown if you cannot open the server socket on this port.

If "not blocked by a firewall", you mean that this port can be accessed from hosts outside your network, then there is no direct way to verify this without trying to open a connection to your host: a port from an external network. There may be other firewalls / NATs between the host where your service is running and the host that may try to connect to your service.

There are some common methods that allow you to check the availability of a service from an external network, for example, NAT bypass .

+1
source

Check if the port is open for incoming connections? You will need to ask for a firewall. Suppose you are listening on a port, but that port is blocked by a firewall and you will wait forever.

The only way out is to start a small server outside of your network / on your computer and ask him to remotely establish a connection to this port on your computer. The remote server can respond (on another channel) if it was able to connect or not.

Another idea: use one of the many port testing services on the Internet. googling "port test online" gives some results.

+2
source

Socket allows you to establish communication between two machines on a network. There may be several filrewalls along the way:

  • personal firewall on both sides
  • company firewalls on both sides.
  • Internet service provider firewalls on both sides.

Firewalls can be configured to block

  • specific IP addresses
  • specific ports
  • certain protocols
  • traffic direction (in / out bound)

In addition, two different situations look the same in terms of TCP:

  • server does not listen on port
  • the firewall blocks the connection (see above)

Soon you should decide what you want to check. If, for example, you just want to know that you can connect to a specific port on a specific machine call new Socket(host, port) and catch exception. If you want to distinguish between a situation that the firewall bothers you or the remote computer is not responding, this is not enough.

In this case, you will need another link. For example, you know that there is an HTTP server on the remote host, and on another proprietary server that can be blocked by the firewall, you can first establish an HTTP connection (to check that the host is alive), and then try to connect to the socket. If HTTP works and the socket, then probably the firewall is not blocking it.

+2
source

All Articles