好久沒寫java了,學的時候,也沒學習網路程式設計這一塊,無意中看到了一本書,於是小小複習一下java,寫個埠掃描器,玩玩吧,網上這種小公具有的是,就是自己無聊寫著玩玩。
原始碼如下:
共兩個類,比較簡單奧
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(""); } } } }
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(); } } } }
執行截圖: