如何验证MAC ID [英] How to validate MAC ID 's

查看:70
本文介绍了如何验证MAC ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用c#.net安装软件时如何验证MAC ID.

How to validate the MAC ID''s while installing the software using c#.net.

推荐答案

Try:
Try:
static PhysicalAddress GetMacAddress()
    {
    foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
        {
        // Only consider Ethernet network interfaces
        if (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet &&
            nic.OperationalStatus == OperationalStatus.Up)
            {
            return nic.GetPhysicalAddress();
            }
        }
    return null;
    }





默认情况下,我在软件中准备了一个Mac id1.
当我将软件安装到其他系统中时.
默认macid1验证为(安装软件系统)mac id.
Mac Id1 = MacId2
两者都不一样,那时候我应该收到错误消息.
这些都只发生在软件安装时间上.

我了解一般原则:另一个MAC地址在哪里?它在什么计算机上?两者如何连接?

每个系统都有mac id吗?只有安装时间,我们才能验证它是否出于安全目的

其他系统表示任何系统.


讨厌,讨厌的问题!但是有一个解决方案:





Default I prepare one Mac id1 in to my software.
When i install my software into other system.
Default macid1 validate to (installing software system )mac id.
Mac Id1 = MacId2
Both are different not equal that time i should get Error message.
These all happened to software installing time only.

I understand the general principle: it''s where is the other MAC address? What computer is it on? How are the two connected?

Every system have mac id right? Installing time only we can validate it is secuirty purpose

other system means any system.


Nasty, nasty problem! There is a solution though:

// Get all devices on network
Dictionary<IPAddress, PhysicalAddress> all = GetAllDevicesOnLAN();
foreach (KeyValuePair<IPAddress, PhysicalAddress> kvp in all)
    {
    Console.WriteLine("IP : {0}\n MAC {1}", kvp.Key, kvp.Value);
    }


并做好工作:


And to do the work:

/// <summary>
/// MIB_IPNETROW structure returned by GetIpNetTable
/// DO NOT MODIFY THIS STRUCTURE.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
struct MIB_IPNETROW
    {
    [MarshalAs(UnmanagedType.U4)]
    public int dwIndex;
    [MarshalAs(UnmanagedType.U4)]
    public int dwPhysAddrLen;
    [MarshalAs(UnmanagedType.U1)]
    public byte mac0;
    [MarshalAs(UnmanagedType.U1)]
    public byte mac1;
    [MarshalAs(UnmanagedType.U1)]
    public byte mac2;
    [MarshalAs(UnmanagedType.U1)]
    public byte mac3;
    [MarshalAs(UnmanagedType.U1)]
    public byte mac4;
    [MarshalAs(UnmanagedType.U1)]
    public byte mac5;
    [MarshalAs(UnmanagedType.U1)]
    public byte mac6;
    [MarshalAs(UnmanagedType.U1)]
    public byte mac7;
    [MarshalAs(UnmanagedType.U4)]
    public int dwAddr;
    [MarshalAs(UnmanagedType.U4)]
    public int dwType;
    }
/// <summary>
/// GetIpNetTable external method
/// </summary>
/// <param name="pIpNetTable"></param>
/// <param name="pdwSize"></param>
/// <param name="bOrder"></param>
/// <returns></returns>
[DllImport("IpHlpApi.dll")]
[return: MarshalAs(UnmanagedType.U4)]
static extern int GetIpNetTable(IntPtr pIpNetTable, [MarshalAs(UnmanagedType.U4)] ref int pdwSize, bool bOrder);

/// <summary>
/// Error codes GetIpNetTable returns that we recognise
/// </summary>
const int ERROR_INSUFFICIENT_BUFFER = 122;
/// <summary>
/// Get the IP and MAC addresses of all known devices on the LAN
/// </summary>
/// <remarks>
/// 1) This table is not updated often - it can take some human-scale time
///    to notice that a device has dropped off the network, or a new device
///    has connected.
/// 2) This discards non-local devices if they are found - these are multicast
///    and can be discarded by IP address range.
/// </remarks>
/// <returns></returns>
private static Dictionary<IPAddress, PhysicalAddress> GetAllDevicesOnLAN()
    {
    Dictionary<IPAddress, PhysicalAddress> all = new Dictionary<IPAddress, PhysicalAddress>();
    // Add this PC to the list...
    all.Add(GetIPAddress(), GetMacAddress());
    int spaceForNetTable = 0;
    // Get the space needed
    // We do that by requesting the table, but not giving any space at all.
    // The return value will tell us how much we actually need.
    GetIpNetTable(IntPtr.Zero, ref spaceForNetTable, false);
    // Allocate the space
    // We use a try-finally block to ensure release.
    IntPtr rawTable = IntPtr.Zero;
    try
        {
        rawTable = Marshal.AllocCoTaskMem(spaceForNetTable);
        // Get the actual data
        int errorCode = GetIpNetTable(rawTable, ref spaceForNetTable, false);
        if (errorCode != 0)
            {
            // Failed for some reason - can do no more here.
            throw new Exception(string.Format("Unable to retrieve network table. Error code {0}", errorCode));
            }
        // Get the rows count
        int rowsCount = Marshal.ReadInt32(rawTable);
        IntPtr currentBuffer = new IntPtr(rawTable.ToInt64() + Marshal.SizeOf(typeof(Int32)));
        // Convert the raw table to individual entries
        MIB_IPNETROW[] rows = new MIB_IPNETROW[rowsCount];
        for (int index = 0; index < rowsCount; index++)
            {
            rows[index] = (MIB_IPNETROW)Marshal.PtrToStructure(new IntPtr(currentBuffer.ToInt64() +
                                                                            (index * Marshal.SizeOf(typeof(MIB_IPNETROW)))
                                                                           ),
                                                                 typeof(MIB_IPNETROW));
            }
        // Define the dummy entries list (we can discard these)
        PhysicalAddress virtualMAC = new PhysicalAddress(new byte[] { 0, 0, 0, 0, 0, 0 });
        PhysicalAddress broadcastMAC = new PhysicalAddress(new byte[] { 255, 255, 255, 255, 255, 255 });
        foreach (MIB_IPNETROW row in rows)
            {
            IPAddress ip = new IPAddress(BitConverter.GetBytes(row.dwAddr));
            byte[] rawMAC = new byte[] { row.mac0, row.mac1, row.mac2, row.mac3, row.mac4, row.mac5 };
            PhysicalAddress pa = new PhysicalAddress(rawMAC);
            if (!pa.Equals(virtualMAC) && !pa.Equals(broadcastMAC) && !IsMulticast(ip))
                {
                //Console.WriteLine("IP: {0}\t\tMAC: {1}", ip.ToString(), pa.ToString());
                if (!all.ContainsKey(ip))
                    {
                    all.Add(ip, pa);
                    }
                }
            }
        }
    finally
        {
        // Release the memory.
        Marshal.FreeCoTaskMem(rawTable);
        }
    return all;
    }
/// <summary>
/// Gets the IP address of the current PC
/// </summary>
/// <returns></returns>
private static IPAddress GetIPAddress()
    {
    String strHostName = Dns.GetHostName();
    IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
    IPAddress[] addr = ipEntry.AddressList;
    foreach (IPAddress ip in addr)
        {
        if (!ip.IsIPv6LinkLocal)
            {
            return (ip);
            }
        }
    return addr.Length > 0 ? addr[0] : null;
    }
/// <summary>
/// Gets the MAC address of the current PC.
/// </summary>
/// <returns></returns>
private static PhysicalAddress GetMacAddress()
    {
    foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
        {
        // Only consider Ethernet network interfaces
        if (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet &&
            nic.OperationalStatus == OperationalStatus.Up)
            {
            return nic.GetPhysicalAddress();
            }
        }
    return null;
    }

/// <summary>
/// Returns true if the specified IP address is a multicast address
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
private static bool IsMulticast(IPAddress ip)
    {
    bool result = true;
    if (!ip.IsIPv6Multicast)
        {
        byte highIP = ip.GetAddressBytes()[0];
        if (highIP < 224 || highIP > 239)
            {
            result = false;
            }
        }
    return result;
    }


这篇关于如何验证MAC ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆