获取本地IP地址、MAC地址写法
一、获取IP地址
string strIP = "";IPHostEntry ipEntry = Dns.GetHostEntry(Dns.GetHostName());foreach (System.Net.IPAddress ip in ipEntry.AddressList){if (ip.AddressFamily == AddressFamily.InterNetwork){strIP = ip.ToString();}}
二、获取MAC地址
NetworkInterface nic = NetworkInterface.GetAllNetworkInterfaces()[0];strMAC = BitConverter.ToString(nic.GetPhysicalAddress().GetAddressBytes());***需要添加命名空间:
using System.Net.NetworkInformation;
using System.Net;
using System.Net.Sockets;
三、获取访问用户的IP地址
string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];if (string.IsNullOrEmpty(ip)){ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];}else{// 如果有多个 IP(如经过多层代理),取第一个ip = ip.Split(',')[0].Trim();}// 处理 IPv6 本地回环if (ip == "::1"){ip = "127.0.0.1";}