SIN@SAPPOROWORKSの覚書

C#を中心に、夜な夜な試行錯誤したコードの記録です。

ARPによるMACアドレスの取得 (C#) (F#)

.NET Frameworkの標準ライブラリに機能が無いため、iphlpapi.dllのSendARPをインポートして使用します。この方法により、ブロードキャストネットワーク内の端末(自分自身を含む)MACアドレスを取得できます。

IPアドレスをもとに検索するので、自分自身のインターフェースでIPアドレスが設定されていないものを列挙することはできません。

C# サンプル

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Net;

namespace ARP_001 {
    class Program {

        [DllImport("iphlpapi.dll", ExactSpelling = true)]
        private static extern int SendARP(int dstIp, int srcIp, byte[] mac, ref int macLen);

        static void Main(string[] args) {
            var ipStr = "192.168.0.1";
            Console.WriteLine(string.Format("{0}へARP要求を送信します。",ipStr));

            
            IPAddress dst = IPAddress.Parse(ipStr);

            var mac = new byte[6];
            var macLen = mac.Length;
            var str = "応答なし";
            if (SendARP((int)dst.Address, 0, mac, ref macLen) == 0) {
                str = string.Format("{0:x2}-{1:x2}-{2:x2}-{3:x2}-{4:x2}-{5:x2}", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
            }
            Console.WriteLine(str);
            Console.WriteLine("何かのキーを押してください。");
            Console.ReadKey();
        }
    }
}

F# サンプル

open System
open System.Runtime.InteropServices
open System.Net

[<DllImport("iphlpapi.dll")>]  extern int SendARP(int dstIp, int srcIp, byte [] mac,int *macLen);


let ipStr = "192.168.0.1"
printfn "%sへARP要求を送信します。" ipStr

let dst = IPAddress.Parse(ipStr)
let mac : byte array = Array.create 6 0uy
let mutable macLen = 6

let result = SendARP((int)dst.Address, 0,mac,&&macLen)

if result=0 then printfn "%02x-%02x-%02x-%02x-%02x-%02x" mac.[0] mac.[1] mac.[2] mac.[3] mac.[4] mac.[5]
else printfn "応答なし"

printfn "何かのキーを押してください。"
Console.ReadKey() |> ignore