Linux下获取ip地址 广播地址和mac地址

2021年6月30日 1点热度 0条评论 来源: 一路阳光随行

代码如下:

#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;
}

 

    原文作者:一路阳光随行
    原文地址: https://blog.csdn.net/wuchuanpingstone/article/details/84615888
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。