Created
March 1, 2023 10:35
-
-
Save nidbCN/f45806f2ff0e635232931f8472e47ef3 to your computer and use it in GitHub Desktop.
C Linux get macaddress via ioctl
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdlib.h> | |
| #include <errno.h> | |
| #include <netinet/in.h> | |
| #include <net/if.h> | |
| #include <stdio.h> | |
| #include <string.h> | |
| #include <sys/ioctl.h> | |
| #include <sys/socket.h> | |
| #define MAC_ADDRESS_LENGTH (6) | |
| #define new(type) ((type*)malloc(sizeof(type))) | |
| #define new_array(type, length) ((type*)malloc(sizeof(type) * length)) | |
| const char *getMacAddress(const char *interfaceName); | |
| int main() { | |
| const char *interfaceName = "eth-bond"; | |
| const char *macAddress = getMacAddress(interfaceName); | |
| printf("MAC address of %s is %s.\n", interfaceName, macAddress); | |
| } | |
| const char *getMacAddress(const char *interfaceName) { | |
| // init socket | |
| int socketHandler = socket(AF_UNIX, SOCK_DGRAM, IPPROTO_IP); | |
| if (socketHandler == EOF) { | |
| printf("Can't init ioctl.\n"); | |
| return NULL; | |
| } | |
| // init ioctl request | |
| struct ifreq *request = new(struct ifreq); | |
| strcpy(request->ifr_name, interfaceName); | |
| // call ioctl | |
| if (ioctl(socketHandler, SIOCGIFHWADDR, request) == EOF) { | |
| printf("Can't get address of interface via ioctl.(%d: %s)\n", errno, strerror(errno)); | |
| return NULL; | |
| } | |
| // copy mac address in binary | |
| uint8_t manInBinary[6]; | |
| memcpy(manInBinary, (request->ifr_hwaddr.sa_data), sizeof(uint8_t) * MAC_ADDRESS_LENGTH); | |
| // convert binary address to string | |
| char *result = new_array(char, MAC_ADDRESS_LENGTH * 2 + MAC_ADDRESS_LENGTH - 1); | |
| sprintf(result, "%02x", manInBinary[0]); | |
| for (int i = 1; i < MAC_ADDRESS_LENGTH; ++i) { | |
| sprintf(result + (2 + (i - 1) * 3), ":%02x", manInBinary[i]); | |
| } | |
| return result; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment