如何获取运行我的 C# 应用程序的服务器的 IP 地址? [英] How to get the IP address of the server on which my C# application is running on?

查看:20
本文介绍了如何获取运行我的 C# 应用程序的服务器的 IP 地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行一个服务器,我想显示我自己的 IP 地址.

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

获取计算机自己(如果可能,外部)IP 地址的语法是什么?

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

有人写了下面的代码.

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?

推荐答案

不,这几乎是最好的方法.由于一台机器可能有多个 IP 地址,因此您需要迭代它们的集合以找到合适的 IP 地址.

Nope, that is pretty much the best way to do it. As a machine could have several IP addresses you need to iterate the collection of them to find the proper one.

唯一改变的就是改变这个:

The only thing I would change would be to change this:

if (ip.AddressFamily.ToString() == "InterNetwork")

为此:

if (ip.AddressFamily == AddressFamily.InterNetwork)

不需要ToString枚举进行比较.

这篇关于如何获取运行我的 C# 应用程序的服务器的 IP 地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆