[英]How to Get system IP (IPv4) address and convert to string using C# asp.net
On my web application I am using the following function to get System IP 在我的Web应用程序上,我正在使用以下功能来获取系统IP
Function 功能
public void SetHostid()
{
try
{
string ip = "";
string strHostName = "";
strHostName = System.Net.Dns.GetHostName();
IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
IPAddress[] addr = ipEntry.AddressList;
ip = addr[1].MapToIPv4().ToString();
HostId = ip;
HttpContext.Current.Session["Hostid"] = HostId;
}
catch (Exception ex)
{
Error_ManagerClass em = new Error_ManagerClass();
em.WriteError(ex);
}
}
It works perfectly because the IP is on the 1 postion of the variable addr ( addr[ 1]
). 由于IP位于变量addr的
addr[ 1]
( addr[ 1]
)上,因此它可以完美地工作。
And the problem comes when I try to run the same solution from a different system. 当我尝试从不同的系统运行相同的解决方案时,问题就来了。 function throws an error while trynig to convert IP to string(
ip = addr[1].MapToIPv4().ToString();
) because IP is not in the position number 1. 尝试将IP转换为字符串时,函数将引发错误(
ip = addr[1].MapToIPv4().ToString();
),因为IP不在位置编号1中。
how can I change the function to work on every computer ?? 如何更改功能以在每台计算机上工作?
If you want to get IPv4 only use this code: 如果只想获取IPv4,请使用以下代码:
var addr = ipEntry.AddressList.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork);
var firstInList = addr.First(); // get first
But you should consider which IP to chose when there are several IP addresses in system. 但是,当系统中有多个IP地址时,应考虑选择哪个IP。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.