2011-04-01 49 views
1

使用下面的代碼我將獲得所有在機器上啓用和運行的網絡接口。查找通過哪個網絡設備用戶連接到互聯網

Private netIntrfc As NetworkInterface() = NetworkInterface.GetAllNetworkInterfaces() 
For i As Integer = 0 To netIntrfc.Length - 1 
    If netIntrfc(i).OperationalStatus = OperationalStatus.Up Then 
    netDevicesList.Items.Add(netIntrfc(i).Name.ToString) 
    End If 
Next 

但我的問題是如何讓默認之一,通過至極用戶一個(以太網適配器)連接到互聯網?

我需要更改默認設置(,通過最終用戶連接到互聯網)適配器。設置我通過註冊表更改,所以我可以爲每個網絡接口添加相同的設置,但這可能會導致問題,並使沒有意思,然後:D

任何人都可以幫忙嗎?謝謝! ;)

編輯:

現在我已經做過類似下面的代碼,因此,如果這可以幫助其他人... :) 但如果有人有連擊的解決方案或更可靠然後發送,請

Dim u As UdpClient = New UdpClient(System.Net.Dns.GetHostName, 1) 
Dim localAddr As IPAddress = CType(u.Client.LocalEndPoint, IPEndPoint).Address 

Private netIntrfc As NetworkInterface() = NetworkInterface.GetAllNetworkInterfaces() 
For i As Integer = 0 To netIntrfc.Length - 1 
    If netIntrfc(i).OperationalStatus = OperationalStatus.Up Then 
    For Each uni As NetworkInformation.UnicastIPAddressInformation In ipProps.UnicastAddresses 
     If uni.Address.ToString = localAddr.ToString Then 
     netDevicesList.Items.Add("DEFAULT: " & netIntrfc(i).Name.ToString) 
     DEFDEVID = netIntrfc(i).Id.ToString 
     End If 
    Next 
    netDevicesList.Items.Add(netIntrfc(i).Name.ToString) 
    End If 
Next 

感謝Thomas-Lithis post

+1

這會不會給你一些提示嗎? http://stackoverflow.com/questions/359596/identifying-active-network-interface-in-net – 2011-04-01 22:38:03

+0

是的,幫助我:)希望它會工作好吧我沒有太多的資源來測試這一點,但至於我在我的電腦與3個以太網卡和一個無線它工作正常:)謝謝。你可以發表答覆,所以我接受你;) – FeRtoll 2011-04-01 23:02:04

回答

-1

我移植代碼到C#,我希望你不介意

static void Main(string[] args) 
    { 
     UdpClient u = new UdpClient(System.Net.Dns.GetHostName(), 1); 
     IPAddress localAddr = (u.Client.LocalEndPoint as IPEndPoint).Address; 
     NetworkInterface[] netIntrfc = NetworkInterface.GetAllNetworkInterfaces(); 
     for (int i = 0; i < netIntrfc.Length - 1; i++) 
     { 
      if (netIntrfc[i].OperationalStatus == OperationalStatus.Up) 
      { 
       IPInterfaceProperties ipProps = netIntrfc[i].GetIPProperties(); 
       foreach (UnicastIPAddressInformation uni in ipProps.UnicastAddresses) 
       { 
        if (uni.Address.ToString() == localAddr.ToString()) 
        { 
         Console.WriteLine("DEFAULT: " + netIntrfc[i].Name.ToString()); 
         Console.WriteLine(netIntrfc[i].Id.ToString()); 
        } 
       } 
      } 
     } 
    } 
相關問題