一個簡單的利用線程池技術實現端口掃描(TCP)的小程序:
關鍵代碼如下:
// 掃描本機
private void getLocal()
{
String ip = getIP();
String portStart = txPortStart1.getText().trim();
String portEnd = txPortEnd1.getText().trim();
if (portStart.length() == 0 || portEnd.length() == 0)
return;
int s = 0;
int e = 0;
try {
s = Integer.valueOf(portStart);
e = Integer.valueOf(portEnd);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "端口輸入有誤");
return;
}
// 檢查端口是否超出范圍
if (! (checkPort(s) && checkPort(e)))
{
JOptionPane.showMessageDialog(null, "端口應該大於0而小於65535");
return;
}
scann(ip, s, e);
runThread(); // 啟動線程, 監視掃描是否已完成
}
private String getIP()
{
try {
InetAddress addr = InetAddress.getLocalHost();
return addr.getHostAddress().toString(); // ip
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, "獲取IP出錯!");
}
return null;
}
// 掃描單個IP
private void scann(String ip, int startPort, int endPort)
{
// 將所有按鈕設為不可用
setBtnEdit(false);
status.setText("請稍候...");
String[] add = {ip, ""};
table.addRow(add);
exec = Executors.newFixedThreadPool(10);
for (int i = startPort; i <= endPort; i++)
exec.execute(new RunSocket(ip, i));
exec.shutdown();
}