根据ip地址获得Mac地址的一种方法

简介:
复制代码
ExpandedBlockStart.gif Code
public static class MacUtility
{
    [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);

    
public static string GetRemoteMac(string clientIP)
    {
        
string ip = clientIP;

        
if (ip == "127.0.0.1")

            ip 
= GetLocalIP()[0];

        var ldest 
= inet_addr(ip);

        Int64 macinfo 
= new Int64();
        Int32 len 
= 6;
        
try
        {
            SendARP(ldest, 
0ref macinfo, ref len);
        }
        
catch
        {
            
return "";

        }
        
string originalMACAddress = Convert.ToString(macinfo, 16);
        
if (originalMACAddress.Length < 12)
        {

            originalMACAddress 
= originalMACAddress.PadLeft(12'0');

        }

        
string macAddress;

        
if (originalMACAddress != "0000" && originalMACAddress.Length == 12)
        {
            
string mac1, mac2, mac3, mac4, mac5, mac6;
            mac1 
= originalMACAddress.Substring(102);
            mac2 
= originalMACAddress.Substring(82);
            mac3 
= originalMACAddress.Substring(62);
            mac4 
= originalMACAddress.Substring(42);
            mac5 
= originalMACAddress.Substring(22);
            mac6 
= originalMACAddress.Substring(02);
            macAddress 
= mac1 + "-" + mac2 + "-" + mac3 + "-" + mac4 + "-" + mac5 + "-" + mac6;
        }
        
else
        {
            macAddress 
= "";
        }
        
return macAddress.ToUpper();

    }
    
public static string[] GetLocalIP()
    {
        
string hostName = Dns.GetHostName();

        IPHostEntry ipEntry 
= Dns.GetHostByName(hostName);

        IPAddress[] arr 
= ipEntry.AddressList;

        
string[] result = new string[arr.Length];

        
for (int i = 0; i < arr.Length; i++)
        {

            result[i] 
= arr[i].ToString();
        }
        
return result;
    }


}
复制代码

相关文章
|
6月前
Mac下查看公网以及内网IP地址
Mac下查看公网以及内网IP地址
279 0
|
16天前
|
缓存 网络协议 网络架构
【计算机网络】第三章 数据链路层(MAC地址 IP地址 ARP协议)
【计算机网络】第三章 数据链路层(MAC地址 IP地址 ARP协议)
20 1
|
7月前
|
缓存 网络协议 网络架构
【计算机网络】第三章 数据链路层(MAC地址 IP地址 ARP协议)
【计算机网络】第三章 数据链路层(MAC地址 IP地址 ARP协议)
|
1天前
|
网络协议 Linux Android开发
计算机网络:MAC地址 & IP地址 & ARP协议
计算机网络:MAC地址 & IP地址 & ARP协议
26 7
|
2天前
|
Web App开发 缓存 iOS开发
强制退出Mac程序的六种方法
强制退出Mac程序的六种方法
11 2
|
11天前
Mac上IntelliJ IDEA设置类注释和方法注释带作者和日期
Mac上IntelliJ IDEA设置类注释和方法注释带作者和日期
|
17天前
|
API 开发工具
MAC 环境变量设置方法
本文介绍在MAC环境下设置环境变量的方法,以“DASHSCOPE_API_KEY”为例,图文展示设置环境变量的操作方法。
|
2月前
|
Linux
linux查看固有MAC地址的三种方法
linux查看固有MAC地址的三种方法
75 0
|
7月前
|
存储 网络协议 安全
IP地址、MAC地址、互联网、WLAN、运营商、子网掩码、网络地址、网段、网关、集线器、光纤、基站
IP地址、MAC地址、互联网、WLAN、运营商、子网掩码、网络地址、网段、网关、集线器、光纤、基站
81 0
|
4月前
Mac系统下Qt程序图标设置方法
Mac系统下Qt程序图标设置方法
31 0