C#獲取本地ip地址(wireless)

參考: https://blog.csdn.net/ropin_os/article/details/6689626

電腦做hotspot時可以使用以下代碼獲取本地ip,用於創建socket.

需要使用using System.Net.NetworkInformation;

NetworkInterface[] interfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
            int len = interfaces.Length;

            for (int i = 0; i < len; i++)
            {
                NetworkInterface ni = interfaces[i];
                if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211)
                {
                    if (ni.Name.IndexOf("本地連接") != -1 || ni.Name.IndexOf("Local Area Connection") != -1)
                    {
                        IPInterfaceProperties property = ni.GetIPProperties();
                        foreach (UnicastIPAddressInformation ip in property.UnicastAddresses)
                        {
                            if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                            {
                                if (ip.Address.ToString().IndexOf("169.254.") == -1)
                                {
                                    Console.WriteLine(ip.Address.ToString());
                                }                                
                            }
                        }
                    }
                }
            }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章