操作Java线程池技能实现TCP端口扫描
一个简朴的操作线程池技能实现端口扫描(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();
}