public static async Task<string> GetExternalIPAddressAsync()
{
using (var client = new HttpClient())
{
var response = await client.GetAsync("http://icanhazip.com");
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
return Regex.Match(content, @"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}").Value;
}
else
{
throw new Exception($"无法获取IP地址:HTTP状态码 {response.StatusCode}");
}
}
}
public static string GetExternalIPAddress()
{
try
{
using (var client = new WebClient())
{
string ipString = client.DownloadString("http://icanhazip.com");
return Regex.Match(ipString, @"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}").Value;
}
}
catch (Exception ex)
{
Console.WriteLine($"获取IP地址时出错: {ex.Message}");
return "0.0.0.0";
}
}
string ipAddress = await GetExternalIPAddressAsync();
string ipAddress = GetExternalIPAddress();