#include <sys/ioctl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[])
{
if(argc < 2)
printf("usage getmac <interface> interface为网络设备,如eth0, 可以通过/sbin/ifconfig查看\n"),exit(-1);
/*
struct ifreq {
union {
char ifrn_name[IFNAMSIZ]; Unique Windows Adapter name (A GUID)
} ifr_ifrn;
*/
struct ifreq req;
int sock;
char mac[32];
if((sock=socket(AF_INET,SOCK_STREAM,0))< 0)
{
printf("error socket\n");
return 2;
}
//#define SIOCGIFHWADDR 0x8927 /* Get hardware address */
strcpy(req.ifr_name,argv[1]);
if(ioctl(sock,SIOCGIFHWADDR,&req) < 0)
{
printf("error ioctl SIOCGIFHWADDR\n");
return 3;
}
unsigned char* macArr= (unsigned char*)req.ifr_hwaddr.sa_data;
sprintf(mac, "%02x-%02x-%02x-%02x-%02x-%02x", macArr[0],macArr[1],macArr[2],macArr[3],macArr[4],macArr[5]);
printf("MAC:%s\n",mac);
struct ifreq req2;
strcpy(req2.ifr_name,argv[1]);
//#define SIOCGIFADDR 0x8915 /* get PA address */
//获取IO设备的更多信息见/usr/include/bits/ioctls.h
if(ioctl(sock, SIOCGIFADDR,&req2) < 0)
{
printf("error ioctl SIGCGIFADDR\n");
return 4;
}
char ipAddr[64] = {0};
inet_ntop(AF_INET,&((struct sockaddr_in*)&(req2.ifr_addr))->sin_addr, ipAddr,sizeof(ipAddr));
printf("IPADDR %s\n", ipAddr);
return 0;
}
获取本机mac地址和Ip地址
最新推荐文章于 2023-12-17 15:03:55 发布