#include <stdlib.h> #include <stdio.h> #include <string.h> // strerror(errno) #include <sys/types.h> #include <sys/socket.h> // socket 函数 #include <arpa/inet.h> // 网络字节交换函数 #include <net/if.h> // struct ifreq //#include <net/if_arp.h> #include <sys/ioctl.h> // ioctl 函数 #include <errno.h> #include <unistd.h> // close 函数 int GetNetworkInfo() { int sockFd =-1; sockFd = socket( AF_INET, SOCK_DGRAM, 0 ); if (sockFd < 0 ) { printf("\n[%s]-[%d]: socket failed:%s!\n\n", __func__, __LINE__, strerror(errno)); return -1; } struct ifreq ifr; struct sockaddr_in *sin = (struct sockaddr_in *) &ifr.ifr_addr; char ip[16] = {0}; int Ret = -1; memcpy( ifr.ifr_name, "eth1", 5); //获取ip 地址 Ret = ioctl( sockFd, SIOCGIFADDR, &ifr ); if( 0 != Ret ) { printf("ioctl failed. errrno:%d, msg:%s", errno, strerror(errno)); close( sockFd ); return -1; } inet_ntop(AF_INET, &sin->sin_addr.s_addr, ip, 16); printf("\n[%s]-[%d]: SIOCGIFADDR: %s\n", __func__, __LINE__, ip); //获取广播ip 地址 memset (sin, 0, sizeof(struct sockaddr_in)); Ret = ioctl( sockFd, SIOCGIFBRDADDR, &ifr ); if( 0 != Ret ) { close( sockFd ); return -1; } inet_ntop(AF_INET, &sin->sin_addr.s_addr, ip, 16); printf("\n[%s]-[%d]: SIOCGIFBRDADDR: %s\n", __func__, __LINE__, ip); //获取mac地址 Ret = ioctl( sockFd, SIOCGIFHWADDR, &ifr ); if( 0 != Ret) { close( sockFd ); return -1; } unsigned char *HwAddr = (unsigned char *)ifr.ifr_hwaddr.sa_data; printf("\n[%s]-[%d]: SIOCGIFHWADDR: %02x:%02x:%02x:%02x:%02x:%02x\n", __func__, __LINE__, HwAddr[0], HwAddr[1], HwAddr[2], HwAddr[3], HwAddr[4], HwAddr[5]); close( sockFd ); return 0; } int main(void) { if( GetNetworkInfo() < 0 ) { printf("\n[%s]-[%d]: GetNetworkInfo failed!\n", __func__, __LINE__); } return 0; }