Tuesday, August 21, 2007

How to Retrieve Remote MAC Address

 

Triggered by Lance Robinson blog post, here is another (quick & dirty, not heavily tested) way to get remote MAC address:

 

function Get-MacAddress{

    param( [string]$ip= $(throw "Please specify IP number") )

    arp -d; # clear arp cache
    $ping = (new-object System.Net.NetworkInformation.Ping).Send($ip);
    $mac = arp -a;
    if($ping){
        ($mac | ? {$_ -match $ip}) -match "([0-9A-F]{2}([:-][0-9A-F]{2}){5})" | out-null;
        $matches[0];
    }
}

 

 

The manual version:

1. Ping the remote machine.
2. Check the local ARP table for a match.

 

C:\WINDOWS>ping 10.0.0.101

Pinging 10.0.0.101 with 32 bytes of data:

Reply from 10.0.0.101: bytes=32 time=2ms TTL=128
Reply from 10.0.0.101: bytes=32 time=1ms TTL=128
Reply from 10.0.0.101: bytes=32 time=1ms TTL=128
Reply from 10.0.0.101: bytes=32 time=1ms TTL=128

Ping statistics for 10.0.0.101:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 1ms, Maximum = 2ms, Average = 1ms

C:\WINDOWS>arp -a

Interface: 10.0.0.105 --- 0x4
  Internet Address      Physical Address      Type
  10.0.0.101            00-09-6b-c6-ab-29     dynamic
  10.0.0.138            00-16-e3-37-d2-47     dynamic

 

Shay

10 comments:

Unknown said...

Here's another "old-fashioned" way that has been combined with PowerShell:

nbtstat -a COMPUTERNAME | select-string "MAC Address"

Shay Levy said...

Yup, even shorter. 10x Jeff

arun said...

You mean MAC address of a machine in the same network. right? Not ANY remote machine.

Mike Crowley said...

This will only work for computers on the same subnet.

Mike Crowley said...
This comment has been removed by the author.
Mike Crowley said...

This works if you have rights to query wmi (PS script):

Get-WmiObject -ComputerName Server1 -Class "Win32_NetworkAdapter" | where {$_.macaddress -ne $null} | select macaddress

Anonymous said...

this way one gets multiple macadresses
Get-WmiObject -ComputerName Server1 -Class "Win32_NetworkAdapter" | where {$_.macaddress -ne $null} | select macaddress

this way one gets only one
gwmi -Class Win32_NetworkAdapterConfiguration -Filter "IpEnabled=True" -computername computer

Tao said...

to @Jeff's suggestion above, watch out for non-english versions of windows! (also, nbtstat is v slow :( )

With respect to the original solution, as you are looking for subnet-local ping responses you can specify the optional ping timeout parameter with a low value, in case you frequently expect the ping to fail:

.Send($ip, 200)

Unknown said...

Don't know but curious to know retrieve mac address of remote computers.

Thanks
Silvester Norman

Changing MAC Address

Shay Levy said...

@Silvester see the WMI Win32_NetworkAdapter example a few comments above.