获取指定名字的网卡的Mac地址和IP地址
文件名:get_mac_ip.c 运行环境:Linux、Arm 编译指令:gcc -o get_mac_ip get_mac_ip.c 运行程序:./get_mac_ip eth0 其中eth0 是网卡的名字,不同网卡名字一般是不一样的。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int get_mac_addr(char* mac, char* ip, char *_net_card)
{
struct ifreq tmp;
int sock_mac;
char mac_addr[30];
struct sockaddr_in *sin;
sock_mac = socket(AF_INET, SOCK_STREAM, 0);
if(sock_mac == -1)
{
perror("create socket fail\n");
return -1;
}
memset(&tmp,0,sizeof(tmp));
strncpy(tmp.ifr_name, _net_card, sizeof(tmp.ifr_name)-1 );
if(ioctl(sock_mac, SIOCGIFHWADDR, &tmp)<0)
{
printf("mac ioctl error\n");
close(sock_mac);
return -1;
}
sprintf(mac_addr, "%02x:%02x:%02x:%02x:%02x:%02x",
(unsigned char)tmp.ifr_hwaddr.sa_data[0],
(unsigned char)tmp.ifr_hwaddr.sa_data[1],
(unsigned char)tmp.ifr_hwaddr.sa_data[2],
(unsigned char)tmp.ifr_hwaddr.sa_data[3],
(unsigned char)tmp.ifr_hwaddr.sa_data[4],
(unsigned char)tmp.ifr_hwaddr.sa_data[5]);
memcpy(mac, mac_addr, strlen(mac_addr));
if(ioctl(sock_mac, SIOCGIFADDR, &tmp) < 0)
{
close(sock_mac);
return -1;
}
sin = (struct sockaddr_in *)&(tmp.ifr_addr);
strcpy(ip, inet_ntoa(sin->sin_addr));
close(sock_mac);
return 0;
}
int main(int argc, char** argv)
{
char mac[32] = "\0";
char ip[32]="\0";
if(argc < 2)
{
printf("Sorry. Please input net card name.\n");
printf("Such as: ./get_ip_mac eth0\n");
return 0;
}
get_mac_addr(mac, ip, argv[1]);
printf("mac=%s\nip=%s\n", mac, ip);
return 0;
}
程序运行截图:
|