C # obtain the Client IP address and Mac address through the Web

Source: Internet
Author: User

I. Ideas (mainly used in LAN)

It is easy to obtain the Client IP address through the Web. It can be parsed from the datagram (Request object) sent by the client to the web server. However, in actual application, the proxy server must be considered, router forwarding and so on.

The process of obtaining a MAC address is complex. Because the request object sent from the client to the server does not contain the MAC address, two methods are provided to obtain the MAC address of the client:

(1). Obtain the MAC address of the client from the client. When the request arrives at the client, obtain the MAC address of the client from the client script and then transmit it to the server.

(2) first obtain the Client IP address, then send an ARP request in the LAN, and use the ARP protocol and known IP address to parse the client's MAC address

The following code obtains the IP address and MAC address, and resolves the MAC address by sending an ARP request:

2. Obtain the IP Address:

  

Public static string GetWebClientIp () {string userIP = "IP"; try {if (System. web. httpContext. current = null | System. web. httpContext. current. request = null | System. web. httpContext. current. request. serverVariables = null) return ""; string CustomerIP = ""; // the IP address CustomerIP = System obtained after CDN acceleration. web. httpContext. current. request. headers ["Cdn-Src-Ip"]; if (! String. IsNullOrEmpty (CustomerIP) {return CustomerIP;} CustomerIP = System. Web. HttpContext. Current. Request. ServerVariables ["HTTP_X_FORWARDED_FOR"]; if (! String. IsNullOrEmpty (CustomerIP) return CustomerIP; if (System. Web. HttpContext. Current. Request. ServerVariables ["HTTP_VIA"]! = Null) {CustomerIP = System. web. httpContext. current. request. serverVariables ["HTTP_X_FORWARDED_FOR"]; if (CustomerIP = null) CustomerIP = System. web. httpContext. current. request. serverVariables ["REMOTE_ADDR"];} else {CustomerIP = System. web. httpContext. current. request. serverVariables ["REMOTE_ADDR"];} if (string. compare (CustomerIP, "unknown", true) = 0) return System. web. httpContext. current. request. userHostAddress; return CustomerIP;} catch {} return userIP ;}


3. Obtain MAC addresses from IP addresses through ARP

1. Two methods to obtain MAC:

1. Only MAC of the local machine can be obtained.

    

   using System.Management;
  public string getMac()    {        ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");        ManagementObjectCollection moc2 = mc.GetInstances();        foreach (ManagementObject mo in moc2)        {            if ((bool)mo["IPEnabled"] == true)            {                return mo["MacAddress"].ToString();                mo.Dispose();            }        }        return "";    }

. Attackers can obtain MAC addresses of arbitrary local network clients.
     using System.Runtime.InteropServices;     using System.Text;
[DllImport ("Iphlpapi. dll ")] static extern int SendARP (Int32 DestIP, Int32 SrcIP, ref Int64 MacAddr, ref Int32 PhyAddrLen); [DllImport (" Ws2_32.dll ")] static extern Int32 inet_addr (string ipaddr );////// Obtain the MAC address using SendArp //////The IP address of the target machine, for example, 192.168.1.1)///
 
  
Mac address of the target machine
 Public static string GetMacAddress (string RemoteIP) {StringBuilder macAddress = new StringBuilder (); try {Int32 remote = inet_addr (RemoteIP); Int64 macInfo = new Int64 (); Int32 length = 6; sendARP (remote, 0, ref macInfo, ref length); string temp = Convert. toString (macInfo, 16 ). padLeft (12, '0 '). toUpper (); int x = 12; for (int I = 0; I <6; I ++) {if (I = 5) {macAddress. append (temp. substring (x-2, 2);} else {macAddress. append (temp. substring (x-2, 2) + "-");} x-= 2;} return macAddress. toString ();} catch {return macAddress. toString ();}}


2. Principles

First, we need to know that the switch communicates through the MAC address, but how do we obtain the MAC address of the target host? In this case, we need to use the ARP Protocol. Each host has an ARP table, which records the correspondence between the host IP address and the MAC address.

ARP is a network-layer protocol that resolves an IP address to a MAC address. The following describes how ARP works:

   

1) if host A wants to send data to host B, host A first checks its ARP cache table to check whether the IP address of host B Corresponds to the MAC address. If yes, the MAC address of host B is encapsulated into the data frame as the source MAC address. If not, host A will send an ARP request, the request's target IP address is the IP address of host B, the target MAC address is the broadcast frame of the MAC address (that is, the FF-FF-FF-FF-FF-FF ), the source IP address and MAC address are the IP address and MAC address of host.

2) When the switch receives the data frame, it finds that the data frame is a broadcast frame. Therefore, the data frame is sent from all interfaces not receiving the data frame.

3) When host B receives the data frame, it verifies whether the IP address is its own and records the ing between host A's IP address and MAC address to its ARP cache table, at the same time, an ARP response will be sent, including its own MAC address.

4) After receiving the response data frame, host A records the ing between host B's IP address and MAC address in its ARP cache table. At this time, the switch has learned the MAC addresses of host A and host B.

Iv. Summary

I have never touched on network programming before, and now I am getting started. I feel that the requirements are higher than those of the cs structure. I need to understand the LAN architecture, the forwarding principles of switches and routers, I also took this opportunity to learn about the MAC address table, ARP cache table, and route table. There is no end to learning. More and more people feel that their knowledge is too scarce and there are too many things to learn.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.