C # /. NET obtain IP network and the public network

Code

private void GetIP()
{
	//内网(局域网)IP
    IPAddress LocalIP = Dns.GetHostAddresses(Dns.GetHostName()).Where(ip => ip.AddressFamily.ToString().Equals("InterNetwork")).FirstOrDefault();
	
	//外网(公网)IP
    Stream stream = null;
    StreamReader streamReader = null;
    try
    {
        stream = WebRequest.Create("https://www.ipip5.com/").GetResponse().GetResponseStream();
        streamReader = new StreamReader(stream, Encoding.UTF8);
        var str = streamReader.ReadToEnd();
        int first = str.IndexOf("<span class=\"c-ip\">") + 19;
        int last = str.IndexOf("</span>", first);
        var ip = str.Substring(first, last - first);
        IPAddress PublicIP = IPAddress.Parse(ip);		//这里就得到了
    }
    catch (Exception ex)
    {
        Console.WriteLine($"出错了,{ex.Message}。获取失败");
    }
    finally
    {
        streamReader?.Dispose();
        stream?.Dispose();
    }
}

Appeals obtain public IP access principle is https://www.ipip5.com/to get its HTML, in theory, this URL can be any query IP site
Here Insert Picture Description
content and then obtain the desired operating through a series of strings on the line

The above code

int first = str.IndexOf("<span class=\"c-ip\">") + 19;

19 shows here <span class="c-ip">the length of their understanding on the line.

Published 62 original articles · won praise 68 · views 160 000 +

Guess you like

Origin blog.csdn.net/ZUFE_ZXh/article/details/104610890