Je voudrais pouvoir lire l'adresse MAC du premier adaptateur de réseau actif en utilisant VB.net ou C# (en utilisant .NET 3.5 SP1) pour une application WinformLire l'adresse MAC de la carte réseau dans .NET
Répondre
vous devez DllImport GetAdaptersInfo - ici est un code C#
http://www.codeguru.com/cpp/i-n/network/networkinformation/comments.php/c5451/?thread=60212
de http://www.dotnetjunkies.com/WebLog/jkirwan/archive/2004/02/10/6943.aspx
Dim mc As System.Management.ManagementClass
Dim mo As ManagementObject
mc = New ManagementClass("Win32_NetworkAdapterConfiguration")
Dim moc As ManagementObjectCollection = mc.GetInstances()
For Each mo In moc
If mo.Item("IPEnabled") = True Then
ListBox1.Items.Add("MAC address " & mo.Item("MacAddress").ToString())
End If
Next
Je suis sûr que vous aurez ha Il n'y a aucun problème à porter ce code en C# si vous avez besoin de
Et que se passe-t-il si le bloc-notes sur lequel ce code s'exécute a désactivé la carte réseau? – Romias
Depuis .Net 2.0, il existe une classe NetworkInterface dans l'espace de noms System.Net.NetworkInformation qui vous donnera cette information. Essayez ceci:
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus == OperationalStatus.Up)
{
Console.WriteLine(nic.GetPhysicalAddress().ToString());
break;
}
}
Fonctionne très bien. Juste besoin de changer if (nic.OperationalStatus == OperationalStatus.Up) – blak3r
Merci ça m'aide! –
est ici une classe à faire:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace MacAddress
{
class MacAddress
{
byte[] _address;
public MacAddress(byte[] b)
{
if (b == null)
throw new ArgumentNullException("b");
if (b.Length != 8)
throw new ArgumentOutOfRangeException("b");
_address = new byte[b.Length];
Array.Copy(b, _address, b.Length);
}
public byte[] Address { get { return _address; } }
public override string ToString()
{
return Address[0].ToString("X2", System.Globalization.CultureInfo.InvariantCulture) + ":" +
Address[1].ToString("X2", System.Globalization.CultureInfo.InvariantCulture) + ":" +
Address[2].ToString("X2", System.Globalization.CultureInfo.InvariantCulture) + ":" +
Address[3].ToString("X2", System.Globalization.CultureInfo.InvariantCulture) + ":" +
Address[4].ToString("X2", System.Globalization.CultureInfo.InvariantCulture) + ":" +
Address[5].ToString("X2", System.Globalization.CultureInfo.InvariantCulture);
}
public static List<MacAddress> GetMacAddresses()
{
int size = 0;
// this chunk of code teases out the first adapter info
int r = GetAdaptersInfo(null, ref size);
if ((r != IPConfigConst.ERROR_SUCCESS) && (r != IPConfigConst.ERROR_BUFFER_OVERFLOW))
{
return null;
}
Byte[] buffer = new Byte[size];
r = GetAdaptersInfo(buffer, ref size);
if (r != IPConfigConst.ERROR_SUCCESS)
{
return null;
}
AdapterInfo Adapter = new AdapterInfo();
ByteArray_To_IPAdapterInfo(ref Adapter, buffer, Marshal.SizeOf(Adapter));
List<MacAddress> addresses = new List<MacAddress>();
do
{
addresses.Add(new MacAddress(Adapter.Address));
IntPtr p = Adapter.NextPointer;
if (p != IntPtr.Zero)
{
IntPtr_To_IPAdapterInfo(ref Adapter, p, Marshal.SizeOf(Adapter));
}
else
{
break;
}
} while (true);
return addresses;
}
// glue definitions into windows
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
private struct IPAddrString
{
public IntPtr NextPointer;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 4 * 4)]
public String IPAddressString;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 4 * 4)]
public String IPMaskString;
public int Context;
}
private class IPConfigConst
{
public const int MAX_ADAPTER_DESCRIPTION_LENGTH = 128;
public const int MAX_ADAPTER_NAME_LENGTH = 256;
public const int MAX_ADAPTER_ADDRESS_LENGTH = 8;
public const int ERROR_BUFFER_OVERFLOW = 111;
public const int ERROR_SUCCESS = 0;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
private struct AdapterInfo
{
public IntPtr NextPointer;
public int ComboIndex;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = IPConfigConst.MAX_ADAPTER_NAME_LENGTH + 4)]
public string AdapterName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = IPConfigConst.MAX_ADAPTER_DESCRIPTION_LENGTH + 4)]
public string Description;
public int AddressLength;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = IPConfigConst.MAX_ADAPTER_ADDRESS_LENGTH)]
public Byte[] Address;
public int Index;
public int Type;
public int DhcpEnabled;
public IntPtr CurrentIPAddress;
public IPAddrString IPAddressList;
public IPAddrString GatewayList;
public IPAddrString DhcpServer;
public Boolean HaveWins;
public IPAddrString PrimaryWinsServer;
public IPAddrString SecondaryWinsServer;
public int LeaseObtained;
public int LeaseExpires;
}
[DllImport("Iphlpapi.dll", CharSet = CharSet.Auto)]
private static extern int GetAdaptersInfo(Byte[] PAdapterInfoBuffer, ref int size);
[DllImport("Kernel32.dll", EntryPoint = "CopyMemory")]
private static extern void ByteArray_To_IPAdapterInfo(ref AdapterInfo dst, Byte[] src, int size);
[DllImport("Kernel32.dll", EntryPoint = "CopyMemory")]
private static extern void IntPtr_To_IPAdapterInfo(ref AdapterInfo dst, IntPtr src, int size);
}
}
Et voici un code de test:
List<MacAddress> addresses = MacAddress.GetMacAddresses();
foreach (MacAddress address in addresses)
{
Console.WriteLine(address);
}
Je suis sûr que la méthode ToString pourrait être mieux, mais il Fait le travail.
using Linq..
using System.Net.NetworkInformation;
..
NetworkInterface nic =
NetworkInterface.GetAllNetworkInterfaces()
.Where(n => n.OperationalStatus == OperationalStatus.Up).FirstOrDefault();
if (nic != null)
return nic.GetPhysicalAddress().ToString();
Il ressemble à ceci est un ancien poste mais je sais que vous courrez dans ce fil à la recherche d'aide alors voici ce que je fait aujourd'hui pour obtenir les adresses MAC de toutes les interfaces réseau dans mon ordinateur portable.
tout d'abord vous devez importer les suivantes
Imports System.Net.NetworkInformation
Ceci est la fonction qui renvoie toutes les adresses MAC dans un tableau de chaînes
Private Function GetMAC() As String()
Dim MACAddresses(0) As String
Dim i As Integer = 0
Dim NIC As NetworkInterface
For Each NIC In NetworkInterface.GetAllNetworkInterfaces
ReDim Preserve MACAddresses(i)
MACAddresses(i) = String.Format("{0}", NIC.GetPhysicalAddress())
i += 1
Next
Return MACAddresses
End Function
Pour toute personne utilisant le Compact Framework plus limité (.NET v2.0 CF) le code suivant fonctionne sur Windows CE 5.0 et CE 6.0 (en lisant juste le nom d'adaptateur, mais recherche "typedef struct _IP_ADAPTER_INFO" sur MSDN pour obtenir la définition complète de la structure retournée):
private const int MAX_ADAPTER_NAME_LENGTH = 256;
[DllImport ("iphlpapi.dll", SetLastError = true)]
private static extern int GetAdaptersInfo(byte[] abyAdaptor, ref int nSize);
// ...
private static string m_szAdaptorName = "DM9CE1";
// ...
private void GetNetworkAdaptorName()
{
// The initial call is to determine the size of the memory required. This will fail
// with the error code "111" which is defined by MSDN to be "ERROR_BUFFER_OVERFLOW".
// The structure size should be 640 bytes per adaptor.
int nSize = 0;
int nReturn = GetAdaptersInfo(null, ref nSize);
// Allocate memory and get data
byte[] abyAdapatorInfo = new byte[nSize];
nReturn = GetAdaptersInfo(abyAdapatorInfo, ref nSize);
if (nReturn == 0)
{
// Find the start and end bytes of the name in the returned structure
int nStartNamePos = 8;
int nEndNamePos = 8;
while ((abyAdapatorInfo[nEndNamePos] != 0) &&
((nEndNamePos - nStartNamePos) < MAX_ADAPTER_NAME_LENGTH))
{
// Another character in the name
nEndNamePos++;
}
// Convert the name from a byte array into a string
m_szAdaptorName = Encoding.UTF8.GetString(
abyAdapatorInfo, nStartNamePos, (nEndNamePos - nStartNamePos));
}
else
{
// Failed? Use a hard-coded network adaptor name.
m_szAdaptorName = "DM9CE1";
}
}
- 1. Utilisation de la carte réseau .NET SqlConnection
- 2. C# pour la réinitialisation d'une carte réseau
- 3. Comment définir le suffixe de recherche DNS pour une carte réseau dans .net?
- 4. Comment puis-je obtenir l'adresse MAC d'une carte réseau en utilisant Delphi?
- 5. Effectuez connect() sur une carte réseau spécifique
- 6. Consommation de Webserices Vista .NET Localhost sur un réseau Wifi à partir de Mac Projet iPhone
- 7. Recherche d'un alias réseau dans .net
- 8. .Net - Relever le débit interface réseau actuel
- 9. serrures Lire en .net
- 10. Comment obtenir les statistiques de l'adaptateur réseau sous Linux/Mac OSX?
- 11. Lire des fichiers CSS dans .NET
- 12. Port de .NET C++ autonome à Mac
- 13. Problème du client .NET Remoting lors de l'exécution sur la machine avec plusieurs cartes réseau
- 14. Composition de la carte dans Fluent NHibernate
- 15. comment faire la différence entre la carte LAN et la carte de données
- 16. C++: Obtenir l'adresse MAC des cartes réseau sous Vista?
- 17. Approche de contrôle de navigation de carte - .NET
- 18. Manière efficace de lire le fichier d'index dans .NET
- 19. ASP .NET avec carte google api
- 20. Comment attendre qu'un flux réseau ait des données à lire?
- 21. Comment lire les fichiers journaux sur le réseau très rapidement?
- 22. Est-il possible de lire les fichiers .eml dans .net
- 23. Exécution d'applications .net sur un réseau protégé
- 24. Comment lire et écrire des paquets IP bruts de Java sur un mac?
- 25. comment gérer la commutation de réseau dans l'iPhone?
- 26. réseau .NET suivi uniquement pour debug
- 27. F # Problème de la carte
- 28. configuration de la structure de la carte
- 29. Dessin sur la carte
- 30. NET SEND aux utilisateurs sur réseau
Hey Lou - vous devriez vérifier avec moi avant de poster le code réel! -Steve – plinth