C# 关于如何获取本地IP问题

本文介绍了一种使用C#语言来获取计算机本地IP地址的方法。通过遍历所有网络接口并筛选出以太网类型的接口,进而获取其IPv4和IPv6地址。适用于需要在网络应用程序中快速识别本机IP地址的场景。

  /// <summary>
        /// C# 如何获取本地IP
        /// </summary>
        /// <returns></returns>
        public void GetLocalIP()
        {
            List<string> strIPs = new List<string>();
            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface adapter in nics)
            {
                if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
                {
                    var mac = adapter.GetPhysicalAddress(); Console.WriteLine(mac);
                    IPInterfaceProperties ip = adapter.GetIPProperties();
                    UnicastIPAddressInformationCollection ipCollection = ip.UnicastAddresses;
                    //GatewayIPAddressInformationCollection ipv4Collection = ip.GatewayAddresses;
                    //Debug.LogError("ipv4Collection>>>>>   " + ipv4Collection.ToString());
                    foreach (UnicastIPAddressInformation ipadd in ipCollection)
                    {
                        Debug.LogError(">>>>>   " + ipadd.Address.ToString());
                        //InterNetwork    IPV4地址      
                        if (ipadd.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                        {   //判断是否为ipv4
                            Debug.LogError("本机ipv4:  " + ipadd.Address.ToString());
                            strIPs.Add(ipadd.Address.ToString());
                        }
                        //InterNetworkV6        IPV6地址 
                        if (ipadd.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
                        {   //判断是否为ipv6
                            Debug.LogError("本机ipv6:  " + ipadd.Address.ToString());
                            strIPs.Add(ipadd.Address.ToString());
                        }
                    }
                }
            }
        }

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值