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地址
}
}
}
}