当前位置: 技术问答>linux和unix
如何获得远端机器的mac地址
来源: 互联网 发布时间:2015-04-14
本文导语: 我做一个服务器,想获得每个连接的客户端的mac地址,进行身份验证,怎么办 | 向远端机器发一个arp请求,然后接收回应包,从其中解析mac地址. | 建议你仔细看看http://www.dhcp-han...
我做一个服务器,想获得每个连接的客户端的mac地址,进行身份验证,怎么办
|
向远端机器发一个arp请求,然后接收回应包,从其中解析mac地址.
|
建议你仔细看看http://www.dhcp-handbook.com/dhcp_faq.html,这里有dhcpFAQ,介绍挺不错的。
|
struct ether_arp {
struct arphdr ea_hdr; /* fixed-size header */
u_int8_t arp_sha[ETH_ALEN]; /* sender hardware address */
u_int8_t arp_spa[4]; /* sender protocol address */
u_int8_t arp_tha[ETH_ALEN]; /* target hardware address */
u_int8_t arp_tpa[4]; /* target protocol address */
};
struct ether_arp *ap;
ap = (struct ether_arp *)bp;//bp为截获数据包的指针
然后将ap->arp_sha作为下面函数的参数,就可以打印出MAC地址了。
更详细的代码请参考tcpdump的源码
/*----------------------------------------------------------------------------
**
** etheraddr_string()
**
** Translate an ethernet address to a colon-delimited string
**
**----------------------------------------------------------------------------
*/
char *etheraddr_string(u_char *ep)
{
u_int i, j;
char *cp;
struct enamemem *tp;
char buf[sizeof("00:00:00:00:00:00")];
tp = lookup_emem(ep);//源程序中有定义
if (tp->e_name) return (tp->e_name);
cp = buf;
if ((j = *ep >> 4) != 0) *cp++ = hex[j];
*cp++ = hex[*ep++ & 0xf];//static char hex[] = "0123456789abcdef";
for (i = 5; (int)--i >= 0;)
{
*cp++ = ':';
if ((j = *ep >> 4) != 0) *cp++ = hex[j];
*cp++ = hex[*ep++ & 0xf];
}
*cp = '';
tp->e_name = strdup(buf);
return (tp->e_name);
}
struct arphdr ea_hdr; /* fixed-size header */
u_int8_t arp_sha[ETH_ALEN]; /* sender hardware address */
u_int8_t arp_spa[4]; /* sender protocol address */
u_int8_t arp_tha[ETH_ALEN]; /* target hardware address */
u_int8_t arp_tpa[4]; /* target protocol address */
};
struct ether_arp *ap;
ap = (struct ether_arp *)bp;//bp为截获数据包的指针
然后将ap->arp_sha作为下面函数的参数,就可以打印出MAC地址了。
更详细的代码请参考tcpdump的源码
/*----------------------------------------------------------------------------
**
** etheraddr_string()
**
** Translate an ethernet address to a colon-delimited string
**
**----------------------------------------------------------------------------
*/
char *etheraddr_string(u_char *ep)
{
u_int i, j;
char *cp;
struct enamemem *tp;
char buf[sizeof("00:00:00:00:00:00")];
tp = lookup_emem(ep);//源程序中有定义
if (tp->e_name) return (tp->e_name);
cp = buf;
if ((j = *ep >> 4) != 0) *cp++ = hex[j];
*cp++ = hex[*ep++ & 0xf];//static char hex[] = "0123456789abcdef";
for (i = 5; (int)--i >= 0;)
{
*cp++ = ':';
if ((j = *ep >> 4) != 0) *cp++ = hex[j];
*cp++ = hex[*ep++ & 0xf];
}
*cp = '';
tp->e_name = strdup(buf);
return (tp->e_name);
}
|
先要说明远端有多远,才能讨论这个问题。跨网段的是得不到的,只能得到路由器接口的MAC。