获取单个IP或IP段的MAC地址
代码:Program.cs。
执行命令示例:mac 192.168.1.3
或
mac 192.168.1.3 6
代码:
using System;
using System.Diagnostics;
namespace mac
{
class Program
{
static void OutputNullHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
//Console.WriteLine(outLine.Data);
}
static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
String str = outLine.Data;
if(str!=null && str.Contains("动态"))
Console.WriteLine(outLine.Data);
}
static void ping(String ip)
{
Process process = new Process();
process.StartInfo.FileName = "ping";
process.StartInfo.Arguments = "-w 100 " + ip;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.OutputDataReceived += new DataReceivedEventHandler(OutputNullHandler);
process.ErrorDataReceived += new DataReceivedEventHandler(OutputNullHandler);
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
}
static void getMac(String ip)
{
Process process = new Process();
process.StartInfo.FileName = "arp";
process.StartInfo.Arguments = "-a " + ip;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
process.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler);
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
}
static void Main(string[] args)
{
String ip = args[0];
int len = args.Length;
if (len > 1)
{
String endIp = args[1]; //结束ip(最末段)
int end = Convert.ToInt32(endIp);
int index = ip.LastIndexOf(".");
int start = Convert.ToInt32(ip.Substring(index + 1)); //起始ip(最末段)
String preStr = ip.Substring(0, index + 1); //ip段前缀
for (int i = start; i <= end; i++)
{
String tmpIp = preStr + i;
ping(tmpIp);
getMac(tmpIp);
}
return;
}
ping(ip);
getMac(ip);
}
}
}