日期:2014-05-19  浏览次数:21129 次

求助:如何用C#语言编程获取本地默认网关的IP和MAC地址!
如何用C#语言编程获取本地默认网关的IP和MAC地址!

------解决方案--------------------
[DllImport( "Iphlpapi.dll ")]
private static extern int SendARP(Int32 dest,Int32 host,ref Int64 mac,ref Int32 length);
[DllImport( "Ws2_32.dll ")]
private static extern Int32 inet_addr(string ip);

///
/// 根据ip得到网卡mac地址
///
/// 给出的ip地址
/// 对应ip的网卡mac地址
public static Int64 GetMACByIP(string ip)
{
Int32 ldest= inet_addr(ip); //目的地的ip
try
{
Int64 macinfo = new Int64();
Int32 len = 6;
int res = SendARP(ldest,0, ref macinfo, ref len);
return macinfo;
}
catch(Exception err)
{
Console.WriteLine( "Error:{0} ",err.Message);
}
return 0;
}

添加:using System.Runtime.InteropServices;
可以取得
------解决方案--------------------
ProcessStartInfo psi = new ProcessStartInfo( "arp.exe ", "-a 157.60.150.1 ");
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
Process p = Process.Start(psi);
string output = p.StandardOutput.ReadToEnd();
Console.WriteLine(Regex.Match(output, @ "([0-9A-F]{2}-){5}[0-9A-F]{2} ").Value);
已经网关调用arp获得物理地址
------解决方案--------------------
#region 根据IP获得MAC地址
/// <summary>
/// 获得一般地址MAC(测试不能获得网关MAC)
/// </summary>
/// <param name= "ip "> </param>
/// <returns> </returns>
private string GetMac(string ip)
{
string str1=string.Empty;
string str2=string.Empty;

ProcessStartInfo info1 = new ProcessStartInfo();
Process process1 = new Process();

info1.FileName = " nbtstat ";
info1.RedirectStandardInput = false;
info1.RedirectStandardOutput = true;
info1.Arguments = " -A " + ip;
info1.UseShellExecute = false;
process1 = Process.Start(info1);

str2 = process1.StandardOutput.ReadToEnd();
str1 = Regex.Match(str2.ToUpper(), @ "([0-9A-F]{2}-){5}[0-9A-F]{2} ").Value;

return str1;
}

/// <summary>
/// 测试获得网关MAC,不能获得一般MAC
/// </summary>
/// <param name= "ip "> </param>
/// <returns> </returns>
private string GetMacs(string ip)
{
string str1 = string.Empty;
string str2 = string.Empty;

ProcessStartInfo info1 = new ProcessStartInfo();
Process process1 = new Process();

info1.FileName = " arp ";
info1.RedirectStandardInput = false;
info1.RedirectStandardOutput = true;
info1.Arguments = " -a " + ip;
info1.UseShellExecute = false;
process1 = Process.Start(info1);

str2 = process1.StandardOutput.ReadToEnd();
str1 = Regex.Match(str2.ToUpper(), @ "([0-9A-F]{2}-){5}[0-9A-F]{2} ").Value;