C# 获取本机IP地址

时间:2022-08-27 16:04:19

有时候软件操作的时候我们需要记录是从哪个机器上操作的,比如登录,或者一般涉及到金钱交易的时候,一般都会记录这个地址。

 /// <summary>
/// 获得本机IP地址
/// </summary>
/// <param name="hostname"></param>
/// <returns></returns>
public static string DoGetHostEntry()
{
System.Net.IPHostEntry IpEntry
= System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
string localhostipv4Address = "";

for (int i = 0; i != IpEntry.AddressList.Length; i++)
{
if (!IpEntry.AddressList[i].IsIPv6LinkLocal)
{
localhostipv4Address
= IpEntry.AddressList[i].ToString();
break;
}
}

return localhostipv4Address;
}