C# 获取局域网内IP的MAC
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Net;
namespace MacApp
{
public partial class Form1 : Form
{
[DllImport("ws2_32.dll")]
private static extern int inet_addr(string cp);
[DllImport("IPHLPAPI.dll")]
private static extern int SendARP(Int32 DestIP, Int32 SrcIP, ref Int64 pMacAddr, ref Int32 PhyAddrLen);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
richTextBox1.Text = GetMacAddress(textBox1.Text);//获取远程IP(不能跨网段)的MAC地址
}
private string GetMacAddress(string hostip)//获取远程IP(不能跨网段)的MAC地址
{
string Mac = "";
try
{
Int32 ldest = inet_addr(hostip); //将IP地址从 点数格式转换成无符号长整型
Int64 macinfo = new Int64();
Int32 len = 6;
SendARP(ldest, 0, ref macinfo, ref len);
string TmpMac = Convert.ToString(macinfo, 16).PadLeft(12,'0');//转换成16进制 注意有些没有十二位
Mac = TmpMac.Substring(0, 2).ToUpper();//
for (int i = 2; i < TmpMac.Length; i = i + 2)
{
Mac = TmpMac.Substring(i, 2).ToUpper() +"-"+ Mac;
}
}
catch (Exception Mye)
{
Mac = "获取远程主机的MAC错误:" + Mye.Message;
}
return Mac;
}
private void Form1_Load(object sender, EventArgs e)
{
if (Dns.GetHostEntry(Dns.GetHostName()).AddressList.Length > 0)
{
textBox1.Text= Dns.GetHostEntry(Dns.GetHostName()).AddressList[0].ToString();//获取本机IP地址
}
}
}
}