Skip to content

Instantly share code, notes, and snippets.

@viko16
Last active December 20, 2015 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save viko16/6200573 to your computer and use it in GitHub Desktop.
Save viko16/6200573 to your computer and use it in GitHub Desktop.
巧妙验证是否ip
using System.Net;
try
{
IPAddress ipTest = IPAddress.Parse(txtBox1.Text);//string转化为ip地址
}
catch (Exception)
{
toolTip1.Show("ip有误", txtBox1, 2000); //2000是提示显示的时间,单位毫秒
}
using System.Net;
string sqlip = txtBox1.Text.Trim();
try
{
IPAddress ipTest = IPAddress.Parse(sqlip);//如果不能转化为有效ip则抛出异常
string pattrn = @"((?:(?: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 (!System.Text.RegularExpressions.Regex.IsMatch(sqlip, pattrn)) //正则判断
{
throw new Exception();
}
toolTip1.Show("ip正确", txtBox1, 2000); //ip正确
}
catch (Exception)
{
toolTip1.Show("ip好像有点问题,请检查", txtBox1, 2000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment