C# 获取 IPv4地址
网上搜罗了的代码 做了下改进。 B/S C/S 都能用。
1 private static string GetIP4Address() 2 { 3 string IP4Address = String.Empty; 4 5 if (HttpContext.Current != null) 6 { 7 foreach (IPAddress IPA in Dns.GetHostAddresses(HttpContext.Current.Request.UserHostAddress)) 8 { 9 if (IPA.AddressFamily.ToString() == "InterNetwork") 10 { 11 IP4Address = IPA.ToString(); 12 break; 13 } 14 } 15 } 16 17 if (IP4Address != String.Empty) 18 { 19 return IP4Address; 20 } 21 22 foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName())) 23 { 24 if (IPA.AddressFamily.ToString() == "InterNetwork") 25 { 26 IP4Address = IPA.ToString(); 27 break; 28 } 29 } 30 31 return IP4Address; 32 }