3
我正在尝试构建网络扫描器。 我知道这个过程,所以我想ping网络中的所有可用主机,然后获取IP地址表,以便我可以映射每个IP的MAC地址。 我谷歌搜索ARP表,但我没有找到任何指导如何实现此功能。 我还发现在堆栈溢出这些类似的问题:iOS - 获取ARP表
答案是关于如何实现ARP功能尚不清楚。 有没有这方面的官方指南?苹果是否批准ARP表功能?
我正在尝试构建网络扫描器。 我知道这个过程,所以我想ping网络中的所有可用主机,然后获取IP地址表,以便我可以映射每个IP的MAC地址。 我谷歌搜索ARP表,但我没有找到任何指导如何实现此功能。 我还发现在堆栈溢出这些类似的问题:iOS - 获取ARP表
答案是关于如何实现ARP功能尚不清楚。 有没有这方面的官方指南?苹果是否批准ARP表功能?
更新后10.2
检查here
我终于有工作,所以我将发布详细的程序,以节省一些时间,其他人库:
route.h
和if_types.h
,然后从“netinet”文件夹复制if_ether.h
到您的Xcode项目中。.m
.h
和文件:MacFinder.h
#import <Foundation/Foundation.h>
#include <sys/param.h>
#include <sys/file.h>
#include <sys/socket.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
#include "if_types.h"
#if TARGET_IPHONE_SIMULATOR
#include <net/route.h>
#else
#include "route.h"
#endif
#include "if_ether.h"
#include <netinet/in.h>
#include <arpa/inet.h>
#include <err.h>
#include <errno.h>
#include <netdb.h>
#include <paths.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
@interface MacFinder : NSObject{
int nflag;
}
-(NSString*) ip2mac: (char*)ip;
@end
MacFinder.m
#import "MacFinder.h"
@implementation MacFinder
-(NSString*) ip2mac: (char*)ip
{
int found_entry = 0;
NSString *mAddr = nil;
u_long addr = inet_addr(ip);
int mib[6];
size_t needed;
char *host, *lim, *buf, *next;
struct rt_msghdr *rtm;
struct sockaddr_inarp *sin;
struct sockaddr_dl *sdl;
extern int h_errno;
struct hostent *hp;
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");
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 (addr) {
if (addr != sin->sin_addr.s_addr)
continue;
found_entry = 1;
}
if (nflag == 0)
hp = gethostbyaddr((caddr_t)&(sin->sin_addr),
sizeof sin->sin_addr, AF_INET);
else
hp = 0;
if (hp)
host = hp->h_name;
else {
host = "?";
if (h_errno == TRY_AGAIN)
nflag = 1;
}
if (sdl->sdl_alen) {
u_char *cp = LLADDR(sdl);
mAddr = [NSString stringWithFormat:@"%x:%x:%x:%x:%x:%x", cp[0], cp[1], cp[2], cp[3], cp[4], cp[5]];
// ether_print((u_char *)LLADDR(sdl));
}
else
mAddr = nil;
}
if (found_entry == 0) {
return nil;
} else {
return mAddr;
}
}
@end
对'malloc'的调用是泄漏。对'gethostbyaddr'的调用看起来多余。否则,这就像一个魅力。谢谢! –
请随时更新答案并修复泄漏! – BlackM
我按照这些指示一步一步,但MAC地址始终为零,因为found_entry int始终是0.有没有人有想法? (IP是100%有效) – user3191334