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

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

有人编写了以下代码。

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;

然而,我通常不信任作者,我不理解这段代码。有更好的方法吗?


当前回答

了解你的公共IP的唯一方法是让别人告诉你;这段代码可以帮助你:

public string GetPublicIP()
{
    String direction = "";
    WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
    using (WebResponse response = request.GetResponse())
    using (StreamReader stream = new StreamReader(response.GetResponseStream()))
    {
        direction = stream.ReadToEnd();
    }

    //Search for the ip in the html
    int first = direction.IndexOf("Address: ") + 9;
    int last = direction.LastIndexOf("</body>");
    direction = direction.Substring(first, last - first);

    return direction;
}

其他回答

using System.Net;

string host = Dns.GetHostName();
IPHostEntry ip = Dns.GetHostEntry(host);
Console.WriteLine(ip.AddressList[0].ToString());

刚在我的机器上测试过了,还能用。

为了获取当前的公网IP地址,你所需要做的就是在页面加载事件中创建一个ASPX页面,代码如下:

Response.Write(HttpContext.Current.Request.UserHostAddress.ToString());

我只是想添加我自己的一行代码(尽管已经有许多其他有用的答案)。


string ipAddress = new WebClient().DownloadString("http://icanhazip.com");

如果你不能依赖于从DNS服务器获取你的IP地址(这发生在我身上),你可以使用以下方法:

System.Net.NetworkInformation命名空间包含一个NetworkInterface类,该类有一个静态的GetAllNetworkInterfaces方法。

此方法将返回您机器上的所有“网络接口”,而且通常有相当多的“网络接口”,即使您的机器上只安装了无线适配器和/或以太网适配器硬件。所有这些网络接口都有本地计算机的有效IP地址,尽管您可能只需要一个。

如果您正在寻找一个IP地址,那么您将需要筛选列表,直到您可以识别正确的地址。你可能需要做一些实验,但我成功地采用了以下方法:

通过检查OperationalStatus == OperationalStatus. up过滤掉任何非活动的网络接口。这将排除您的物理以太网适配器,例如,如果您没有插入网线。

对于每个NetworkInterface,你可以使用GetIPProperties方法获得一个IPInterfaceProperties对象,并且从一个IPInterfaceProperties对象中,你可以访问UnicastIPAddressInformation对象列表的UnicastAddresses属性。

通过检查DuplicateAddressDetectionState == DuplicateAddressDetectionState过滤掉非首选单播地址。首选 通过检查AddressPreferredLifetime != UInt32.MaxValue过滤出“虚拟”地址。

此时,我取与所有这些过滤器匹配的第一个单播地址(如果有的话)的地址。

编辑:

[2018年5月16日修订的代码,以包括上述文本中提到的重复地址检测状态和首选生存期的条件]

下面的示例演示了基于操作状态、地址族、排除环回地址(127.0.0.1)、重复地址检测状态和首选生存期的过滤。

static IEnumerable<IPAddress> GetLocalIpAddresses()
{
    // Get the list of network interfaces for the local computer.
    var adapters = NetworkInterface.GetAllNetworkInterfaces();

    // Return the list of local IPv4 addresses excluding the local
    // host, disconnected, and virtual addresses.
    return (from adapter in adapters
            let properties = adapter.GetIPProperties()
            from address in properties.UnicastAddresses
            where adapter.OperationalStatus == OperationalStatus.Up &&
                  address.Address.AddressFamily == AddressFamily.InterNetwork &&
                  !address.Equals(IPAddress.Loopback) &&
                  address.DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred &&
                  address.AddressPreferredLifetime != UInt32.MaxValue
            select address.Address);
}
namespace NKUtilities 
{
    using System;
    using System.Net;
    using System.Net.Sockets;

    public class DNSUtility
    {
        public static int Main(string [] args)
        {
            string strHostName = "";
            try {

                if(args.Length == 0)
                {
                    // Getting Ip address of local machine...
                    // First get the host name of local machine.
                    strHostName = Dns.GetHostName();
                    Console.WriteLine ("Local Machine's Host Name: " +  strHostName);
                }
                else
                {
                    // Otherwise, get the IP address of the host provided on the command line.
                    strHostName = args[0];
                }

                // Then using host name, get the IP address list..
                IPHostEntry ipEntry = Dns.GetHostEntry (strHostName);
                IPAddress [] addr = ipEntry.AddressList;

                for(int i = 0; i < addr.Length; i++)
                {
                    Console.WriteLine("IP Address {0}: {1} ", i, addr[i].ToString());
                }
                return 0;

            } 
            catch(SocketException se) 
            {
                Console.WriteLine("{0} ({1})", se.Message, strHostName);
                return -1;
            } 
            catch(Exception ex) 
            {
                Console.WriteLine("Error: {0}.", ex.Message);
                return -1;
            }
        }
    }
}

详情请看这里。

你必须记住你的电脑可以有多个IP(实际上它总是这样)-所以你是哪一个。