首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在C#中通过远程处理获取外部IP地址

在C#中,通过远程处理获取外部IP地址的方法如下:

  1. 使用HttpClient获取外部IP地址
代码语言:csharp
复制
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;
}
  1. 使用WebClient获取外部IP地址
代码语言:csharp
复制
using System;
using System.Net;

public static string GetExternalIPAddress()
{
    using var webClient = new WebClient();
    return webClient.DownloadString("https://api.ipify.org?format=json");
}
  1. 使用WebRequest获取外部IP地址
代码语言:csharp
复制
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地址,其中第一种方法使用了异步操作,可以更好地处理网络请求。在实际应用中,可以根据需要选择合适的方法。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券