How can I get the MAC address of network printer via C#?

China☆狼群 提交于 2019-12-11 20:11:22

问题


I wanna get the identifier of a Intermec barcode printer, it uses network interface, so I think of MAC address. How can I get the MAC address via C#? Or I can get the serial number of the printer directly?


回答1:


I am assuming that you have the IP address of the network printer and your pc and the printer are at the same local network. You can give this program a try.

    static void Main(string[] args)
    {
        PhysicalAddress pa = LocateMacAddress(IPAddress.Parse("172.16.0.99"));
        Console.WriteLine(pa.ToString());
        Console.ReadKey();
    }
    static PhysicalAddress LocateMacAddress(IPAddress ipAddress)
    {
        if (ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
        {
            byte[] macAddressBytes = new byte[6];
            int length = macAddressBytes.Length;
            ArpErrorCodes c = (ArpErrorCodes)SendARP((uint)ipAddress.Address, 0, macAddressBytes, ref length);
            if (c == ArpErrorCodes.None)
            {
                return new PhysicalAddress(macAddressBytes);
            }
        }
        return PhysicalAddress.None;
    }

    [DllImport("iphlpapi.dll", ExactSpelling = true)]
    public static extern int SendARP(uint DestIP, uint SrcIP, [Out] byte[] pMacAddr, ref int PhyAddrLen);

}

enum ArpErrorCodes
{
    None = 0,
    ERROR_GEN_FAILURE = 31,
    ERROR_NOT_SUPPORTED = 50,
    ERROR_BAD_NET_NAME = 67,
    ERROR_BUFFER_OVERFLOW = 111,
    ERROR_NOT_FOUND = 1168,
    ERROR_INVALID_USER_BUFFER = 1784,
}


来源:https://stackoverflow.com/questions/19509874/how-can-i-get-the-mac-address-of-network-printer-via-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!