您的位置:首页 > 运维架构 > Linux

Linux获取本机IP、MAC示例程序

2009-09-24 16:36 295 查看
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <stdio.h>

#include <string>
#include <iostream>
#include <cstring>

using namespace std;

void peek_interfaces(int fd);
void print_hw_addr(int fd, const char* if_name);

int main() {
	int fd = socket(AF_INET, SOCK_DGRAM, 0);
	if(-1 == fd) {
		perror("Failed create socket.");
		return -1;
	}

	peek_interfaces(fd);
	close(fd);
	return 0;
}

void peek_interfaces(int fd) {
	ifreq ifs[16] = {0};
	ifconf conf = {sizeof(ifs)};
	conf.ifc_req = ifs;
	if(-1 == ioctl(fd, SIOCGIFCONF, &conf)) {
		perror("Failed IOCTL SIOCGIFCONF.");
		return;
	}
	if(conf.ifc_len >= sizeof(ifs)) {
		perror("Buffer too small for IOCTL SIOCGIFCONF.");
		return;
	}
	
	int num = conf.ifc_len / sizeof(ifreq);
	cout << num << " interface entry retrieved." << endl;
	for(int i = 0; i < num; ++i) {
		cout << "[ " << ifs[i].ifr_name << " ]" << endl;
		sockaddr_in* sai = (sockaddr_in*)&ifs[i].ifr_addr;
		cout << "Addr: " << inet_ntoa(sai->sin_addr) << endl;
		print_hw_addr(fd, ifs[i].ifr_name);
		cout << endl;
	}
}

void print_hw_addr(int fd, const char* if_name) {
	ifreq req = {0};
	strcpy(req.ifr_name, if_name);
	if(-1 == ioctl(fd, SIOCGIFFLAGS, &req)) {
		perror("Failed IOCTL SIOCGIFFLAGS.");
		return;
	}
	if(req.ifr_flags & IFF_LOOPBACK) {
		cout << "Is LOOPBACK." << endl;
		return;
	}

	if(-1 == ioctl(fd, SIOCGIFHWADDR, &req)) {
		perror("Failed IOCTL SIOCGIFHWADDR.");
		return;
	}
	unsigned char* puc = (unsigned char*)req.ifr_hwaddr.sa_data;
	printf("HW addr: %02x:%02x:%02x:%02x:%02x:%02x/n",
		puc[0], puc[1], puc[2], puc[3], puc[4], puc[5]);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: