ASP.NET 获取客户端IP、MAC地址

这篇具有很好参考价值的文章主要介绍了ASP.NET 获取客户端IP、MAC地址。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

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>

aspx获取客户端ip地址,个人笔记,Asp.Net,asp.net,tcp/ip,macos 

qqwry.dat 纯真IP数据库下载地址: 

https://www.duote.com/soft/848527.html

 文章来源地址https://www.toymoban.com/news/detail-618234.html

到了这里,关于ASP.NET 获取客户端IP、MAC地址的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • JAVA获取客户端IP地址

    2024年02月16日
    浏览(49)
  • 【JavaScript】如何获取客户端IP地址?

    使用这个库:request-ip 它按照如下顺序获取请求的IP地址: X-Client-IP X-Forwarded-For (Header may return multiple IP addresses in the format: “client IP, proxy 1 IP, proxy 2 IP”, so we take the first one.) CF-Connecting-IP (Cloudflare) Fastly-Client-Ip (Fastly CDN and Firebase hosting header when forwared to a cloud function) True-Clie

    2024年02月05日
    浏览(49)
  • Java 获取客户端请求IP地址

    2024年02月15日
    浏览(45)
  • 获取客户端真实 IP 地址的最佳实践

    1. 业务上云带来性能收益 公司从去年全面推动业务上云,而以往 IDC 架构部署上,接入层采用典型的 4 层 LVS 多机房容灾架构,在业务高峰时期,扩容困难(受限于物理机资源和 LVS 内网网段的网络规划),且抵挡不住 HTTPS 卸载引发的高 CPU 占用。 而经过压力测试发现,使用

    2024年02月05日
    浏览(58)
  • Java WebSocket 获取客户端 IP 地址

    在开发 Web 应用程序时,我们通常需要获取客户端的 IP 地址用于日志记录、身份验证、限制访问等操作。当使用 WebSocket 协议时,我们可以使用 Java WebSocket API 来获取客户端的 IP 地址。 本文将介绍如何使用 Java WebSocket API 获取客户端 IP 地址,以及如何在常见的 WebSocket 框架中

    2024年02月05日
    浏览(45)
  • Nginx代理后获取客户端真实IP地址

    在项目实际应用中,我们可能会需要获取到用户也就是客户端的真实IP地址,比如记录系统操作日志等情况。 通常情况下我们可以使用以下方式来获取IP地址 但是当我们使用Nginx反向代理项目地址后,使用以上方法只能获取到Nginx服务器的IP地址,并不是客户端的IP地址。 解决

    2023年04月11日
    浏览(48)
  • 【Java开发】之获取客户端真实 IP 地址

    在投票系统开发中,为了防止刷票,我们需要限制每个 IP 地址只能投票一次; 当网站受到诸如 DDoS(Distributed Denial of Service,分布式拒绝服务攻击)等攻击时,我们需要快速定位攻击者 IP; 在渗透测试过程中,经常会碰到网站有 CDN(Content Distribution Network,内容交付网络),

    2024年02月04日
    浏览(48)
  • Qt 获取本机 ip地址方法 获取客户端ip和端口的方法

    上述函数返回本机所有IPv4的ip地址列表,比如192.168.1.10|192.166.1.95 其它方法=》 获取客户端IP地址:

    2024年02月14日
    浏览(42)
  • Docker部署Nginx,无法获取客户端真实ip地址

    在部署docker版本nginx进行请求转发,意外发现nginx打印日志中的客户端ip并非为客户端的真实ip(221.237.xxx.xxx),而是docker虚拟网卡的ip(172.17.0.1) 开始猜测是nginx配置问题,对比其他环境,发现配置相同,但其他环境未出现此情况 通过查询资料,推测是docker网桥和linux防火墙存在

    2023年04月21日
    浏览(38)
  • Java编程技巧:获取ip地址、通过ip获取地理位置、获取客户端操作系统、获取客户端浏览器、获取主机名、获取操作系统、获取系统架构

    说明: 大家直接去对应项目位置找到代码,然后看着复制就行了 1.1、若依(自己写的代码) 项目:https://gitee.com/y_project/RuoYi 子模块:ruoyi-common 所在类:com.ruoyi.common.utils.IpUtils 所在方法:getIpAddr 详细位置:整个方法 1.2、Snowy(借助hutool工具包) 项目:https://gitee.com/xiaonuo

    2024年02月04日
    浏览(128)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包