在C#中,通过远程处理获取外部IP地址的方法如下:
using System;
using System.Net.Http;
using System.Threading.Tasks;
public static async Task<string> GetExternalIPAddressAsync()
{
using var httpClient = new HttpClient();
var response = await httpClient.GetAsync("https://api.ipify.org?format=json");
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
return responseBody;
}
using System;
using System.Net;
public static string GetExternalIPAddress()
{
using var webClient = new WebClient();
return webClient.DownloadString("https://api.ipify.org?format=json");
}
using System;
using System.Net;
using System.IO;
public static string GetExternalIPAddress()
{
var request = WebRequest.Create("https://api.ipify.org?format=json");
using var response = request.GetResponse();
using var stream = response.GetResponseStream();
using var reader = new StreamReader(stream);
return reader.ReadToEnd();
}
以上三种方法都可以获取外部IP地址,其中第一种方法使用了异步操作,可以更好地处理网络请求。在实际应用中,可以根据需要选择合适的方法。
领取专属 10元无门槛券
手把手带您无忧上云