PoshCode Archive  Artifact [38484d8a99]

Artifact 38484d8a99aeee64e1787d2213eba3c53157c00045bad443730543124dda7e47:

  • File Get-MACFromIP.ps1 — part of check-in [c13ddbc9f3] at 2018-06-10 13:15:27 on branch trunk — Get the MAC Address of an existing IP using SendARP request. (user: bar971it size: 1708)

# encoding: ascii
# api: csharp
# title: Get-MACFromIP
# description: Get the MAC Address of an existing IP using SendARP request.
# version: 0.1
# type: function
# author: bar971it
# license: CC0
# function: Get-MACFromIP
# x-poshcode-id: 2763
# x-archived: 2011-12-29T21:47:37
# x-published: 2011-07-02T03:06:00
#
# ( please visit bar971.it and/or dimmiunapassword.com. Thank You)
#
Function Get-MACFromIP {
param ($IPAddress)

$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


$type::GetMacAddress($IPAddress)

}