在Java编程中,如何扫描打开的端口(是否被使用)?
以下示例显示如何通过创建 Socket
对象来检查主机上打开或正在使用的端口(相当于一个简单的端口扫描器)。
package com.yiibai;
import java.net.*;
import java.io.*;
public class CheckPort {
public static void main(String[] args) {
Socket Skt;
String host = "localhost";
if (args.length > 0) {
host = args[0];
}
for (int i = 100; i < 1024; i++) {
try {
System.out.println("Looking for " + i);
Skt = new Socket(host, i);
System.out.println("There is a server on port " + i + " of " + host);
} catch (UnknownHostException e) {
System.out.println("Exception occured" + e);
break;
} catch (IOException e) {
}
}
}
}
Java
上述代码示例将产生以下结果 -
......
Looking for 133
Looking for 134
Looking for 135
There is a server on port 135 of localhost
Looking for 136
Looking for 137
Looking for 138
......
原文地址:https://www.cnblogs.com/borter/p/9617177.html
时间: 2024-11-14 04:09:03