How to get the MAC address prior to connection?

2019-06-04 22:27发布

问题:

I have a situation where I ping a range of IPs in the network. Then, I try to connect to the successful pings.

My aim is to connect to specific equipment that has a specific MAC prefix. For example, when I ping a range of 100 IPs, I might get 20 replies. These replies include computers, printers, and possibly the hardware I am trying to connect.

Currently what happens is that when I try to connect to anything other than the hardware I would like (i.e computer, printer) I get a timeout connection.

This is fine, however, it is not efficient. I would like to filter out the successful ping list by using the MAC address, however, I have not yet been able to find a solution that allows me to seek a MAC address prior to connecting the hardware.

I have looked through most the MAC questions on here, but none fit my needs.

Any ideas??

回答1:

I was able to find the solution here: http://pinvoke.net/default.aspx/iphlpapi/SendARP.html

The following method returns the MAC

internal static string GetMAC(string ip)
    {
        IPAddress dst = IPAddress.Parse(ip); // the destination IP address Note:Can Someone give the code to get the IP address of the server

        byte[] macAddr = new byte[6];
        uint macAddrLen = (uint)macAddr.Length;
        if (SendARP((int)dst.Address, 0, macAddr, ref macAddrLen) != 0)
            throw new InvalidOperationException("SendARP failed.");

        string[] str = new string[(int)macAddrLen];
        for (int i = 0; i < macAddrLen; i++)
            str[i] = macAddr[i].ToString("x2");
        return string.Join(":", str);
        //Console.WriteLine(string.Join(":", str));
    }