代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <string.h>
int main(int argc, char *argv[])
{
int inet_sock;
struct ifreq ifr;
//建立套接字
inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
//获得接口地址
bzero(&ifr, sizeof(ifr));
strcpy(ifr.ifr_name, "eth0");
if (ioctl(inet_sock, SIOCGIFADDR, &ifr) < 0)
perror("ioctl");
printf("host:%s\n", inet_ntoa(((struct sockaddr_in*)&(ifr.ifr_addr))->sin_addr));
//获得广播地址
bzero(&ifr, sizeof(ifr));
strcpy(ifr.ifr_name, "eth0");
if (ioctl(inet_sock, SIOCGIFBRDADDR, &ifr) < 0)
perror("ioctl");
printf("broadcast:%s\n", inet_ntoa(((struct sockaddr_in*)&(ifr.ifr_addr))->sin_addr));
//获取MAC地址
char mac_addr[30];
bzero(&ifr, sizeof(ifr));
strcpy(ifr.ifr_name, "eth0");
if((ioctl( inet_sock, SIOCGIFHWADDR, &ifr)) < 0)
{
printf("mac ioctl error\n");
return -1;
}
sprintf(mac_addr,"%02x:%02x:%02x:%02x:%02x:%02x",
(unsigned char)ifr.ifr_hwaddr.sa_data[0],
(unsigned char)ifr.ifr_hwaddr.sa_data[1],
(unsigned char)ifr.ifr_hwaddr.sa_data[2],
(unsigned char)ifr.ifr_hwaddr.sa_data[3],
(unsigned char)ifr.ifr_hwaddr.sa_data[4],
(unsigned char)ifr.ifr_hwaddr.sa_data[5]);
printf("local mac:%s \n",mac_addr);
return 0;
}