Ping一个IP地址是否有效



先导入两个命名空间:

using System.Text.RegularExpressions; //Ping using System.Net.NetworkInformation; //Regex

下面是ping按钮的单击事件:

/// /// Ping IP /// /// 【Ping一个IP地址是否有效】 /// private void btnPing_Click(object sender, EventArgs e) { //输入的IP是否是有效 string ip = txtIP.Text.Trim(); bool bIP = IsLegitimateIP(ip); if (!bIP) { MessageBox.Show("无效的IP地址!"); txtIP.Focus(); txtIP.SelectAll(); return; } //Ping IP Ping ping = new Ping(); PingReply reply = ping.Send(ip); if (reply.Status != IPStatus.Success) { MessageBox.Show("Ping失败!"); txtIP.Focus(); txtIP.SelectAll(); return; } else { MessageBox.Show("Ping成功!"); } } /// /// 通过正则表达式判断是否是合法的IP地址 /// /// 输入的IP地址 /// private bool IsLegitimateIP(string strIP) { string strReg = @"(\d{1,2}|1 \d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])"; if (Regex.IsMatch(strIP, strReg)) { return true; } else { return false; } }

下面是效果图:



源码下载地址: http://download.csdn.net/detail/zhangyaowen123123/3626325

    推荐阅读