How to get the IP address of the server on which m

2018-12-31 07:35发布

I am running a server, and I want to display my own IP address.

What is the syntax for getting the computer's own (if possible, external) IP address?

Someone wrote the following code.

IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
    if (ip.AddressFamily.ToString() == "InterNetwork")
    {
        localIP = ip.ToString();
    }
}
return localIP;

However, I generally distrust the author, and I don't understand this code. Is there a better way to do so?

标签: c# ip-address
25条回答
忆尘夕之涩
2楼-- · 2018-12-31 08:11

The question doesn't say ASP.NET MVC but I'm just leaving this here anyway:

Request.UserHostAddress
查看更多
登录 后发表回答