how can i learn my client ip with .NET?

2019-06-20 16:59发布

i need my client ip from whatismyip.com. But Regex pattern is not correct i think? Can you help me this patttern?

5条回答
戒情不戒烟
2楼-- · 2019-06-20 17:22

Try to use
http://www.whatismyip.org/
It's much simpler.

Or you want to parse information exactly whatismyip.com?

查看更多
干净又极端
3楼-- · 2019-06-20 17:22

This is how you get the ip in ASP.NET C#

string pstrClientAddress = HttpContext.Current.Request.UserHostAddress;
查看更多
相关推荐>>
4楼-- · 2019-06-20 17:30

Have you read the comment in the obtained HTML:

Please set your code to scrape your IP from www.whatismyip.com/automation/n09230945.asp For more info, please see our "Recommended Automation Practices" thread in the Forum.

So this should get you going:

using (var client = new WebClient())
{
    Console.WriteLine(client.DownloadString(
        "http://www.whatismyip.com/automation/n09230945.asp"));
}
查看更多
smile是对你的礼貌
5楼-- · 2019-06-20 17:30

Do it like this instead:

class Program
{
    static void Main(string[] args)
    {
        string whatIsMyIp = "http://www.whatismyip.com/automation/n09230945.asp";
        WebClient wc = new WebClient();
        UTF8Encoding utf8 = new UTF8Encoding();
        string requestHtml = "";
        try
        {
            requestHtml = utf8.GetString(wc.DownloadData(whatIsMyIp));
        }
        catch (WebException we)
        {
            // do something with exception 
            Console.Write(we.ToString());
        }

        IPAddress externalIp = null;
        externalIp = IPAddress.Parse(requestHtml);

        Console.Write("IP Numaram:" + externalIp.ToString());
        Console.ReadKey(); 

    }
}
查看更多
放我归山
6楼-- · 2019-06-20 17:43

This can be achieved way easier using the automation interface from www.whatismyip.com, so there's no need for any regex:

static void Main(string[] args)
    {
        const string url = "http://www.whatismyip.com/automation/n09230945.asp";

        var client = new WebClient();
        try
        {
            var myIp = client.DownloadString(url);
            Console.WriteLine("Your IP: " + myIp);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error contacting website: " + ex.Message);
        }
    }
查看更多
登录 后发表回答