获取客户机MAC地址 根据IP地址 获取机器的MAC地址 / 获取真实Ip地址

时间:2023-03-08 16:36:02
        [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);
/// <summary>
/// 获取客户机MAC地址 根据IP地址 获取机器的MAC地址
/// </summary>
/// <returns></returns>
public static string GetBarMACIP(string strIP)
{
//MAC信息
string mac_dest = "";
try
{
int ldest = inet_addr(strIP); //目的地的ip
int lhost = inet_addr(""); //本地服务器的ip
Int64 macinfo = new Int64();
int len = ;
int res = SendARP(ldest, , ref macinfo, ref len);
string mac_src = macinfo.ToString("X");
if (mac_src == "")
{
return "";
}
while (mac_src.Length < )
{
mac_src = mac_src.Insert(, "");
} for (int i = ; i < ; i++)
{
if ( == (i % ))
{
if (i == )
{
mac_dest = mac_dest.Insert(, mac_src.Substring(i, ));
}
else
{
mac_dest = "-" + mac_dest.Insert(, mac_src.Substring(i, ));
}
}
}
return mac_dest;
}
catch
{
return "";
}
} /// <summary>
/// 取得IP地址
/// </summary>
/// <returns></returns>
public static string GetIp()
{
string str = "";
//穿过代理服务器取远程用户真实IP地址:
if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
str = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
else
str = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
return str;
}