Linux下获取CPUID、硬盘序列号与MAC地址(1)(3)
其中,ifrn_name为网络接口的名称,ifr_ifru.ifru_hwaddr为网络接口的MAC地址。
#ifndef MAX_IFINDEX
# define MAX_IFINDEX 8
#endif
static int
getmacaddr (const char *ip, char *id, size_t max)
{
int i, sockfd;
struct sockaddr_in *loc;
struct ifreq req[1];
sockfd = socket (AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0)
{
fprintf (stderr, "Unable to create socket.\n");
return -1;
}
for (i = 0; i <= MAX_IFINDEX; ++ i)
{
req->ifr_ifindex = i;
if (ioctl (sockfd, SIOCGIFNAME, req) < 0)
{
fprintf (stderr, "ioctl error: %s\n", strerror (errno));
continue;
}
if (ioctl (sockfd, SIOCGIFADDR, req) < 0)
{
fprintf (stderr, "ioctl interface index [%d] error: %s\n", i, strerror (errno));
continue;
}
loc = (struct sockaddr_in *) (&(req->ifr_ifru.ifru_addr));
if (loc->sin_addr.s_addr == inet_addr (ip))
{
fprintf (stderr, "%s bind at %s.\n", ip, req->ifr_name);
break;
}
}
if (i > MAX_IFINDEX)
{
fprintf (stderr, "input IP error.\n");
close (sockfd);
return -1;
}
if (ioctl (sockfd, SIOCGIFHWADDR, req) < 0)
{
fprintf (stderr, "ioctl error: %s\n", strerror (errno));
close (sockfd);
return -1;
}
close (sockfd);
snprintf (id, max, "%02X%02X%02X%02X%02X%02X",
req->ifr_hwaddr.sa_data[0] & 0xff,
req->ifr_hwaddr.sa_data[1] & 0xff,
req->ifr_hwaddr.sa_data[2] & 0xff,
req->ifr_hwaddr.sa_data[3] & 0xff,
req->ifr_hwaddr.sa_data[4] & 0xff,
req->ifr_hwaddr.sa_data[5] & 0xff);
fprintf (stdout, "MAC address of %s: [%s].\n", req->ifr_name, id);
return 0;
}
评论暂时关闭