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
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.