using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebTest.ajax
{
public partial class ajaxHander : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string json = "\"\"";
string type = Request.Form["type"].ToString();
switch (type)
{
case "checkip"://录音文件查询
#region
string UserHostAddress = HttpContext.Current.Request.UserHostAddress;//客户端公网IP地址
string UserAgent = HttpContext.Current.Request.UserAgent; //客户端完整用户代理字符串
string UserHostName = HttpContext.Current.Request.UserHostName; //客户端DNS名称
//方法一
string str1= HttpContext.Current.Request.UserHostAddress;//::1
//方法二
string str2 = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];//::1
//方法三
string strHostName = System.Net.Dns.GetHostName();//zh-yinsheng
string IPv6 = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString();//10.199.6.45
string IPv4 = System.Net.Dns.GetHostAddresses(strHostName).GetValue(1).ToString();//2.0.0.1
//方法四(无视代理)
string str3 = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
string LIP = string.Empty;
string SIP = string.Empty;
string IP = string.Empty;
System.Net.IPAddress[] addressList = System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName()).AddressList;
if (addressList.Length > 1)
{
LIP = addressList[0].ToString();//10.199.6.45
SIP = addressList[1].ToString();//2.0.0.1
IP = addressList[2].ToString();//192.168.43.61
}
else
{
IP = addressList[0].ToString();//192.168.43.61
}
string result = Context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(result))
{
result = Context.Request.ServerVariables["REMOTE_ADDR"];//::1
}
#region 获取客户端IP
string userIP;
HttpRequest Request = HttpContext.Current.Request;
// 如果使用代理,获取真实IP
if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] == "")
userIP = Request.ServerVariables["REMOTE_ADDR"];
else
userIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (userIP == null || userIP == "")
userIP = Request.UserHostAddress;
#endregion
#region
获取客户端ip地址
//string ipAddress = HttpContext.Current.Request.UserHostAddress.ToString().Trim();
调用函数得到mac地址
//string macAddress = GetMac(IP);
#endregion
#region 根据ip获取mac地址
string mac = GetClientMAC();//00-FF-09-A7-86-57
#endregion
#region MyRegion
string loginip = System.Web.HttpContext.Current.Request.UserHostAddress; //获取IP
loginip = IP;//测试使用
QQWryLocator qqsry = new QQWryLocator(Server.MapPath("~/ajax/QQWry.Dat")); //http://www.cz88.net/下载
IPLocation ip = qqsry.Query(loginip);
string City = ip.Country; //ip.Country获取地区名
#endregion
Response.Write(json);
break;
#endregion
}
Response.End();
}
#region MyRegion
//通过IP地址获取MAC地址的方法(可跨网段获取)
string GetMac(string IP)
{
string dirResults = "";
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo();
System.Diagnostics.Process proc = new System.Diagnostics.Process();
psi.FileName = "nbtstat";
psi.RedirectStandardInput = false;
psi.RedirectStandardOutput = true;
psi.Arguments = "-A " + IP;
psi.UseShellExecute = false;
proc = System.Diagnostics.Process.Start(psi);
dirResults = proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
dirResults = dirResults.Replace("\r", "").Replace("\n", "").Replace("\t", "");
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("Mac[ ]{0,}Address[ ]{0,}=[ ]{0,}(?<key>((.)*?))__MAC", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Compiled);
System.Text.RegularExpressions.Match mc = reg.Match(dirResults + "__MAC");
if (mc.Success)
{ return mc.Groups["key"].Value; }
else
{
reg = new System.Text.RegularExpressions.Regex("Host not found", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Compiled);
mc = reg.Match(dirResults);
if (mc.Success)
{
return "Host not found!";
}
else
{ return ""; }
}
}
#endregion
#region 根据ip获取mac地址
[System.Runtime.InteropServices.DllImport("Iphlpapi.dll")]
private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
[System.Runtime.InteropServices.DllImport("Ws2_32.dll")]
private static extern Int32 inet_addr(string ip);
private string GetClientMAC()
{
string mac_dest = string.Empty;
// 在此处放置用户代码以初始化页面
try
{
string userip = Request.UserHostAddress;
string strClientIP = Request.UserHostAddress.ToString().Trim();//::1
Int32 ldest = inet_addr(strClientIP); //目的地的ip
Int32 lhost = 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");
}
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));
}
}
}
}
catch (Exception ex)
{
throw ex;
}
return mac_dest;///00-FF-09-A7-86-57
}
#endregion
}
}
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace WebTest.ajax
{
public class IPLocation
{
private string _IP;
private string _Country;
private string _Local;
public string IP
{
get { return _IP; }
set { _IP = value; }
}
public string Country
{
get { return _Country; }
set { _Country = value; }
}
public string Local
{
get { return _Local; }
set { _Local = value; }
}
}
public class QQWryLocator
{
private byte[] data;
Regex regex = new Regex(@"(((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))");
long firstStartIpOffset;
long lastStartIpOffset;
long ipCount;
public long Count { get { return ipCount; } }
public QQWryLocator(string dataPath)
{
using (FileStream fs = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
data = new byte[fs.Length];
fs.Read(data, 0, data.Length);
}
byte[] buffer = new byte[8];
Array.Copy(data, 0, buffer, 0, 8);
firstStartIpOffset = ((buffer[0] + (buffer[1] * 0x100)) + ((buffer[2] * 0x100) * 0x100)) + (((buffer[3] * 0x100) * 0x100) * 0x100);
lastStartIpOffset = ((buffer[4] + (buffer[5] * 0x100)) + ((buffer[6] * 0x100) * 0x100)) + (((buffer[7] * 0x100) * 0x100) * 0x100);
ipCount = Convert.ToInt64((double)(((double)(lastStartIpOffset - firstStartIpOffset)) / 7.0));
if (ipCount <= 1L)
{
throw new ArgumentException("ip FileDataError");
}
}
private static long IpToInt(string ip)
{
char[] separator = new char[] { '.' };
if (ip.Split(separator).Length == 3)
{
ip = ip + ".0";
}
string[] strArray = ip.Split(separator);
long num2 = ((long.Parse(strArray[0]) * 0x100L) * 0x100L) * 0x100L;
long num3 = (long.Parse(strArray[1]) * 0x100L) * 0x100L;
long num4 = long.Parse(strArray[2]) * 0x100L;
long num5 = long.Parse(strArray[3]);
return (((num2 + num3) + num4) + num5);
}
private static string IntToIP(long ip_Int)
{
long num = (long)((ip_Int & 0xff000000L) >> 0x18);
if (num < 0L)
{
num += 0x100L;
}
long num2 = (ip_Int & 0xff0000L) >> 0x10;
if (num2 < 0L)
{
num2 += 0x100L;
}
long num3 = (ip_Int & 0xff00L) >> 8;
if (num3 < 0L)
{
num3 += 0x100L;
}
long num4 = ip_Int & 0xffL;
if (num4 < 0L)
{
num4 += 0x100L;
}
return (num.ToString() + "." + num2.ToString() + "." + num3.ToString() + "." + num4.ToString());
}
public IPLocation Query(string ip)
{
if (!regex.Match(ip).Success)
{
throw new ArgumentException("IP格式错误");
}
IPLocation ipLocation = new IPLocation();
ipLocation.IP = ip;
long intIP = IpToInt(ip);
if ((intIP >= IpToInt("127.0.0.1") && (intIP <= IpToInt("127.255.255.255"))))
{
ipLocation.Country = "本机内部环回地址";
ipLocation.Local = "";
}
else
{
if ((((intIP >= IpToInt("0.0.0.0")) && (intIP <= IpToInt("2.255.255.255"))) || ((intIP >= IpToInt("64.0.0.0")) && (intIP <= IpToInt("126.255.255.255")))) ||
((intIP >= IpToInt("58.0.0.0")) && (intIP <= IpToInt("60.255.255.255"))))
{
ipLocation.Country = "网络保留地址";
ipLocation.Local = "";
}
}
long right = ipCount;
long left = 0L;
long middle = 0L;
long startIp = 0L;
long endIpOff = 0L;
long endIp = 0L;
int countryFlag = 0;
while (left < (right - 1L))
{
middle = (right + left) / 2L;
startIp = GetStartIp(middle, out endIpOff);
if (intIP == startIp)
{
left = middle;
break;
}
if (intIP > startIp)
{
left = middle;
}
else
{
right = middle;
}
}
startIp = GetStartIp(left, out endIpOff);
endIp = GetEndIp(endIpOff, out countryFlag);
if ((startIp <= intIP) && (endIp >= intIP))
{
string local;
ipLocation.Country = GetCountry(endIpOff, countryFlag, out local);
ipLocation.Local = local;
}
else
{
ipLocation.Country = "未知";
ipLocation.Local = "";
}
return ipLocation;
}
private long GetStartIp(long left, out long endIpOff)
{
long leftOffset = firstStartIpOffset + (left * 7L);
byte[] buffer = new byte[7];
Array.Copy(data, leftOffset, buffer, 0, 7);
endIpOff = (Convert.ToInt64(buffer[4].ToString()) + (Convert.ToInt64(buffer[5].ToString()) * 0x100L)) + ((Convert.ToInt64(buffer[6].ToString()) * 0x100L) * 0x100L);
return ((Convert.ToInt64(buffer[0].ToString()) + (Convert.ToInt64(buffer[1].ToString()) * 0x100L)) + ((Convert.ToInt64(buffer[2].ToString()) * 0x100L) * 0x100L)) + (((Convert.ToInt64(buffer[3].ToString()) * 0x100L) * 0x100L) * 0x100L);
}
private long GetEndIp(long endIpOff, out int countryFlag)
{
byte[] buffer = new byte[5];
Array.Copy(data, endIpOff, buffer, 0, 5);
countryFlag = buffer[4];
return ((Convert.ToInt64(buffer[0].ToString()) + (Convert.ToInt64(buffer[1].ToString()) * 0x100L)) + ((Convert.ToInt64(buffer[2].ToString()) * 0x100L) * 0x100L)) + (((Convert.ToInt64(buffer[3].ToString()) * 0x100L) * 0x100L) * 0x100L);
}
/// <summary>
/// Gets the country.
/// </summary>
/// <param name="endIpOff">The end ip off.</param>
/// <param name="countryFlag">The country flag.</param>
/// <param name="local">The local.</param>
/// <returns>country</returns>
private string GetCountry(long endIpOff, int countryFlag, out string local)
{
string country = "";
long offset = endIpOff + 4L;
switch (countryFlag)
{
case 1:
case 2:
country = GetFlagStr(ref offset, ref countryFlag, ref endIpOff);
offset = endIpOff + 8L;
local = (1 == countryFlag) ? "" : GetFlagStr(ref offset, ref countryFlag, ref endIpOff);
break;
default:
country = GetFlagStr(ref offset, ref countryFlag, ref endIpOff);
local = GetFlagStr(ref offset, ref countryFlag, ref endIpOff);
break;
}
return country;
}
private string GetFlagStr(ref long offset, ref int countryFlag, ref long endIpOff)
{
int flag = 0;
byte[] buffer = new byte[3];
while (true)
{
//用于向前累加偏移量
long forwardOffset = offset;
flag = data[forwardOffset++];
//没有重定向
if (flag != 1 && flag != 2)
{
break;
}
Array.Copy(data, forwardOffset, buffer, 0, 3);
forwardOffset += 3;
if (flag == 2)
{
countryFlag = 2;
endIpOff = offset - 4L;
}
offset = (Convert.ToInt64(buffer[0].ToString()) + (Convert.ToInt64(buffer[1].ToString()) * 0x100L)) + ((Convert.ToInt64(buffer[2].ToString()) * 0x100L) * 0x100L);
}
if (offset < 12L)
{
return "";
}
return GetStr(ref offset);
}
private string GetStr(ref long offset)
{
byte lowByte = 0;
byte highByte = 0;
StringBuilder stringBuilder = new StringBuilder();
byte[] bytes = new byte[2];
Encoding encoding = Encoding.GetEncoding("GB2312");
while (true)
{
lowByte = data[offset++];
if (lowByte == 0)
{
return stringBuilder.ToString();
}
if (lowByte > 0x7f)
{
highByte = data[offset++];
bytes[0] = lowByte;
bytes[1] = highByte;
if (highByte == 0)
{
return stringBuilder.ToString();
}
stringBuilder.Append(encoding.GetString(bytes));
}
else
{
stringBuilder.Append((char)lowByte);
}
}
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>JavaScript获取客户端IP[利用接口]</title>
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div>
<h3>方法:使用搜狐接口(所有的平台及浏览器)JS无法获取到客户端端口号以及mac地址</h3>
<script src="http://pv.sohu.com/cityjson?ie=utf-8"></script>
<script type="text/javascript">
document.write(returnCitySN["cip"] + ',' + returnCitySN["cname"]);
console.log(returnCitySN);
</script>
</div>
<div>
<input id="btncheckip" type="button" style="height:30px;margin-left:5px;" value="查询ip" />
</div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function () {
//查询ip
$("#btncheckip").click(function () {
$.ajax({
type: "post",
url: '../ajax/ajaxHander.aspx',
data: "type=checkip",
dataType: "json",
success: function (data) {
if (data != "") {
}
}
});
});
});
</script>
qqwry.dat 纯真IP数据库下载地址: 文章来源:https://www.toymoban.com/news/detail-618234.html
https://www.duote.com/soft/848527.html
文章来源地址https://www.toymoban.com/news/detail-618234.html
到了这里,关于ASP.NET 获取客户端IP、MAC地址的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!