Skip to content

Commit 11a5720

Browse files
author
Artiom N.
committed
Chapter 10 iflist example add
1 parent 457f27b commit 11a5720

File tree

3 files changed

+75
-0
lines changed

3 files changed

+75
-0
lines changed

src/book01/ch10/cpp/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
cmake_minimum_required(VERSION 3.10)
22

33
if (UNIX)
4+
add_subdirectory("if_list")
45
add_subdirectory("if_nameindex")
56
add_subdirectory("if_rename")
67
add_subdirectory("ethtool")
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
cmake_minimum_required(VERSION 3.10)
2+
3+
project("${CHAPTER_NAME}if_list" C CXX)
4+
5+
add_executable("${PROJECT_NAME}" main.cpp)
6+
target_link_libraries("${PROJECT_NAME}" socket-wrapper)
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
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

Comments
 (0)