欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

asp.net获取客户端IP地址网卡等

程序员文章站 2022-06-25 15:53:02
<%@ page language="c#" autoeventwireup="true" codefile="mac.x....

<%@ page language="c#" autoeventwireup="true" codefile="mac.x.cs" inherits="mac" %>

<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">

<html xmlns="">
<head runat="server">
    <title>无标题页</title>
</head>
<body>
    <form id="form1" runat="server">
    <p>
   
    </p>
    </form>
</body>
</html>

 

后台代码:

using system;
using system.collections;
using system.configuration;
using system.data;
using system.linq;
using system.web;
using system.web.security;
using system.web.ui;
using system.web.ui.htmlcontrols;
using system.web.ui.webcontrols;
using system.web.ui.webcontrols.webparts;
using system.xml.linq;
using system.runtime.interopservices;

public partial class mac : system.web.ui.page
{
    [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);


    protected void page_load(object sender, eventargs e)
    {
        // 在此处放置用户代码以初始化页面
        try
        {
            string userip = request.userhostaddress;
            string strclientip = request.userhostaddress.tostring().trim();
            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");
            if (mac_src == "0")
            {
                if (userip == "127.0.0.1")
                    response.write("正在访问localhost!");
                else
                    response.write("欢迎来自ip为" + userip + "的朋友!" + "<br>");
                return;
            }

            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));
                    }
                }
            }

            response.write("欢迎来自ip为" + userip + "<br>" + ",mac地址为" + mac_dest + "的朋友!"

             + "<br>");
        }
        catch (exception err)
        {
            response.write(err.message);
        }


    }
}

 


作者 郑文亮