天天看点

C# 判断是否是合法的IP地址

添加 using System.Text.RegularExpressions;

Regex rx = new Regex(@"((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))");
            if (rx.IsMatch("192.1682.13.2"))
            {
                 MessageBox.Show("Is IP address");
            }
            else
            {
                 MessageBox.Show("Is not IP address");
            }      

网上有这个方法,不过亲测不成功!

IPAddress ip;

            if (IPAddress.TryParse("192.168.88.1", out ip) == true)
            {
                MessageBox.Show("合法");
            }
            else
            {
                MessageBox.Show("非法");
            }