|
| 1 | +extern "C" |
| 2 | +{ |
| 3 | +#include <net/if.h> |
| 4 | +#include <sys/ioctl.h> |
| 5 | +} |
| 6 | + |
| 7 | +#include <socket_wrapper/socket_class.h> |
| 8 | +#include <socket_wrapper/socket_headers.h> |
| 9 | +#include <socket_wrapper/socket_wrapper.h> |
| 10 | + |
| 11 | +#include <array> |
| 12 | +#include <cassert> |
| 13 | +#include <iostream> |
| 14 | +#include <stdexcept> |
| 15 | +#include <vector> |
| 16 | + |
| 17 | + |
| 18 | +int main() |
| 19 | +{ |
| 20 | + ifconf ifc = {0}; |
| 21 | + |
| 22 | + const socket_wrapper::SocketWrapper sock_wrap; |
| 23 | + |
| 24 | + const auto sock = socket_wrapper::Socket(AF_INET, SOCK_DGRAM, 0); |
| 25 | + |
| 26 | + if (sock < 0) |
| 27 | + { |
| 28 | + throw std::system_error(errno, std::system_category(), "socket"); |
| 29 | + } |
| 30 | + |
| 31 | + if (ioctl(sock, SIOCGIFCONF, &ifc) < 0) |
| 32 | + { |
| 33 | + throw std::system_error(errno, std::system_category(), "SIOCGIFCONF with 0 buffer"); |
| 34 | + } |
| 35 | + |
| 36 | + std::cout << "Buffer size = " << ifc.ifc_len << std::endl; |
| 37 | + assert(ifc.ifc_len); |
| 38 | + |
| 39 | + std::vector<char> buffer(ifc.ifc_len); |
| 40 | + |
| 41 | + ifc.ifc_buf = buffer.data(); |
| 42 | + |
| 43 | + if (ioctl(sock, SIOCGIFCONF, &ifc) < 0) |
| 44 | + { |
| 45 | + throw std::system_error(errno, std::system_category(), "SIOCGIFCONF"); |
| 46 | + } |
| 47 | + |
| 48 | + for (auto i = ifc.ifc_req; i != ifc.ifc_req + ifc.ifc_len / sizeof(ifreq); ++i) |
| 49 | + { |
| 50 | + std::cout << i->ifr_name << ": "; |
| 51 | + if (AF_INET == i->ifr_addr.sa_family) |
| 52 | + { |
| 53 | + std::array<char, INET_ADDRSTRLEN> buf; |
| 54 | + std::cout << inet_ntop( |
| 55 | + AF_INET, &(reinterpret_cast<sockaddr_in*>(&i->ifr_addr)->sin_addr), buf.data(), buf.size()); |
| 56 | + } |
| 57 | + else if (AF_INET6 == i->ifr_addr.sa_family) |
| 58 | + { |
| 59 | + std::array<char, INET6_ADDRSTRLEN> buf; |
| 60 | + std::cout << inet_ntop( |
| 61 | + AF_INET6, &(reinterpret_cast<sockaddr_in6*>(&i->ifr_addr)->sin6_addr), buf.data(), buf.size()); |
| 62 | + } |
| 63 | + |
| 64 | + std::cout << std::endl; |
| 65 | + } |
| 66 | + |
| 67 | + return EXIT_SUCCESS; |
| 68 | +} |
0 commit comments