附一源代码:
/*用C语言得到本机的硬件地址 */
#include
#include
#include
#include
#include
#include
#include
#include
#define MAXINTERFACES 16
int main(argc, argv)
register int argc;
register char *argv[];
{
register int fd, intrface, retn = 0;
struct ifreq buf[MAXINTERFACES];
struct arpreq arp;
struct ifconf ifc;
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) >= 0) {
ifc.ifc_len = sizeof buf;
ifc.ifc_buf = (caddr_t) buf;
if (!ioctl(fd, SIOCGIFCONF, (char *) &ifc)) {
intrface = ifc.ifc_len / sizeof(struct ifreq);
printf("interface num is intrface=%d\n\n\n", intrface);
while (intrface-- > 0) {
printf("net device %s\n", buf[intrface].ifr_name);
/*Jugde whether the net card status is promisc*/
if (!(ioctl(fd, SIOCGIFFLAGS, (char *) &buf[intrface]))) {
if (buf[intrface].ifr_flags & IFF_PROMISC) {
puts("the interface is PROMISC");
retn++;
}
} else {
char str[256];
sprintf(str, "cpm: ioctl device %s",
buf[intrface].ifr_name);
perror(str);
}
/*Jugde whether the net card status is up*/
if (buf[intrface].ifr_flags & IFF_UP) {
puts("the interface status is UP");
} else {
puts("the interface status is DOWN");
}
/*Get IP of the net card */
if (!(ioctl(fd, SIOCGIFADDR, (char *) &buf[intrface]))) {
puts("IP address is:");
puts(inet_ntoa(((struct sockaddr_in *) (&buf[intrface].ifr_addr))->sin_addr));
puts("");
//puts (buf[intrface].ifr_addr.sa_data);
} else {
char str[256];
sprintf(str, "cpm: ioctl device %s",
buf[intrface].ifr_name);
perror(str);
}
/*Get HW ADDRESS of the net card */
if (!(ioctl(fd, SIOCGIFHWADDR, (char *) &buf[intrface]))) {
puts("HW address is:");
printf("%02x:%02x:%02x:%02x:%02x:%02x\n",
(unsigned char) buf[intrface].ifr_hwaddr.
sa_data[0],
(unsigned char) buf[intrface].ifr_hwaddr.
sa_data[1],
(unsigned char) buf[intrface].ifr_hwaddr.
sa_data[2],
(unsigned char) buf[intrface].ifr_hwaddr.
sa_data[3],
(unsigned char) buf[intrface].ifr_hwaddr.
sa_data[4],
(unsigned char) buf[intrface].ifr_hwaddr.
sa_data[5]);
puts("");
puts("");
}
else {
char str[256];
sprintf(str, "cpm: ioctl device %s",
buf[intrface].ifr_name);
perror(str);
}
}
} else
perror("cpm: ioctl");
} else
perror("cpm: socket");
close(fd);
return retn;
}
另外一种方式:
s = fd; /* socket to probe IP&MAC */
if(s < 0){
perror("socket screwup.");
exit(1);
}
/*
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, iface, sizeof(ifr.ifr_name));
*/
if(ioctl(s, SIOCGIFHWADDR, ifr) < 0){ /* get MAC address of ifr */
perror("hwaddr screwed up.");
exit(1);
}
/*
memcpy(mac, ifr.ifr_hwaddr.sa_data, 6);
printf("%s\n",ether_ntoa((struct ether_addr *)mac));
*/
if(ioctl(s, SIOCGIFADDR, ifr) < 0){ /* get IP address of iface */
printf("ip screwed up\n");
exit(1);
}
/*
memcpy(ip, ifr.ifr_hwaddr.sa_data+2, 4);
printf("%s\n ",inet_ntoa(*(struct in_addr *)ip));
*/
hutong236 于 2008-03-11 19:41:41发表:
你这不是从硬件那得到的,是从系统那找出来的!