1 | #ifndef ADDRESSDISCOVERY_HPP_ |
---|
2 | #define ADDRESSDISCOVERY_HPP_ |
---|
3 | |
---|
4 | #include "ariba/utility/addressing/addressing.hpp" |
---|
5 | |
---|
6 | #include <sys/types.h> |
---|
7 | #include <sys/socket.h> |
---|
8 | #include <arpa/inet.h> |
---|
9 | #include <netinet/in.h> |
---|
10 | #include <net/if.h> |
---|
11 | #include <ifaddrs.h> |
---|
12 | |
---|
13 | using namespace ariba::addressing; |
---|
14 | |
---|
15 | mac_address getMacFromIF( const char* name ) { |
---|
16 | int s; |
---|
17 | struct ifreq buffer; |
---|
18 | s = socket(PF_INET, SOCK_DGRAM, 0); |
---|
19 | memset(&buffer, 0x00, sizeof(buffer)); |
---|
20 | strcpy(buffer.ifr_name, name); |
---|
21 | ioctl(s, SIOCGIFHWADDR, &buffer); |
---|
22 | close(s); |
---|
23 | mac_address addr; |
---|
24 | addr.assign( (uint8_t*)buffer.ifr_hwaddr.sa_data, 6 ); |
---|
25 | return addr; |
---|
26 | } |
---|
27 | |
---|
28 | void discoverEndpoints( endpoint_set& endpoints ) { |
---|
29 | struct ifaddrs* ifaceBuffer = NULL; |
---|
30 | struct ifaddrs* tmpAddr = NULL; |
---|
31 | void* tmpAddrPtr = NULL; |
---|
32 | char straddr [INET_ADDRSTRLEN]; |
---|
33 | |
---|
34 | int ret = getifaddrs( &ifaceBuffer ); |
---|
35 | if( ret != 0 ) return; |
---|
36 | |
---|
37 | for( struct ifaddrs* i=ifaceBuffer; i != NULL; i=i->ifa_next ) { |
---|
38 | |
---|
39 | // ignore devices that are disabled or have no ip |
---|
40 | if(i == NULL) continue; |
---|
41 | struct sockaddr* addr = i->ifa_addr; |
---|
42 | |
---|
43 | // only look at IPv4, not IPv6 addresses |
---|
44 | if (addr->sa_family == AF_INET) { |
---|
45 | if (addr==NULL) continue; |
---|
46 | tmpAddrPtr= &((struct sockaddr_in*)addr)->sin_addr; |
---|
47 | inet_ntop( i->ifa_addr->sa_family, tmpAddrPtr, straddr, sizeof(straddr) ); |
---|
48 | ip_address ip = straddr; |
---|
49 | if (ip.is_loopback()) continue; |
---|
50 | address_vf vf = ip; |
---|
51 | endpoints.add( vf ); |
---|
52 | } else |
---|
53 | if (addr->sa_family == AF_INET6) { |
---|
54 | if (addr==NULL) continue; |
---|
55 | tmpAddrPtr= &((struct sockaddr_in6*)addr)->sin6_addr; |
---|
56 | inet_ntop( i->ifa_addr->sa_family, tmpAddrPtr, straddr, sizeof(straddr) ); |
---|
57 | ip_address ip = straddr; |
---|
58 | if (ip.is_loopback()) continue; |
---|
59 | address_vf vf = ip; |
---|
60 | endpoints.add( vf ); |
---|
61 | } else |
---|
62 | if (i->ifa_name[0]=='p' && i->ifa_name[1]=='a' && i->ifa_name[2]=='n') { |
---|
63 | mac_address mac = getMacFromIF(i->ifa_name); |
---|
64 | address_vf vf = mac; |
---|
65 | endpoints.add( vf ); |
---|
66 | } |
---|
67 | } |
---|
68 | } |
---|
69 | |
---|
70 | #endif /* ADDRESSDISCOVERY_HPP_ */ |
---|