获取客户端IP:
Response.Write("Client IP Type 1:" + Page.Request.UserHostAddress + "<br>");
string _sClientIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? Request.ServerVariables["REMOTE_ADDR"];
Response.Write("Client IP Type 2:" + _sClientIP + "<br>");
而获取客户端Mac地址需要投机实现,譬如借助nbtstat
关于nbtstat详情,请参见:http://baike.baidu.com/view/416527.htm
具体代码实现:
public static string GetClientMacByNbtstat(string _sClientIP)
{
string _sMacAddress = null;
try
{
ProcessStartInfo _proStart = new ProcessStartInfo();
Process _proc = new Process();
StringBuilder sb = new StringBuilder();
_proStart.FileName = "nbtstat";
_proStart.RedirectStandardInput = false;
_proStart.RedirectStandardOutput = true;
_proStart.UseShellExecute = false;
_proStart.Arguments = "-A " + _sClientIP;
_proc = Process.Start(_proStart);
using (StreamReader _srRead = _proc.StandardOutput)
{
while (!_srRead.EndOfStream)
{
_sMacAddress = _srRead.ReadLine();
if (_sMacAddress.ToUpper().IndexOf("MAC") != -1)
{
_sMacAddress = _sMacAddress.Substring(_sMacAddress.LastIndexOf("=") + 1);
break;
}
}
_proc.WaitForExit();
}
_proc.Dispose();
_proc.Close();
}
catch
{
_sMacAddress = string.Empty;
}
return _sMacAddress;
}
第二种获取方式参考了 http://www.cnblogs.com/linyc/archive/2011/04/02/2002849.html 进行小小的修改,具体代码如下:
[DllImport("Ws2_32.dll")]
private static extern Int32 inet_addr(string ip);
[DllImport("Iphlpapi.dll")]
private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
public static string GetClientMac(string _sClientIP)
{
string _sMacAddress = string.Empty;
try
{
Int32 _nDescIp = inet_addr(_sClientIP);
Int32 _nLocalHost = inet_addr(string.Empty);
Int64 _nMacInfo = new Int64();
Int32 len = 6;
int _nClientMacInfo = SendARP(_nDescIp, 0, ref _nMacInfo, ref len);
_sMacAddress = _nMacInfo.ToString("X");
int _nMacLength = _sMacAddress.Length;
if (_nMacLength == 12)
{
StringBuilder _sbMac = new StringBuilder();
for (int i = _nMacLength; i > 0; i--)
{
if (i % 2 == 0)
_sbMac.AppendFormat("{0} ", _sMacAddress.Substring(i - 2, 2));
}
_sMacAddress = _sbMac.ToString().TrimEnd().Replace(' ', '-');
}
}
catch
{
_sMacAddress = string.Empty;
}
return _sMacAddress;
}
实现效果:
而读取到数据如图:
在局域网里面测试通过,其他情况还未测试,希望有所帮助吧。
<script type="text/javascript"> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>