使用 Java 检查开放端口 [英] Check for open ports with Java

查看:34
本文介绍了使用 Java 检查开放端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Java,如何检查特定 TCP/IP 端口是否打开且未被防火墙阻止?

Using 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.

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

如果未被防火墙阻止"是指可以从网络外部的主机访问该端口,那么如果不尝试从外部网络打开到您的主机的连接,就没有直接的方法来检查这一点.启动您的服务的主机和可能尝试连接到您的服务的主机之间可能存在其他防火墙/NAT.

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.

有一些常用技术可以检查来自外部网络的服务可访问性,例如,请参见 NAT 遍历.

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

这篇关于使用 Java 检查开放端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆