|
发表于 2020-7-17 20:26:44
|
显示全部楼层
- #include <sys/ioctl.h>
- #include <net/if.h>
- #include <netinet/in.h>
- #include <string.h>
- #include <stdio.h>
- void dump_macaddress(char* address) {
- printf("%02x", address[0]);
- for (int i = 1; i < 6; i++) {
- printf(":%2x", address[i] & 0xff);
- }
- printf("\n");
- }
- int main() {
- struct ifreq ifr;
- struct ifconf ifc;
- char buf[1024];
- int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
- if (sock == -1) { /* handle error*/ };
- ifc.ifc_len = sizeof(buf);
- ifc.ifc_buf = buf;
- if (ioctl(sock, SIOCGIFCONF, &ifc) == -1) { /* handle error */ }
- struct ifreq *it = ifc.ifc_req;
- const struct ifreq *const end = it + (ifc.ifc_len / sizeof(struct ifreq));
- for (; it != end; ++it) {
- strcpy(ifr.ifr_name, it->ifr_name);
- if (ioctl(sock, SIOCGIFFLAGS, &ifr) == 0) {
- if (!(ifr.ifr_flags & IFF_LOOPBACK)) { // don't count loopback
- if (ioctl(sock, SIOCGIFHWADDR, &ifr) == 0) {
- dump_macaddress(ifr.ifr_hwaddr.sa_data);
- }
- }
- } else { /* handle error */ }
- }
- }
复制代码 |
|