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

前端 未结 26 1850
天命终不由人
天命终不由人 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:28
    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;
            }    
         }
    }
    
    0 讨论(0)
  • 2020-11-22 06:28

    Yet another way to get your public IP address is to use OpenDNS's resolve1.opendns.com server with myip.opendns.com as the request.

    On the command line this is:

      nslookup myip.opendns.com resolver1.opendns.com
    

    Or in C# using the DNSClient nuget:

      var lookup = new LookupClient(new IPAddress(new byte[] { 208, 67, 222, 222 }));
      var result = lookup.Query("myip.opendns.com", QueryType.ANY);
    

    This is a bit cleaner than hitting http endpoints and parsing responses.

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

    Here is how i solved it. i know if you have several physical interfaces this might not select the exact eth you want.

    private string FetchIP()
    {
        //Get all IP registered
        List<string> IPList = new List<string>();
        IPHostEntry host;
        host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                IPList.Add(ip.ToString());
            }
        }
    
        //Find the first IP which is not only local
        foreach (string a in IPList)
        {
            Ping p = new Ping();
            string[] b = a.Split('.');
            string ip2 = b[0] + "." + b[1] + "." + b[2] + ".1";
            PingReply t = p.Send(ip2);
            p.Dispose();
            if (t.Status == IPStatus.Success && ip2 != a)
            {
                return a;
            }
        }
        return null;
    }
    
    0 讨论(0)
  • 2020-11-22 06:33

    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.

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

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

    to this:

    if (ip.AddressFamily == AddressFamily.InterNetwork)
    

    There is no need to ToString an enumeration for comparison.

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

    Don't rely on InterNetwork all the time because you can have more than one device which also uses IP4 which would screw up the results in getting your IP. Now, if you would like you may just copy this and please review it or update it to how you see fit.

    First I get the address of the router (gateway) If it comes back that I am connected to a gateway (which mean not connected directly into the modem wireless or not) then we have our gateway address as IPAddress else we a null pointer IPAddress reference.

    Then we need to get the computer's list of IPAddresses. This is where things are not that hard because routers (all routers) use 4 bytes (...). The first three are the most important because any computer connected to it will have the IP4 address matching the first three bytes. Ex: 192.168.0.1 is standard for router default IP unless changed by the adminstrator of it. '192.168.0' or whatever they may be is what we need to match up. And that is all I did in IsAddressOfGateway function. The reason for the length matching is because not all addresses (which are for the computer only) have the length of 4 bytes. If you type in netstat in the cmd, you will find this to be true. So there you have it. Yes, it takes a little more work to really get what you are looking for. Process of elimination. And for God's sake, do not find the address by pinging it which takes time because first you are sending the address to be pinged and then it has to send the result back. No, work directly with .Net classes which deal with your system environment and you will get the answers you are looking for when it has to solely do with your computer.

    Now if you are directly connected to your modem, the process is almost the same because the modem is your gateway but the submask is not the same because your getting the information directly from your DNS Server via modem and not masked by the router serving up the Internet to you although you still can use the same code because the last byte of the IP assigned to the modem is 1. So if IP sent from the modem which does change is 111.111.111.1' then you will get 111.111.111.(some byte value). Keep in mind the we need to find the gateway information because there are more devices which deal with internet connectivity than your router and modem.

    Now you see why you DON'T change your router's first two bytes 192 and 168. These are strictly distinguished for routers only and not internet use or we would have a serious issue with IP Protocol and double pinging resulting in crashing your computer. Image that your assigned router IP is 192.168.44.103 and you click on a site with that IP as well. OMG! Your computer would not know what to ping. Crash right there. To avoid this issue, only routers are assigned these and not for internet usage. So leave the first two bytes of the router alone.

    static IPAddress FindLanAddress()
    {
        IPAddress gateway = FindGetGatewayAddress();
        if (gateway == null)
            return null;
    
        IPAddress[] pIPAddress = Dns.GetHostAddresses(Dns.GetHostName());
    
        foreach (IPAddress address in pIPAddress)            {
            if (IsAddressOfGateway(address, gateway))
                    return address;
        return null;
    }
    static bool IsAddressOfGateway(IPAddress address, IPAddress gateway)
    {
        if (address != null && gateway != null)
            return IsAddressOfGateway(address.GetAddressBytes(),gateway.GetAddressBytes());
        return false;
    }
    static bool IsAddressOfGateway(byte[] address, byte[] gateway)
    {
        if (address != null && gateway != null)
        {
            int gwLen = gateway.Length;
            if (gwLen > 0)
            {
                if (address.Length == gateway.Length)
                {
                    --gwLen;
                    int counter = 0;
                    for (int i = 0; i < gwLen; i++)
                    {
                        if (address[i] == gateway[i])
                            ++counter;
                    }
                    return (counter == gwLen);
                }
            }
        }
        return false;
    
    }
    static IPAddress FindGetGatewayAddress()
    {
        IPGlobalProperties ipGlobProps = IPGlobalProperties.GetIPGlobalProperties();
    
        foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
        {
            IPInterfaceProperties ipInfProps = ni.GetIPProperties();
            foreach (GatewayIPAddressInformation gi in ipInfProps.GatewayAddresses)
                return gi.Address;
        }
        return null;
    }
    
    0 讨论(0)
  • 2020-11-22 06:33

    Try this:

     IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
     String MyIp = localIPs[0].ToString();
    
    0 讨论(0)
提交回复
热议问题