2 * Copyright 2006-2010, Haiku, Inc. All Rights Reserved.
3 * Distributed under the terms of the MIT License.
6 * Axel Dörfler, axeld@pinc-software.de
12 #include <sys/socket.h>
13 #include <sys/sockio.h>
18 #include <AutoDeleter.h>
20 #include "compatibility/bsd/ifaddrs.h"
28 fFD
= socket(AF_INET
, SOCK_DGRAM
, 0);
37 int FD() const { return fFD
; }
42 } // namespace BPrivate
49 if_nametoindex(const char* name
)
51 BPrivate::Socket socket
;
56 strlcpy(request
.ifr_name
, name
, IF_NAMESIZE
);
57 if (ioctl(socket
.FD(), SIOCGIFINDEX
, &request
, sizeof(struct ifreq
)) < 0)
60 return request
.ifr_index
;
65 if_indextoname(unsigned index
, char* nameBuffer
)
67 BPrivate::Socket socket
;
72 request
.ifr_index
= index
;
73 if (ioctl(socket
.FD(), SIOCGIFNAME
, &request
, sizeof(struct ifreq
)) < 0)
76 strlcpy(nameBuffer
, request
.ifr_name
, IF_NAMESIZE
);
84 BPrivate::Socket socket
;
88 // get a list of all interfaces
91 config
.ifc_len
= sizeof(config
.ifc_value
);
92 if (ioctl(socket
.FD(), SIOCGIFCOUNT
, &config
, sizeof(struct ifconf
)) < 0)
95 int count
= (int)config
.ifc_value
;
96 ifreq
* interfaces
= (ifreq
*)malloc(count
* sizeof(struct ifreq
));
97 if (interfaces
== NULL
)
100 MemoryDeleter
deleter(interfaces
);
102 config
.ifc_len
= count
* sizeof(struct ifreq
);
103 config
.ifc_req
= interfaces
;
104 if (ioctl(socket
.FD(), SIOCGIFCONF
, &config
, sizeof(struct ifconf
)) < 0)
107 struct if_nameindex
* interfaceArray
= (struct if_nameindex
*)malloc(
108 sizeof(struct if_nameindex
) * (count
+ 1));
109 if (interfaceArray
== NULL
)
114 // retrieve interface index
116 strlcpy(((struct ifreq
&)request
).ifr_name
, interfaces
->ifr_name
,
119 if (ioctl(socket
.FD(), SIOCGIFINDEX
, &request
,
120 sizeof(struct ifreq
)) >= 0) {
121 interfaceArray
[i
].if_index
= request
.ifr_index
;
122 interfaceArray
[i
].if_name
= strdup(interfaces
->ifr_name
);
126 interfaces
= (ifreq
*)((char*)interfaces
127 + _SIZEOF_ADDR_IFREQ(interfaces
[0]));
131 interfaceArray
[i
].if_index
= 0;
132 interfaceArray
[i
].if_name
= NULL
;
134 return interfaceArray
;
139 if_freenameindex(struct if_nameindex
*interfaceArray
)
141 for (int i
= 0; interfaceArray
[i
].if_name
; i
++)
142 free(interfaceArray
[i
].if_name
);
144 free(interfaceArray
);