Three methods of obtaining IP

Take the first host address ip

public string GetLocalIp()
{
///获取本地的IP地址
string AddressIP = string.Empty;
foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
{
if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
{
AddressIP = _IPAddress.ToString();
}
}
return AddressIP;
}

The second

/// <Summary>
/// take the local host IP
/// </ Summary>
/// <Returns> </ Returns>
public static String GetLocalIP ()
{
the try
{

String Dns.GetHostName the HostName = (); / / hostname to give
the IPHostEntry IpEntry = Dns.GetHostEntry (the hostName);
for (int I = 0; I <IpEntry.AddressList.Length; I ++)
{
// filter out the IP address from the IPv4 type IP address list
// AddressFamily. this IP InterNetwork expressed as the IPv4,
//AddressFamily.InterNetworkV6 indicates the type of address is an IPv6
IF (IpEntry.AddressList [I] == .AddressFamily AddressFamily.InterNetwork)
{
String IP = "";
IP = IpEntry.AddressList [I]. the ToString ();
return IpEntry.AddressList [I] .ToString ();
}
}
return "";
}
The catch (Exception EX)
{
return ex.Message;
}
}
The third IP to get access through the web site

public static string GetIP()
{
using (var webClient = new WebClient())
{
try
{
var temp = webClient.DownloadString("http://localhost:1234/WeatherWebForm.aspx");//一般指定网址
var ip = Regex.Match(temp, @"\[(?<ip>\d+\.\d+\.\d+\.\d+)]").Groups["ip"].Value;
return !string.IsNullOrEmpty(ip) ? ip : null;
}
catch (Exception ex)
{
return ex.Message;
}
}
}

Guess you like

Origin www.cnblogs.com/nanqinling/p/11930492.html