1. 程式人生 > >使用c#進行socket程式設計時,獲取網絡卡的資訊

使用c#進行socket程式設計時,獲取網絡卡的資訊

在進行程式設計時,有時候,我們需要知道資料包是來自哪個網絡卡,網絡卡的IP地址是多少,以便於進行進一步的操作。由於收到的資料包可能是廣播包或者是組播包,所以我們不能根據IP資料包的目的地址進行判斷。那麼使用C#進行網路程式設計時,如何獲取到資料包相關的網絡卡資訊?

我在網上查閱了一些資料,感覺有的地方有些錯誤,導致自己運行了好久都有結果,最後在我們同事的指點下,明白了。書到用時方恨少!

下面就介紹一下如何呼叫。

在C#中,有個函式 ReceiveMessageFrom()可以拿到和資料包相關的網絡卡的資訊。

public int ReceiveMessageFrom(
    byte[] buffer,
    int offset,
    int size,
    ref SocketFlags socketFlags,
    ref EndPoint remoteEP,
    out IPPacketInformation ipPacketInformation
)
在ipPacketInformation中,有個interface變數, MSDN對這個變數的解釋是這樣的。

Gets the network interface information that is associated with a call toReceiveMessageFrom orEndReceiveMessageFrom.

An Int32 value, which representstheindex of the network interface. You can use this index withGetAllNetworkInterfaces to get more information about the relevant interface.

注意index.關鍵就在這個地方。我們知道index的意思是索引,於時就會想到是 返回陣列的下標。這裡是之前在網上看的一些資料錯誤的主要原因。

在windows中,每個網絡卡都有一個index進行標識,但是index可能不是連續的。雖然GetAllNetworkInterfaces 返回一個數組,陣列的下標和 ipPacketInformation中的interface是兩個東西。那如何獲取網絡卡資訊呢,比如IP地址。

 NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();

                    foreach (NetworkInterface adapter in adapters)
                    {
                     //支援IPv4的,如果是IPv6的請改相應的函式呼叫
                        if (adapter.Supports(NetworkInterfaceComponent.IPv4) && (ipPacketInformation.Interface == adapter.GetIPProperties().GetIPv4Properties().Index))
                        {
                            UnicastIPAddressInformationCollection uniCast = adapter.GetIPProperties().UnicastAddresses;
                            if (uniCast.Count > 0)
                            {
                                Console.WriteLine(adapter.Description);
                                foreach (UnicastIPAddressInformation uni in uniCast)
                                {
                                  //得到IPv4的地址。 AddressFamily.InterNetwork指的是IPv4
                                    if (uni.Address.AddressFamily == AddressFamily.InterNetwork)
                                    {
                                        Console.WriteLine("  Unicast Address ......................... : {0}", uni.Address);
                                    }
                                }
                                Console.WriteLine();
                            }
                        }

                    }
函式的相關資訊請參考msdn.

通過這種方式我們就拿到了網絡卡相關的資訊。希望對你有所幫助。