如何利用Java线程池实现TCP端口扫描

2018-8-24

一个简单的利用线程池技术实现端口扫描(TCP)的java程序,关键代码如下:


// 扫描本机

private void gocal()

{

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 {

IAddress addr = IAddress.gocalHost();

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();

}







暗色背景
手机扫码阅读本页