//CDN加速后取到的IP
customerIp = Request.Headers["Cdn-Src-Ip"];
if (!string.IsNullOrWhiteSpace(customerIp))
return customerIp;
customerIp = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrWhiteSpace(customerIp))
return customerIp;
if (Request.ServerVariables["HTTP_VIA"] != null)
customerIp = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (customerIp == null)
customerIp = Request.ServerVariables["REMOTE_ADDR"];
customerIp = Request.ServerVariables["REMOTE_ADDR"];
if (string.Compare(customerIp, "unknown", true) == 0)
return Request.UserHostAddress;
return string.IsNullOrWhiteSpace(customerIp) ? userIP : customerIp;
获取ip第二种方式:
public string TestGetIp2()
return ExcuteAjaxService<object>(() =>
string ipStr = string.Empty;
if (Request.ServerVariables["HTTP_VIA"] != null)
ipStr = Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
ipStr = Request.ServerVariables["REMOTE_ADDR"].ToString();
string hostName = string.Empty;
IPAddress ip = IPAddress.Parse(ipStr);
IPHostEntry host = Dns.GetHostEntry(ip);
hostName = host.HostName;
return new { Ip = ipStr, HostName = hostName };
获取mac方式:
[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);
public string GetMac(string remoteIp)
return ExcuteAjaxService<object>(() =>
var macAddress = new StringBuilder();
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));
macAddress.Append(temp.Substring(x - 2, 2) + "-");
x -= 2;
return macAddress.ToString();
catch
return macAddress.ToString();
辅助方法(与该博客无关):
private string ExcuteAjaxService<T>(Func<T> action)
var msg = action.Invoke();
return JsonConvert.SerializeObject(new { IsSuccess = true, Message = msg });
catch (Exception ex)
return JsonConvert.SerializeObject(new { IsSuccess = false, Message = ex.Message, Exception = ex });
ending
2019-10-28测试发现:第一种获取ip的方式有效,第二种异常获取ip第一种方式:public string TestGetIp() { return ExcuteAjaxService<object>(() => { string userIP = "未获取用户IP";...
if(Context.Request.ServerVariables["HTTP_VIA"]!=null)
ip=Context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
ip=Context.Request.ServerVariables["RE
本文实例讲述了C#获取本机IP地址和Mac地址的方法。分享给大家供大家参考。具体分析如下:
查找了几个方法,经过调试修改,下面这个方法能很好的获取到本地的IP和MAC地址。可以用于这方面的功能实现。主要是要添加System.Management的引用。
using System;
using System.Management;
using System.Net;
public class Program
static void Main(string[] args)
string ip = "";
string mac = "";
Managem