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

前端 未结 26 2240
天命终不由人
天命终不由人 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:43

    To get the remote ip address the quickest way possible. You must have to use a downloader, or create a server on your computer.

    The downsides to using this simple code: (which is recommended) is that it will take 3-5 seconds to get your Remote IP Address because the WebClient when initialized always takes 3-5 seconds to check for your proxy settings.

     public static string GetIP()
     {
                string externalIP = "";
                externalIP = new WebClient().DownloadString("http://checkip.dyndns.org/");
                externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
                                               .Matches(externalIP)[0].ToString();
                return externalIP;
     }
    

    Here is how I fixed it.. (first time still takes 3-5 seconds) but after that it will always get your Remote IP Address in 0-2 seconds depending on your connection.

    public static WebClient webclient = new WebClient();
    public static string GetIP()
    {
        string externalIP = "";
        externalIP = webclient.DownloadString("http://checkip.dyndns.org/");
        externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
                                       .Matches(externalIP)[0].ToString();
        return externalIP;
    }
    

提交回复
热议问题