简体   繁体   English

扫描外国主机的端口

[英]Scanning Foreign Host's Ports

I Im writing a port scanner in java as an educational exercise and I have run into a problem. 我是用Java编写端口扫描程序作为教育活动,但遇到了问题。 My program works fine when im scanning the ports on my local machine, however when i try to scan for ports on foriegn computers the process just freezes. 我在扫描本地计算机上的端口时,我的程序运行良好,但是,当我尝试在foriegn计算机上扫描端口时,该过程将冻结。 Here is the code for my scan method: 这是我的扫描方法的代码:

public void scan(InetAddress ad, int start, int end){
    for(int i=start; i<=end; i++){
        try{
            socket = new Socket(ad, i);
            System.out.println("Port "+i+"is open");
        }catch(Exception e){
            System.out.println("Port "+i+"is not open");
        }
    } 
}

So far it is working when the host name is my loopback address or just "localhost", it even works with my IP Address. 到目前为止,当主机名是我的回送地址或只是“ localhost”时,它就可以使用,甚至可以与我的IP地址一起使用。 But when I for instance resolve the IP for www.google.com or even give it the IP address of my other computer on the same network, the program will freeze after scanning the first port. 但是,例如当我解析www.google.com的IP或什至为它提供同一网络上另一台计算机的IP地址时,该程序将在扫描第一个端口后冻结。

I am resolving the IP address like this: 我正在解析这样的IP地址:

inetAddressObject = InetAddress.getByName(hostNameString);

Can anyone tell me if I am missing a big difference between scanning ports on a local machine and scanning ports on a foreign host? 谁能告诉我我是否错过了本地计算机上的扫描端口与外部主机上的扫描端口之间的巨大区别? Or is there just something simple going wrong with my code ? 还是我的代码出现一些简单的错误?

The way you are calling the Socket constructor the connection will be made right away. 您调用Socket构造函数的方式将立即建立连接。 The problem is that if the connection times out then you will have to wait a while (OS default). 问题是,如果连接超时,那么您将不得不等待一段时间(操作系统默认设置)。 The way you should do it is the following: 您应该执行以下操作:

Socket s = new Socket();
s.connect(new InetSocketAddress(ad, i), timeout);

The separate reason is why it is timing out. 另一个原因是它超时了。 This is because your machine is likely behind a firewall of some sorts and is unrelated to your code example. 这是因为您的计算机可能位于某种类型的防火墙之后,并且与您的代码示例无关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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