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:08

I just thought that I would add my own, one-liner (even though there are many other useful answers already).


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

查看更多
无与为乐者.
3楼-- · 2018-12-31 08:08

The LINQ solution:

Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork).Select(ip => ip.ToString()).FirstOrDefault() ?? ""
查看更多
浮光初槿花落
4楼-- · 2018-12-31 08:09

If you can't rely on getting your IP address from a DNS server (which has happened to me), you can use the following approach:

The System.Net.NetworkInformation namespace contains a NetworkInterface class, which has a static GetAllNetworkInterfaces method.

This method will return all "network interfaces" on your machine, and there are generally quite a few, even if you only have a wireless adapter and/or an ethernet adapter hardware installed on your machine. All of these network interfaces have valid IP addresses for your local machine, although you probably only want one.

If you're looking for one IP address, then you'll need to filter the list down until you can identify the right address. You will probably need to do some experimentation, but I had success with the following approach:

  • Filter out any NetworkInterfaces that are inactive by checking for OperationalStatus == OperationalStatus.Up. This will exclude your physical ethernet adapter, for instance, if you don't have a network cable plugged in.

For each NetworkInterface, you can get an IPInterfaceProperties object using the GetIPProperties method, and from an IPInterfaceProperties object you can access the UnicastAddresses property for a list of UnicastIPAddressInformation objects.

  • Filter out non-preferred unicast addresses by checking for DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred
  • Filter out "virtual" addresses by checking for AddressPreferredLifetime != UInt32.MaxValue.

At this point I take the address of the first (if any) unicast address that matches all of these filters.

EDIT:

[revised code on May 16, 2018 to include the conditions mentioned in the text above for duplicate address detection state and preferred lifetime]

The sample below demonstrates filtering based on operational status, address family, excluding the loopback address (127.0.0.1), duplicate address detection state, and preferred lifetime.

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);
}
查看更多
余欢
5楼-- · 2018-12-31 08:09
namespace NKUtilities 
{
    using System;
    using System.Net;

    public class DNSUtility
    {
        public static int Main (string [] args)
        {

          String strHostName = new String ("");
          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
          {
              strHostName = args[0];
          }

          // Then using host name, get the IP address list..
          IPHostEntry ipEntry = DNS.GetHostByName (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;
        }    
     }
}
查看更多
只靠听说
6楼-- · 2018-12-31 08:10

Try this:

 IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
 String MyIp = localIPs[0].ToString();
查看更多
零度萤火
7楼-- · 2018-12-31 08:11

To find IP address list I have used this solution

public static IEnumerable<string> GetAddresses()
{
    var host = Dns.GetHostEntry(Dns.GetHostName());
    return (from ip in host.AddressList where ip.AddressFamily == AddressFamily.lo select ip.ToString()).ToList();
}

But I personally like below solution to get local valid IP address

public static IPAddress GetIPAddress(string hostName)
{
    Ping ping = new Ping();
    var replay = ping.Send(hostName);

    if (replay.Status == IPStatus.Success)
    {
        return replay.Address;
    }
    return null;
 }

public static void Main()
{
    Console.WriteLine("Local IP Address: " + GetIPAddress(Dns.GetHostName()));
    Console.WriteLine("Google IP:" + GetIPAddress("google.com");
    Console.ReadLine();
}
查看更多
登录 后发表回答