How to get the IP address of the server on which my C# application is running on?

前端 未结 26 1949
天命终不由人
天命终不由人 2020-11-22 06:01

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?

Someon

相关标签:
26条回答
  • 2020-11-22 06:49

    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);
    }
    
    0 讨论(0)
  • 2020-11-22 06:49

    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();
    }
    
    0 讨论(0)
  • 2020-11-22 06:50

    Maybe by external IP you can consider (if you are in a Web server context) using this

    Request.ServerVariables["LOCAL_ADDR"];
    

    I was asking the same question as you and I found it in this stackoverflow article.

    It worked for me.

    0 讨论(0)
  • 2020-11-22 06:51
    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;
                }
            }
        }
    }
    

    Look here for details.

    You have to remember your computer can have more than one IP (actually it always does) - so which one are you after.

    0 讨论(0)
  • 2020-11-22 06:52

    For getting the current public IP address, all you need to do is create an ASPX page with the following line on the page load event:

    Response.Write(HttpContext.Current.Request.UserHostAddress.ToString());
    
    0 讨论(0)
  • 2020-11-22 06:54

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

    Request.UserHostAddress
    
    0 讨论(0)
提交回复
热议问题