Another small function from me today. And another one that I can’t take credit for. I found this one on poshcode, and just did some minor tweaking to it. It sends an ARP request to get the MAC address from an IPv4 address.

function Get-MACAddress {
<#
.SYNOPSIS
Sends an Address Resolution Protocol (ARP) request to obtain the physical address that corresponds to the specified destination IPv4 address.
.NOTES
http://poshcode.org/2763
#>
param (
[Parameter(Position = 0)]
[ValidateNotNullorEmpty()]
[string] $IPAddress = ([System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces() | Where-Object {$_.OperationalStatus -eq 'Up' -and $_.NetworkInterfaceType -ne [System.Net.NetworkInformation.NetworkInterfaceType]::Loopback})[0].GetIPProperties().UnicastAddresses.Address.ToString()
)
$sign = @"
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
public static class NetUtils
{
[System.Runtime.InteropServices.DllImport("iphlpapi.dll", ExactSpelling = true)]
static extern int SendARP(int DestIP, int SrcIP, byte[] pMacAddr, ref int PhyAddrLen);
public static string GetMacAddress(String addr)
{
try
{
IPAddress IPaddr = IPAddress.Parse(addr);
byte[] mac = new byte[6];
int L = 6;
SendARP(BitConverter.ToInt32(IPaddr.GetAddressBytes(), 0), 0, mac, ref L);
String macAddr = BitConverter.ToString(mac, 0, L);
return (macAddr.Replace('-',':'));
}
catch (Exception ex)
{
return (ex.Message);
}
}
}
"@
$type = Add-Type TypeDefinition $sign Language CSharp PassThru
Write-Output ($type::GetMacAddress($IPAddress))
}

view raw
Get-MACAddress.ps1
hosted with ❤ by GitHub

2 comments

  1. Hey, how are you doing old friend?
    Since PowerShell 4.0 (Windows 8.1 / Server 2012 R2), there is a cmdlet called “Get-NetAdapater”. It returns all network information from the local adapters that are currently present on the machine. It also has a -CimSession parameter that can be used to query information remotely 😉

    Like

    1. Hey. I’m doing fine thank you 🙂 I realised after the fact, that I should perhaps have given the function another name. It was really written to be able to discover MAC addresses using ARP, so you can get the MAC of for instance network equipment etc.

      Liked by 1 person

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s