2019-10-28测试发现:第一种获取ip的方式有效,第二种异常
获取ip第一种方式:
public string TestGetIp()
{
return ExcuteAjaxService<object>(() =>
{
string userIP = "未获取用户IP";
string customerIp = string.Empty;
//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"];
}
}
else
{
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();
}
else
{
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();
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();
}
});
}
辅助方法(与该博客无关):
private string ExcuteAjaxService<T>(Func<T> action)
{
try
{
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