ios根据ARP表获取mac地址

ios根据ARP表获取mac地址

#ios

-(NSString*) getMacAddress:(NSString *)strIP {
     
    NSString *macAddr = nil;
    const char *ip = [strIP UTF8String];
    
    if (ip == nil) {
     
        
        return nil;
    }
    if (strcmp(ip,"") == 0) {
     
        
        return nil;
    }
    
    in_addr_t addr = inet_addr(ip);
    
    int client = socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);
    
    struct sockaddr_in remote_addr;
    memset(&remote_addr,0,sizeof(remote_addr));
    remote_addr.sin_port = htons(8000);
    remote_addr.sin_addr.s_addr= addr;
    
    sendto(client, "", sizeof("") , 0 , (struct sockaddr*)&remote_addr, sizeof(struct sockaddr_in));
    
    
    int mib[6];
    size_t needed;  // 需要分区的缓冲区大小
    char *lim, *buf, *next;
    struct rt_msghdr *rtm;  //msghdr 消息头
    struct sockaddr_inarp *sin;  // arp socketaddr
    struct sockaddr_dl *sdl;  //Link-Level Sockaddr
    extern int h_errno;
    
    mib[0] = CTL_NET;
    mib[1] = PF_ROUTE;
    mib[2] = 0;
    mib[3] = AF_INET;
    mib[4] = NET_RT_FLAGS;
    mib[5] = RTF_LLINFO;
    
    // 获取缓冲区的大小
    if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
        err(1, "route-sysctl-estimate");
    
    //分析内存
    if ((buf = malloc(needed)) == NULL)
        err(1, "malloc");
    
    // 查询 ARP 表
    if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0)
        err(1, "actual retrieval of routing table");
    
    lim = buf + needed;
    
    for (next = buf; next < lim; next += rtm->rtm_msglen) {
     
        
        rtm = (struct rt_msghdr *)next;
        sin = (struct sockaddr_inarp *)(rtm + 1);
        sdl = (struct sockaddr_dl *)(sin + 1);
        
        if (sdl->sdl_alen) {
     
            
            if (addr == sin->sin_addr.s_addr) {
     
                
                u_char  *cp = (u_char*)LLADDR(sdl);
                macAddr = [NSString stringWithFormat:@"%02x:%02x:%02x:%02x:%02x:%02x", cp[0], cp[1], cp[2], cp[3], cp[4], cp[5]];
                
            }
            
        }
    }
    
    free(buf);
    return macAddr;
}

你可能感兴趣的:(ios)