using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; namespace Sog { public static class NetUtils { public static string GetHostIp() { string hostname = Dns.GetHostName(); //得到本机名 IPHostEntry localhost = Dns.GetHostEntryAsync(hostname).Result; foreach (IPAddress localaddr in localhost.AddressList) { if (IPAddress.IsLoopback(localaddr)) continue; // 返回第一个IPv4地址 if (localaddr.AddressFamily == AddressFamily.InterNetwork) { return localaddr.ToString(); } } return null; } /// /// 判断ip是否本机本地地址,ipv4 /// /// public static bool IsThisMachineAddress(string address) { try { if(address == "127.0.0.1" || address == "localhost") { return true; } //System.Net.NetworkInformation.IPAddressCollection //Console.WriteLine("NetUtils.IsThisMachineLocalIp ipaddress {0}", ipaddress); string hostname = Dns.GetHostName();//得到本机名 if(hostname == address) { return true; } bool ismatching = false; IPHostEntry localhost = Dns.GetHostEntryAsync(hostname).Result; foreach (IPAddress localaddr in localhost.AddressList) { if (localaddr.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork) continue; if (IPAddress.IsLoopback(localaddr)) continue; string ip = localaddr.ToString(); //Console.WriteLine("NetUtils.IsThisMachineLocalIp Dns.GetHostEntryAsync ip {0} in list", ip); if (ip == address) { ismatching = true; return ismatching; } } var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (var network in networkInterfaces) { if (network.OperationalStatus != OperationalStatus.Up) continue; var properties = network.GetIPProperties(); if (properties.GatewayAddresses.Count == 0) continue; foreach (var tmpaddress in properties.UnicastAddresses) { if (tmpaddress.Address.AddressFamily != AddressFamily.InterNetwork) continue; if (IPAddress.IsLoopback(tmpaddress.Address)) continue; string ip = tmpaddress.Address.ToString(); //Console.WriteLine("NetUtils.IsThisMachineLocalIp NetworkInterface ip {0} in list", ip); if (ip == address) { ismatching = true; return ismatching; } } } return ismatching; } catch (Exception ex) { TraceLog.Exception(ex); } return false; } // 把ip地址转换成网络字节序(大端)的数字, 等于inet_aton public static uint IpAddrToNum(string addr) { uint ipNum = 0; var ipAddr = IPAddress.Parse(addr); if (ipAddr != null) { foreach (byte b in ipAddr.GetAddressBytes()) { ipNum = ipNum << 8; ipNum |= b; } } return ipNum; } // 把网络字节序(大端)的数字转换成ip地址, 等于inet_ntoa public static string IpNumToAddr(uint ipNum) { byte[] ipArr = new byte[4]; for (int i = 0; i < 4; i++) { ipArr[i] = (byte)(ipNum & 0xffff); ipNum = ipNum >> 8; } return string.Format("{0}.{1}.{2}.{3}", ipArr[3], ipArr[2], ipArr[1], ipArr[0]); } } }