天天看點

java 校驗ip位址有效_驗證IP位址的有效性

packagecom.lzw;importjava.awt.EventQueue;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjavax.swing.JButton;importjavax.swing.JFrame;importjavax.swing.JLabel;importjavax.swing.JOptionPane;importjavax.swing.JPanel;importjavax.swing.JTextField;importjavax.swing.border.EmptyBorder;public class CheckIPAddress extendsJFrame {privateJPanel contentPane;privateJTextField ipField;

public static voidmain(String[] args) {

EventQueue.invokeLater(newRunnable() {public voidrun() {try{

CheckIPAddress frame= newCheckIPAddress();

frame.setVisible(true);

}catch(Exception e) {

e.printStackTrace();

}

}

});

}

publicCheckIPAddress() {

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setBounds(100, 100, 280, 128);

contentPane= newJPanel();

contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));

setContentPane(contentPane);

contentPane.setLayout(null);

JLabel lblip= new JLabel("\u8BF7\u8F93\u5165IP\u5730\u5740\uFF1A");

lblip.setBounds(12, 14, 92, 15);

contentPane.add(lblip);

ipField= newJTextField();

ipField.setBounds(100, 10, 141, 25);

contentPane.add(ipField);

JButton button= new JButton("\u9A8C\u8BC1");

button.addActionListener(newActionListener() {public voidactionPerformed(ActionEvent e) {

do_button_actionPerformed(e);

}

});

button.setBounds(66, 57, 93, 23);

contentPane.add(button);

}protected voiddo_button_actionPerformed(ActionEvent e) {

String text= ipField.getText();//擷取使用者輸入

String info = matches(text);//對輸入文本進行IP驗證

JOptionPane.showMessageDialog(null, info);//用對話框輸出驗證結果

}

publicString matches(String text) {if (text != null && !text.isEmpty()) {//定義正規表達式

String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."

+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."

+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."

+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";//判斷ip位址是否與正規表達式比對

if(text.matches(regex)) {//傳回判斷資訊

return text + "\n是一個合法的IP位址!";

}else{//傳回判斷資訊

return text + "\n不是一個合法的IP位址!";

}

}//傳回判斷資訊

return "請輸入要驗證的IP位址!";

}

}