none
如何准确的获取到本地连接的IP地址(前提是我有无线网络和本地连接两个IP地址) RRS feed

  • 问题

  • 我的无线网络IP地址:192.168.10.102
    本地连接IP地址:192.168.16.9

    我要获取到 本地连接IP地址:192.168.16.9


    网上的做法是这样 但是我现在有两个IP一个本地 一个 无线
    string strHostName = Dns.GetHostName();
     string clientIPAddress = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString();

    我如何能准确的获取到本地连接的IP地址 而不是无线网络的呢?


    后来我的思路是这样
     i              nt len = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces().Length;
                    for (int i = 0; i < len; i++)
                    {
                        if (System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[i].Name == "本地连接")
                        {
                          然后 在获取IP地址 但是不知道为什么获取都不对 
    System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[i].GetIPProperties().DnsAddresses[1].ToString()
                        }

                    }
    2009年7月31日 6:56

答案

  • // 网卡名称是可变的,判断网卡名称还不能完成保存能正确的区别本地网卡
    // 下面的方法更准确一些
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data.OleDb;
    using System.Data;
    using System.Net;
    using System.Net.NetworkInformation;
    using System.Net.Sockets;
    using Microsoft.Win32;
    
    namespace ConsoleDemo
    {
        /// <summary>
        /// 标题:区分本地网卡、虚拟网卡及无线网卡
        /// 作者:X.X.Y
        /// 日期:2009-08-03
        /// 描述:测试环境 VS2008 + XP
        /// </summary>
        class Program
        {
            static void Main(string[] args)
            {
                ShowNetworkInterfaceMessage();
            }
    
            /// <summary>
            /// 显示本机各网卡的详细信息
            /// </summary>
            public static void ShowNetworkInterfaceMessage()
            {
                NetworkInterface[] fNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
    
                foreach (NetworkInterface adapter in fNetworkInterfaces)
                {
                    #region " 网卡类型 "
    
                    string fCardType = "未知网卡";
                    string fRegistryKey = "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\" + adapter.Id + "\\Connection";
                    RegistryKey rk = Registry.LocalMachine.OpenSubKey(fRegistryKey, false);
    
                    if (rk != null)
                    {
                        // 区分 PnpInstanceID 
                        // 如果前面有 PCI 就是本机的真实网卡
                        // MediaSubType 为 01 则是常见网卡,02为无线网卡。
                        string fPnpInstanceID = rk.GetValue("PnpInstanceID", "").ToString();
                        int fMediaSubType = Convert.ToInt32(rk.GetValue("MediaSubType", 0));
    
                        if (fPnpInstanceID.Length > 3 &&
                            fPnpInstanceID.Substring(0, 3) == "PCI")
                            fCardType = "物理网卡";
                        else if (fMediaSubType == 1)
                            fCardType = "虚拟网卡";
                        else if (fMediaSubType == 2)
                            fCardType = "无线网卡";
                    }
    
                    #endregion
    
                    #region " 网卡信息 "
    
                    Console.WriteLine("-----------------------------------------------------------");
                    Console.WriteLine("-- " + fCardType);
                    Console.WriteLine("-----------------------------------------------------------");
    
                    Console.WriteLine("Id .................. : {0}", adapter.Id); // 获取网络适配器的标识符
                    Console.WriteLine("Name ................ : {0}", adapter.Name); // 获取网络适配器的名称
                    Console.WriteLine("Description ......... : {0}", adapter.Description); // 获取接口的描述
                    Console.WriteLine("Interface type ...... : {0}", adapter.NetworkInterfaceType); // 获取接口类型
                    Console.WriteLine("Is receive only...... : {0}", adapter.IsReceiveOnly); // 获取 Boolean 值,该值指示网络接口是否设置为仅接收数据包。
                    Console.WriteLine("Multicast............ : {0}", adapter.SupportsMulticast); // 获取 Boolean 值,该值指示是否启用网络接口以接收多路广播数据包。
                    Console.WriteLine("Speed ............... : {0}", adapter.Speed); // 网络接口的速度
                    Console.WriteLine("Physical Address .... : {0}", adapter.GetPhysicalAddress().ToString()); // MAC 地址
    
                    IPInterfaceProperties fIPInterfaceProperties = adapter.GetIPProperties();
                    UnicastIPAddressInformationCollection UnicastIPAddressInformationCollection = fIPInterfaceProperties.UnicastAddresses;
                    foreach (UnicastIPAddressInformation UnicastIPAddressInformation in UnicastIPAddressInformationCollection)
                    {
                        if (UnicastIPAddressInformation.Address.AddressFamily == AddressFamily.InterNetwork)
                            Console.WriteLine("Ip Address .......... : {0}", UnicastIPAddressInformation.Address); // Ip 地址
                    }
    
                    Console.WriteLine();
    
                    #endregion
                }
    
                Console.ReadKey();
            }
        }
    }

    知识改变命运,奋斗成就人生!
    2009年8月3日 7:56
    版主
  • 你好,你可以通过下面的代码测试我已经测试过了

    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.Ethernet)
                {
                   if (ni.Name == "本地连接")
                   {
                      IPInterfaceProperties property = ni.GetIPProperties();
                      foreach (UnicastIPAddressInformation ip in
                          property.UnicastAddresses)
                      {
                         if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                         {
                            localIP = ip.Address.ToString();
                         }
                      }
                   }
                }

             }


    你还可以通过这个方法 查看每个网卡的具体信息

     private static void GetLocalIP()
          {
             ManagementObjectSearcher objSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'");

             ManagementObjectCollection objCollection = objSearcher.Get();

             foreach (ManagementObject obj in objCollection)
             {

                //string[] AddressList = (string[])obj["IPAddress"];
                PropertyDataCollection properties = obj.Properties;

                foreach (PropertyData data in properties)
                {
                   Console.WriteLine(string.Format("Name:{0},是否是数组:{1},值:{2}",data.Name,data.IsArray.ToString(),data.Value));
                   if (data.IsArray)
                   {
                      try
                      {
                         string[] values = (string[])obj[data.Name];
                         if (values != null)
                         {
                            foreach (string str in values)
                            {
                               Console.WriteLine(str);
                            }
                         }
                      }
                      catch (Exception ex)
                      {
                         Console.WriteLine(ex.Message);
                      }
                   }

                 
     
                } Console.WriteLine("_________________________________");
                //string[] names = (string[])obj["name"];

                //foreach (string Address in AddressList)
                //{

                //   Console.WriteLine(Address);

                //}

             }
          }







    Wenn ich dich hab’,gibt es nichts, was unerträglich ist.坚持不懈!http://hi.baidu.com/1987raymond
    2009年8月3日 6:40
    版主

全部回复

  • string   strHostIP="";  
    IPHostEntry  oIPHost=Dns.Resolve(Environment.MachineName);
    if (oIPHost.AddressList.Length>0)
    	strHostIP=oIPHost.AddressList[0].ToString();
    Console.WriteLine(strHostIP);
     

    http://hi.baidu.com/2009ajun
    • 已编辑 Junxiang 2009年7月31日 23:36
    2009年7月31日 23:33
  • ls 按你的做法 获取出来的IP192.168.10.102
    是无线网络的地址
    2009年8月1日 0:44
  • 你好,你可以通过下面的代码测试我已经测试过了

    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.Ethernet)
                {
                   if (ni.Name == "本地连接")
                   {
                      IPInterfaceProperties property = ni.GetIPProperties();
                      foreach (UnicastIPAddressInformation ip in
                          property.UnicastAddresses)
                      {
                         if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                         {
                            localIP = ip.Address.ToString();
                         }
                      }
                   }
                }

             }


    你还可以通过这个方法 查看每个网卡的具体信息

     private static void GetLocalIP()
          {
             ManagementObjectSearcher objSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'");

             ManagementObjectCollection objCollection = objSearcher.Get();

             foreach (ManagementObject obj in objCollection)
             {

                //string[] AddressList = (string[])obj["IPAddress"];
                PropertyDataCollection properties = obj.Properties;

                foreach (PropertyData data in properties)
                {
                   Console.WriteLine(string.Format("Name:{0},是否是数组:{1},值:{2}",data.Name,data.IsArray.ToString(),data.Value));
                   if (data.IsArray)
                   {
                      try
                      {
                         string[] values = (string[])obj[data.Name];
                         if (values != null)
                         {
                            foreach (string str in values)
                            {
                               Console.WriteLine(str);
                            }
                         }
                      }
                      catch (Exception ex)
                      {
                         Console.WriteLine(ex.Message);
                      }
                   }

                 
     
                } Console.WriteLine("_________________________________");
                //string[] names = (string[])obj["name"];

                //foreach (string Address in AddressList)
                //{

                //   Console.WriteLine(Address);

                //}

             }
          }







    Wenn ich dich hab’,gibt es nichts, was unerträglich ist.坚持不懈!http://hi.baidu.com/1987raymond
    2009年8月3日 6:40
    版主
  • // 网卡名称是可变的,判断网卡名称还不能完成保存能正确的区别本地网卡
    // 下面的方法更准确一些
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data.OleDb;
    using System.Data;
    using System.Net;
    using System.Net.NetworkInformation;
    using System.Net.Sockets;
    using Microsoft.Win32;
    
    namespace ConsoleDemo
    {
        /// <summary>
        /// 标题:区分本地网卡、虚拟网卡及无线网卡
        /// 作者:X.X.Y
        /// 日期:2009-08-03
        /// 描述:测试环境 VS2008 + XP
        /// </summary>
        class Program
        {
            static void Main(string[] args)
            {
                ShowNetworkInterfaceMessage();
            }
    
            /// <summary>
            /// 显示本机各网卡的详细信息
            /// </summary>
            public static void ShowNetworkInterfaceMessage()
            {
                NetworkInterface[] fNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
    
                foreach (NetworkInterface adapter in fNetworkInterfaces)
                {
                    #region " 网卡类型 "
    
                    string fCardType = "未知网卡";
                    string fRegistryKey = "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\" + adapter.Id + "\\Connection";
                    RegistryKey rk = Registry.LocalMachine.OpenSubKey(fRegistryKey, false);
    
                    if (rk != null)
                    {
                        // 区分 PnpInstanceID 
                        // 如果前面有 PCI 就是本机的真实网卡
                        // MediaSubType 为 01 则是常见网卡,02为无线网卡。
                        string fPnpInstanceID = rk.GetValue("PnpInstanceID", "").ToString();
                        int fMediaSubType = Convert.ToInt32(rk.GetValue("MediaSubType", 0));
    
                        if (fPnpInstanceID.Length > 3 &&
                            fPnpInstanceID.Substring(0, 3) == "PCI")
                            fCardType = "物理网卡";
                        else if (fMediaSubType == 1)
                            fCardType = "虚拟网卡";
                        else if (fMediaSubType == 2)
                            fCardType = "无线网卡";
                    }
    
                    #endregion
    
                    #region " 网卡信息 "
    
                    Console.WriteLine("-----------------------------------------------------------");
                    Console.WriteLine("-- " + fCardType);
                    Console.WriteLine("-----------------------------------------------------------");
    
                    Console.WriteLine("Id .................. : {0}", adapter.Id); // 获取网络适配器的标识符
                    Console.WriteLine("Name ................ : {0}", adapter.Name); // 获取网络适配器的名称
                    Console.WriteLine("Description ......... : {0}", adapter.Description); // 获取接口的描述
                    Console.WriteLine("Interface type ...... : {0}", adapter.NetworkInterfaceType); // 获取接口类型
                    Console.WriteLine("Is receive only...... : {0}", adapter.IsReceiveOnly); // 获取 Boolean 值,该值指示网络接口是否设置为仅接收数据包。
                    Console.WriteLine("Multicast............ : {0}", adapter.SupportsMulticast); // 获取 Boolean 值,该值指示是否启用网络接口以接收多路广播数据包。
                    Console.WriteLine("Speed ............... : {0}", adapter.Speed); // 网络接口的速度
                    Console.WriteLine("Physical Address .... : {0}", adapter.GetPhysicalAddress().ToString()); // MAC 地址
    
                    IPInterfaceProperties fIPInterfaceProperties = adapter.GetIPProperties();
                    UnicastIPAddressInformationCollection UnicastIPAddressInformationCollection = fIPInterfaceProperties.UnicastAddresses;
                    foreach (UnicastIPAddressInformation UnicastIPAddressInformation in UnicastIPAddressInformationCollection)
                    {
                        if (UnicastIPAddressInformation.Address.AddressFamily == AddressFamily.InterNetwork)
                            Console.WriteLine("Ip Address .......... : {0}", UnicastIPAddressInformation.Address); // Ip 地址
                    }
    
                    Console.WriteLine();
    
                    #endregion
                }
    
                Console.ReadKey();
            }
        }
    }

    知识改变命运,奋斗成就人生!
    2009年8月3日 7:56
    版主
  • 你好,

    看一下 Win32_NetworkAdapterConfiguration class,使用 WMI Code Creator是否可以得到你需要的信息。
    http://www.microsoft.com/downloads/details.aspx?FamilyID=2cc30a64-ea15-4661-8da4-55bbc145c30e&displaylang=en
    你可以通过这个工具生成VB script, VB.NET和C#代码,来查询系统的信息。


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    2009年8月3日 9:14
    版主
  • // 网卡名称是可变的,判断网卡名称还不能完成保存能正确的区别本地网卡
    // 下面的方法更准确一些
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data.OleDb;
    using System.Data;
    using System.Net;
    using System.Net.NetworkInformation;
    using System.Net.Sockets;
    using Microsoft.Win32;
    
    namespace ConsoleDemo
    {
        /// <summary>
        /// 标题:区分本地网卡、虚拟网卡及无线网卡
        /// 作者:X.X.Y
        /// 日期:2009-08-03
        /// 描述:测试环境 VS2008 + XP
        /// </summary>
        class Program
        {
            static void Main(string[] args)
            {
                ShowNetworkInterfaceMessage();
            }
    
            /// <summary>
            /// 显示本机各网卡的详细信息
            /// </summary>
            public static void ShowNetworkInterfaceMessage()
            {
                NetworkInterface[] fNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
    
                foreach (NetworkInterface adapter in fNetworkInterfaces)
                {
                    #region " 网卡类型 "
    
                    string fCardType = "未知网卡";
                    string fRegistryKey = "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\" + adapter.Id + "\\Connection";
                    RegistryKey rk = Registry.LocalMachine.OpenSubKey(fRegistryKey, false);
    
                    if (rk != null)
                    {
                        // 区分 PnpInstanceID 
                        // 如果前面有 PCI 就是本机的真实网卡
                        // MediaSubType 为 01 则是常见网卡,02为无线网卡。
                        string fPnpInstanceID = rk.GetValue("PnpInstanceID", "").ToString();
                        int fMediaSubType = Convert.ToInt32(rk.GetValue("MediaSubType", 0));
    
                        if (fPnpInstanceID.Length > 3 &&
                            fPnpInstanceID.Substring(0, 3) == "PCI")
                            fCardType = "物理网卡";
                        else if (fMediaSubType == 1)
                            fCardType = "虚拟网卡";
                        else if (fMediaSubType == 2)
                            fCardType = "无线网卡";
                    }
    
                    #endregion
    
     
    

    知识改变命运,奋斗成就人生!

    您好 請問Virsual basic 2010該如何修改呢?

    我需要抓取無線網卡的PNP碼然後在有線網路插上去的時候 停用無線網卡

    我只會把她修改成判斷出無線網卡

    該如何抓到無線網卡的"PnpInstanceID"呢

         Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim fNetworkInterfaces() As NetworkInterface = NetworkInterface.GetAllNetworkInterfaces()
            Dim adapter As NetworkInterface
            For Each adapter In fNetworkInterfaces
                Dim fCardType As String = ""
                Dim fCardPNP As String = ""
                Dim fRegisTryKey As String = "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\" + adapter.Id + "\\Connection"
                Dim rk As RegisTryKey = RegisTry.LocalMachine.OpenSubKey(fRegisTryKey, False)

                If Not rk Is Nothing Then
                    Dim fPnpInstanceID As String = rk.GetValue("PnpInstanceID", "").ToString()
                    Dim fMediaSubType As Integer = Convert.ToInt32(rk.GetValue("MediaSubType", 0))
                    If fMediaSubType = 2 Then
                        fCardType = "無線網卡"
                        fCardPNP = fPnpInstanceID
                    End If
                End If

                If fCardType = "無線網卡" Then
                    MsgBox(fCardType & fCardPNP)
                End If
            Next
        End Sub


     謝謝





    • 已编辑 X Z 2012年4月13日 9:19
    2012年4月13日 9:05