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;/*** Launch the application.*/

public static voidmain(String[] args) {

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

CheckIPAddress frame= newCheckIPAddress();

frame.setVisible(true);

}catch(Exception e) {

e.printStackTrace();

}

}

});

}/*** Create the frame.*/

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);//用对话框输出验证结果

}/*** 验证ip是否合法

*

*@paramtext

* ip地址

*@return验证信息*/

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地址!";

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值