%@ WebHandler Language="C#" Class="getIP" %>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Text.RegularExpressions;
public class getIP : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
context.Response.Write("HostAddress:"+context.Request.UserHostAddress +"
");
context.Response.Write("HostName:"+context.Request.UserHostName +"
");
context.Response.Write("Agent:"+context.Request.UserAgent +"
");
context.Response.Write("REMOTE_ADDR:"+context.Request.ServerVariables["REMOTE_ADDR"] +"
");
context.Response.Write("HTTP_X_FORWARDED_FOR:"+context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] +"
");
string ip = context.Request.ServerVariables["REMOTE_ADDR"];
context.Response.Write("MAC:"+GetClientMac(ip) +"
");
context.Response.Write("MAC2:"+GetClientMac(ip) +"
");
}
[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);
public static string GetClientMac(string IP)
{
Int32 ldest = inet_addr(IP);
Int64 macinfo = new Int64();
Int32 len = 6;
int res = SendARP(ldest, 0, ref macinfo, ref len);
string mac_src = macinfo.ToString("X");
while (mac_src.Length < 12)
{
mac_src = mac_src.Insert(0, "0");
}
string mac_dest = "";
for (int i = 0; i < 11; i++)
{
if (0 == (i % 2))
{
if (i == 10)
{
mac_dest = mac_dest.Insert(0, mac_src.Substring(i, 2));
}
else
{
mac_dest = "-" + mac_dest.Insert(0, mac_src.Substring(i, 2));
}
}
}
return mac_dest;
}
//跨网段取Mac
public string GetMac(string IP)
{
string dirResults = "";
ProcessStartInfo psi = new ProcessStartInfo();
Process proc = new Process();
psi.FileName = "nbtstat";
psi.RedirectStandardInput = false;
psi.RedirectStandardOutput = true;
psi.Arguments = "-A " + IP;
psi.UseShellExecute = false;
proc = Process.Start(psi);
dirResults = proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
dirResults = dirResults.Replace("\r", "").Replace("\n", "").Replace("\t", "");
Regex reg = new Regex("Mac[ ]{0,}Address[ ]{0,}=[ ]{0,}(?((.)*?))__MAC", RegexOptions.IgnoreCase | RegexOptions.Compiled);
Match mc = reg.Match(dirResults + "__MAC");
if (mc.Success)
{ return mc.Groups["key"].Value; }
else
{
reg = new Regex("Host not found", RegexOptions.IgnoreCase | RegexOptions.Compiled);
mc = reg.Match(dirResults);
if (mc.Success)
{
return "Host not found!";
}
else
{ return ""; }
}
}
public bool IsReusable
{
get
{
return false;
}
}
}