饰心

C#根据网络适配器获取本机ip

电脑版发表于:2019/11/18 13:47

直接调用下面方法即可:

private IList<string> GetHostIpForFas()
{
    try
    {
        IList<string> strIp = new List<string>();
        //NetworkInterface:提供网络接口的配置和统计信息。
        NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
        foreach (NetworkInterface adapter in adapters)
        {
            IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
            UnicastIPAddressInformationCollection allAddress = adapterProperties.UnicastAddresses;
            //这里是根据网络适配器名称找到对应的网络
            if (allAddress.Count > 0 && adapter.Name == "WLAN 2")
            {
                foreach (UnicastIPAddressInformation addr in allAddress)
                {
                    if (addr.Address.AddressFamily == AddressFamily.InterNetwork)
                    {
                        strIp.Add(addr.Address.ToString());
                    }
                }
            }
        }
        return strIp;
    }
    catch (Exception ex)
    {
        return null;
    }
}


实际上获取的就是电脑上的网络属性信息,见下图:



关于TNBLOG
TNBLOG,技术分享。技术交流:群号677373950
ICP备案 :渝ICP备18016597号-1
App store Android
精彩评论
{{item.replyName}}
{{item.content}}
{{item.time}}
{{subpj.replyName}}
@{{subpj.beReplyName}}{{subpj.content}}
{{subpj.time}}
猜你喜欢