Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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,
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...