开发者

Check for open ports with Java

开发者 https://www.devze.com 2023-02-08 01:37 出处:网络
Usin开发者_开发问答g Java, how do I check if a specific TCP/IP port is open and not blocked by a firewall?If by \"port is open\" you mean, that this port can be used by your server application, then y

Usin开发者_开发问答g Java, how do I check if a specific TCP/IP port is open and not blocked by a firewall?


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

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

IOException will be thrown, if you cannot open server socket on this port.

If by "not blocked by a firewall" you mean, that this port can be accessed from hosts outside your network, then there's no straight way to check this without trying to open connection to your host:port from outside network. There may be other firewalls / NATs between host where your service is started, and host, which may try to connect to you service.

There are some common techniques which allow to check service accessibility from outside network, see, for example, NAT traversal.


Check if a port is open for inbound connections? You'll have to ask the firewall. Suppose, you listen to a port but this port is blocked by the firewall, then you'll wait "forever".

The only way out - run a small server outside your network/your machine and ask it remotly to establish a connection to a given port on your machine. The remote server can reply (on a different channel) if it was able to connect or not.

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


Socket allows connection between 2 machines in the network. There may be several filrewalls on this way:

  1. personal firewall on both sides
  2. firewalls of the companies on both sides.
  3. firewalls of the ISPs on both sides.

Firewalls may be configured to block

  1. certain IPs
  2. certain ports
  3. certain protocols
  4. traffic direction (in/out bound)

Moreover 2 different situations look the same from TCP point of view:

  1. server is not listening to the port
  2. firewall blocks the connection (see above)

Shortly first you have to decide what do you want to test. If for example you just want to know that you can connect to specific port on specific machine call new Socket(host, port) and catch exception. If you want to distinguish between situation that firewall bothers you or the remote has does not respond it is not enough.

In this case you need some other reference. For example you know that remote host has HTTP server on it and some other proprietary server that can be blocked by firewall you can first establish HTTP connection (to check that host is alive) and then try to connect to the socket. If HTTP works and socket does not probably firewall is blocking it.

0

精彩评论

暂无评论...
验证码 换一张
取 消