以下代码是在学习过程中,网上查到的。如果有版权问题,请联系删帖!!!

 在网上找到了两种方法

一种是直接使用 .net的类,测试后发现比如输入数字 8,

会自动变成 0.0.0.8

而这种格式并非我们所要的。

所有直接使用.net类会存在这样的坑

 

后面用了正则表达式的方法,亲测是可用的。

下面就是所有代码

 

作为一个正在学习的人,网上看到的很多代码都是某些

功能的部分代码。让人摸不着头脑。

所以放上所有代码

 

使用正则表达式(亲测可用)

 

 1 using system;
 2 using system.collections.generic;
 3 using system.componentmodel;
 4 using system.data;
 5 using system.drawing;
 6 using system.linq;
 7 using system.text;
 8 using system.windows.forms;
 9 //引用判断ip地址的命名空间system.text.regularexpressions;
10 using system.text.regularexpressions;
11 namespace c_sharp连接s7_1200plc
12 {
13     public partial class form1 : form
14     {
15         public form1()
16         {
17             initializecomponent();
18         }
19 
20         private void btnipaddresswrite_click(object sender, eventargs e)
21         {
22             //获取输入的ip信息
23             string stripaddress = txtipaddress.text;
24             if (isip(stripaddress.trim()))
25             {
26                 messagebox.show("ip地址正确");
27 
28             }
29             else
30             {
31                 messagebox.show("ip地址错误");
32             }
33         }
34 
35       
36         /// <summary>
37         /// 验证ip地址是否合法
38         /// </summary>
39         /// <param name="ip">要验证的ip地址</param>
40         /// <returns></returns>
41         public static bool isip(string ip)
42         {
43             //如果为空,认为验证不合格
44             if(string.isnullorempty(ip))
45             {
46                 return false;
47             }
48 
49             //清除要验证字符传中的空格
50             ip=ip.trim();
51 
52             //模式字符串,正则表达式
53             string patten = @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$";
54 
55             //验证
56             return regex.ismatch(ip,patten ); 
57         }
58     }
59 }