본문 바로가기

C/C++

모든 네트워크 인터페이스의 MAC 주소 추출

@마크다운 


#모든 네트워크 인터페이스의 MAC 주소 추출


리눅스 커널에서 제공하는 /sys 디렉토리를 통해 값을 편하게 얻어올 수 있다.


```

DIR* nics = opendir("/sys/class/net");

struct dirent* nic = NULL;

char buf[20];

while((nic = readdir(nics))) {

    if(nic->d_name[0] == '.' || strstr(nic->d_name, "lo"))

        continue;


    char path[PATH_MAX];

    snprintf(path, sizeof(path), "/sys/class/net/%s/address", nic->d_name);

    int sysfile = open(path, 0);

    if(sysfile == -1)

        continue;


    ssize_t nread = read(sysfile, buf, sizeof(buf));

    if(nread <= 0) {

        close(sysfile);

        continue;

    }

    buf[nread - 1] = '\0'; // remove trailing newline


    printf("'%s': '%s'\n", nic->d_name, buf); // 'enp0s31f6': '1c:1b:0d:63:89:43'

}

```

'C/C++' 카테고리의 다른 글

최적화  (0) 2017.08.06
C 옵션 처리 라이브러리 - getopt  (0) 2017.06.25
flex bison 참고자료  (0) 2017.04.26
C라이브러리를 C++과 호환되도록 하는 방법  (0) 2017.04.06
Nonblocking I/O in C  (0) 2017.04.03