C#小结之网络
public bool Ping(string ip) { int timeout = 1000; string data = "Test Data!"; System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.PingOptions(); options.DontFragment = true; byte[] buffer = Encoding.ASCII.GetBytes(data); System.Net.NetworkInformation.PingReply reply = p.Send(ip, timeout, buffer, options); if (reply.Status == System.Net.NetworkInformation.IPStatus.Success) return true; else return false; }
/// <summary> /// 得到本机IP /// </summary> private string GetLocalIP() { //本机IP地址 string strLocalIP = ""; //得到计算机名 string strPcName = Dns.GetHostName(); //得到本机IP地址数组 IPHostEntry ipEntry = Dns.GetHostEntry(strPcName); //遍历数组 foreach (var IPadd in ipEntry.AddressList) { //判断当前字符串是否为正确IP地址 if (IsRightIP(IPadd.ToString())) { //得到本地IP地址 strLocalIP = IPadd.ToString(); //结束循环 break; } } //返回本地IP地址 return strLocalIP; } //得到网关地址 private string GetGateway() { //网关地址 string strGateway = ""; //获取所有网卡 NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); //遍历数组 foreach (var netWork in nics) { //单个网卡的IP对象 IPInterfaceProperties ip = netWork.GetIPProperties(); //获取该IP对象的网关 GatewayIPAddressInformationCollection gateways = ip.GatewayAddresses; foreach (var gateWay in gateways) { //如果能够Ping通网关 if (IsPingIP(gateWay.Address.ToString())) { //得到网关地址 strGateway = gateWay.Address.ToString(); //跳出循环 break; } } //如果已经得到网关地址 if (strGateway.Length > 0) { //跳出循环 break; } } //返回网关地址 return strGateway; } /// <summary> /// 判断是否为正确的IP地址 /// </summary> /// <param name="strIPadd">需要判断的字符串</param> /// <returns>true = 是 false = 否</returns> public static bool IsRightIP(string strIPadd) { //利用正则表达式判断字符串是否符合IPv4格式 if (Regex.IsMatch(strIPadd, "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}")) { //根据小数点分拆字符串 string[] ips = strIPadd.Split('.'); if (ips.Length == 4 || ips.Length == 6) { //如果符合IPv4规则 if (System.Int32.Parse(ips[0]) < 256 && System.Int32.Parse(ips[1]) < 256 & System.Int32.Parse(ips[2]) < 256 & System.Int32.Parse(ips[3]) < 256) //正确 { //if (strIPadd.Substring(0, 7) == "172.16.") //{ return true; //} //else //{ // MessageBox.Show("IP必须处于T网状态,为172.16.xxx.xxx", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning); // return false; //} } //如果不符合 else //错误 return false; } else //错误 return false; } else //错误 return false; } /// <summary> /// 尝试Ping指定IP是否能够Ping通 /// </summary> /// <param name="strIP">指定IP</param> /// <returns>true 是 false 否</returns> public static bool IsPingIP(string strIP) { try { //创建Ping对象 Ping ping = new Ping(); //接受Ping返回值 PingReply reply = ping.Send(strIP, 1000); //Ping通 return true; } catch { //Ping失败 return false; } }