File Coverage

get_mac_linux.c
Criterion Covered Total %
statement 12 23 52.1
branch 4 8 50.0
condition n/a
subroutine n/a
pod n/a
total 16 31 51.6


line stmt bran cond sub pod time code
1             /*
2             Perl ARP Extension
3             Get the MAC address of an interface
4             Linux code
5              
6             Programmed by Bastian Ballmann
7             Last update: 11.05.2022
8              
9             This program is free software; you can redistribute
10             it and/or modify it under the terms of the
11             GNU General Public License version 2 as published
12             by the Free Software Foundation.
13              
14             This program is distributed in the hope that it will
15             be useful, but WITHOUT ANY WARRANTY; without even
16             the implied warranty of MERCHANTABILITY or FITNESS
17             FOR A PARTICULAR PURPOSE.
18             See the GNU General Public License for more details.
19             */
20              
21             #include
22             #include
23             #include
24             #include
25             #include
26             #include
27             #include
28             #include
29             #include "arp.h"
30              
31 1           int get_mac_linux(const char *dev, char *mac)
32             {
33             int sock;
34             struct ifreq iface;
35              
36 1 50         if ( !strlen(mac) || !strlen(dev) )
    50          
37 0           return -1;
38              
39             /* Set hardware address as unknown */
40 1           strncpy(mac,"unknown", HEX_HW_ADDR_LEN);
41 1           mac[HEX_HW_ADDR_LEN - 1] = '\0';
42              
43             /* Copy device name into the ifreq strcture so that we can look for its
44             * hardware address through an ioctl request */
45 1           strncpy(iface.ifr_name, dev, IFNAMSIZ);
46 1           iface.ifr_name[IFNAMSIZ - 1] = '\0';
47              
48             // Open a socket
49 1 50         if((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
50             {
51 0           perror("socket");
52 0           return -1;
53             }
54             else
55             {
56             // Get the interface hardware address
57 1 50         if((ioctl(sock, SIOCGIFHWADDR, &iface)) < 0)
58             {
59 1           perror("ioctl SIOCGIFHWADDR");
60 1           close(sock);
61 1           return -1;
62             }
63             else
64             {
65 0           sprintf(mac,"%02x:%02x:%02x:%02x:%02x:%02x",
66 0           iface.ifr_hwaddr.sa_data[0] & 0xff,
67 0           iface.ifr_hwaddr.sa_data[1] & 0xff,
68 0           iface.ifr_hwaddr.sa_data[2] & 0xff,
69 0           iface.ifr_hwaddr.sa_data[3] & 0xff,
70 0           iface.ifr_hwaddr.sa_data[4] & 0xff,
71 0           iface.ifr_hwaddr.sa_data[5] & 0xff);
72             }
73             }
74              
75 0           close(sock);
76 1           return 0;
77             }