C#里获取IP地址方法整理【IPV4,IPV6】
using System; namespace GetIpDemo { ////// C#里获取IP地址方法整理【IPV4,IPV6】 /// LDH @ 2021-11-19 /// internal class Program { private static void Main() { Console.Title = "C#里获取IP地址方法整理【IPV4,IPV6】"; var ipv4 = IpAddressHelper.GetIpV4(); Console.WriteLine("IPV4:" + ipv4); PrintLine(); var ipv6 = IpAddressHelper.GetIpV6(); Console.WriteLine("IPV6:" + ipv6); PrintLine(); var localIp = IpAddressHelper.GetLocalIp(); Console.WriteLine("Local IP:" + localIp); PrintLine(); var ip = IpAddressHelper.GetIpAddress(); Console.WriteLine("IP:" + ip); PrintLine(); var ipStr = "1888.555.666.666"; var isIp = IpAddressHelper.IsIpStr(ipStr); PrintLine(); if (isIp) Console.WriteLine($"{ipStr}是合法的IP"); else Console.WriteLine($"{ipStr}是非法的IP"); PrintLine(); Console.ReadKey(); } private static void PrintLine() { Console.WriteLine("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"); } } }
using System.Net; using System.Net.Sockets; namespace GetIpDemo { ////// 获取IP地址帮助类 /// LDH @ 2021-11-19 /// public class IpAddressHelper { /// /// 获取本地IP地址信息 /// public static string GetIpAddress() { // 获取本地的IP地址 var addressIp = string.Empty; foreach (var ipAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList) if (ipAddress.AddressFamily.ToString() == "InterNetwork") addressIp = ipAddress.ToString(); return addressIp; } /// /// 获取IPV4地址 /// /// 返回IPV4地址 public static string GetIpV4() { // 本机名 var hostName = Dns.GetHostName(); // 方法已过期,IPV4地址 var localhostIpV4 = Dns.GetHostByName(hostName); var ipV4Address = localhostIpV4.AddressList[0]; var ipV4 = ipV4Address.ToString(); return ipV4; } /// /// 获取IPV6地址 /// /// 返回IPV6地址 public static string GetIpV6() { // 本机名 var hostName = Dns.GetHostName(); // IPV6 地址 var localhostIpV6 = Dns.GetHostEntry(hostName); var ipV6Address = localhostIpV6.AddressList[0]; var ipV6 = ipV6Address.ToString(); return ipV6; } /// /// 获取本机IP地址 /// /// 获取本机IP地址 public static string GetLocalIp() { try { var HostName = Dns.GetHostName(); //得到主机名 var IpEntry = Dns.GetHostEntry(HostName); for (var i = 0; i < IpEntry.AddressList.Length; i++) // 从IP地址列表中筛选出IPv4类型的IP地址 //AddressFamily.InterNetwork表示此IP为IPv4, //AddressFamily.InterNetworkV6表示此地址为IPv6类型 if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork) return IpEntry.AddressList[i].ToString(); } catch { // ignored } return string.Empty; } /// /// 判读是否是IP地址 /// /// ip字符串 /// 是否是IP地址 public static bool IsIpStr(string ipStr) { IPAddress ip; return IPAddress.TryParse(ipStr, out ip); } } }