java编写的端口扫描器

Author Avatar
MagicDo 6月 02, 2017
  • 在其它设备中阅读本文章

好久没写java了,学的时候,也没学习网络编程这一块,无意中看到了一本书,于是小小复习一下java,写个端口扫描器,玩玩吧,网上这种小工具有的是,就是自己无聊写着玩玩。

源代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import javax.swing.*;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.*;
public class PortScan extends JFrame {
JPanel center=new JPanel();
Box hBox0=Box.createHorizontalBox();
Box hBox1= Box.createHorizontalBox();
Box hBox2= Box.createHorizontalBox();
Box hBox3= Box.createHorizontalBox();
private JLabel state=new JLabel("关闭");
private JLabel HOST=new JLabel("主机名:");
private JLabel PORT=new JLabel("端口号:");
private JLabel STATE=new JLabel("状态:");
private JButton btn1=new JButton("开始扫描");
private JButton reset=new JButton("重置");
private JTextField host=new JTextField(20);
private JTextField port=new JTextField(7);
Font f1=new Font("隶书",Font.PLAIN,15);
public static void main(String[] args) {
JFrame portscan=new PortScan();
portscan.setVisible(true);
}

public PortScan(){
setTitle("PortScanner");
setSize(300, 200);
center.setLayout(new BoxLayout(center,BoxLayout.Y_AXIS));
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension screenSize = kit.getScreenSize();//获取屏幕分辨率
setLocation(screenSize.width/4,screenSize.height/4);//位置
state.setFont(f1);
HOST.setFont(f1);
PORT.setFont(f1);
btn1.setFont(f1);
reset.setFont(f1);
STATE.setFont(f1);
center.add(hBox0);
center.add(Box.createRigidArea(new Dimension(10,20)));
center.add(hBox1);
center.add(Box.createRigidArea(new Dimension(2,20)));
center.add(hBox2);
center.add(Box.createRigidArea(new Dimension(2,20)));
center.add(hBox3);
hBox0.add(HOST);
hBox0.add(host);
hBox1.add(PORT);
hBox1.add(port);
hBox2.add(btn1);
hBox2.add(reset);
hBox3.add(STATE);
hBox3.add(state);
add(center);
btn1.addActionListener(new MyActionListener());
reset.addActionListener(new MyActionListener());
}
class MyActionListener implements ActionListener{

@Override
public void actionPerformed(ActionEvent e) {
String post1=host.getText();
int port1=Integer.parseInt(port.getText());
if(e.getActionCommand()=="开始扫描"){
if( PortScannerByIP.scan(post1, port1)){
state.setText("开放");
}else{
state.setText("关闭");
}

}
if(e.getActionCommand()=="重置"){
host.setText("");
port.setText("");
}
}


}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
   import java.io.IOException;
import java.net.Socket;


public class PortScannerByIP {

public static boolean scan(String host,int port){
boolean flag=true;
Socket socket=null;
try {
socket=new Socket(host,port);
return flag;
} catch (IOException e) {
flag=false;
return flag;
}finally{
try {
if(socket!=null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}