C#获取本机内网外网IP

using System.Net;

# region 获取内、外网Ip

/// <summary>
/// 获取本地ip地址,优先取内网ip
/// </summary>
public static String GetLocalIp()
{
    String[] Ips = GetLocalIpAddress();

    foreach (String ip in Ips) if (ip.StartsWith("10.80.")) return ip;
    foreach (String ip in Ips) if (ip.Contains(".")) return ip;

    return "127.0.0.1";
}

/// <summary>
/// 获取本地ip地址,多个ip
/// </summary>
public static String[] GetLocalIpAddress()
{
    string hostName = Dns.GetHostName();                    //获取主机名称  
    IPAddress[] addresses = Dns.GetHostAddresses(hostName); //解析主机IP地址  

    string[] IP = new string[addresses.Length];             //转换为字符串形式  
    for (int i = 0; i < addresses.Length; i++) IP[i] = addresses[i].ToString();

    return IP;
}

/// <summary>
/// 获取外网ip地址
/// </summary>
public static string GetExtenalIpAddress_0()
{
    string IP = "未获取到外网ip";
    try
    {
        //从网址中获取本机ip数据  
        System.Net.WebClient client = new System.Net.WebClient();
        client.Encoding = System.Text.Encoding.Default;
        string str = client.DownloadString("http://1111.ip138.com/ic.asp");
        client.Dispose();

        //提取外网ip数据 [218.104.71.178]  
        int i1 = str.IndexOf("["), i2 = str.IndexOf("]");
        IP = str.Substring(i1 + 1, i2 - 1 - i1);
    }
    catch (Exception) { }

    return IP;
}

/// <summary>
/// 获取外网ip地址
/// </summary>
public static string GetExtenalIpAddress()
{
    String url = "http://hijoyusers.joymeng.com:8100/test/getNameByOtherIp";
    string IP = "未获取到外网ip";
    try
    {
        //从网址中获取本机ip数据  
        System.Net.WebClient client = new System.Net.WebClient();
        client.Encoding = System.Text.Encoding.Default;
        string str = client.DownloadString(url);
        client.Dispose();

        if (!str.Equals("")) IP = str;
        else IP = GetExtenalIpAddress_0();
    }
    catch (Exception) { }

    return IP;
}

# endregion


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值