c#

C#获取外网IP地址的方法介绍

小樊
167
2024-07-06 01:48:20
栏目: 编程语言

在C#中获取外网IP地址的方法有多种,以下是其中一种常用的方法:

using System;
using System.Net;

class Program
{
    static void Main()
    {
        try
        {
            WebClient client = new WebClient();
            string externalIP = client.DownloadString("http://icanhazip.com");
            Console.WriteLine("External IP Address: " + externalIP);
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }
}

在上述代码中,我们使用WebClient类来向一个公开的外部IP地址查询服务(比如http://icanhazip.com)发送一个HTTP请求,并获取返回的IP地址。然后我们将这个IP地址打印出来。需要注意的是,这个方法依赖于外部服务的可用性,因此可能会受到网络状态或服务故障的影响。

另外,还可以使用其他方式获取外网IP地址,比如通过请求http://ip-api.com/json等API接口获取IP地址信息。根据实际需求选择合适的方法进行获取。

0
看了该问题的人还看了