OpenVPN 3 Core Library
Loading...
Searching...
No Matches
gwnetlink.hpp
Go to the documentation of this file.
1// OpenVPN -- An application to securely tunnel IP networks
2// over a single port, with support for SSL/TLS-based
3// session authentication and key exchange,
4// packet encryption, packet authentication, and
5// packet compression.
6//
7// Copyright (C) 2012- OpenVPN Inc.
8//
9// SPDX-License-Identifier: MPL-2.0 OR AGPL-3.0-only WITH openvpn3-openssl-exception
10//
11
12// Find default gateways on Linux using ip route command
13
14#pragma once
15
16#include <string>
17
19#include <openvpn/addr/ip.hpp>
20#include <openvpn/addr/ipv4.hpp>
21#include <openvpn/addr/ipv6.hpp>
23
24namespace openvpn {
26{
27 public:
28 OPENVPN_EXCEPTION(linux_gw_netlink_error);
29
40 LinuxGWNetlink(const std::string &addr, const std::string &iface_to_ignore, bool ipv6)
41 {
42 try
43 {
44 if (ipv6)
45 {
46 IPv6::Addr addr6;
47
49 addr6,
50 dev_,
51 iface_to_ignore)
52 < 0)
53 {
54 OPENVPN_THROW(linux_gw_netlink_error,
55 "error retrieving default IPv6 GW");
56 }
57
59 }
60 else
61 {
62 IPv4::Addr addr4;
63
65 addr4,
66 dev_,
67 iface_to_ignore)
68 < 0)
69 {
70 OPENVPN_THROW(linux_gw_netlink_error,
71 "error retrieving default IPv4 GW");
72 }
73
75 }
76 }
77 catch (...)
78 {
79 /* nothing to do. just leave default GW unassigned */
80 }
81 }
82
83 const std::string &dev() const
84 {
85 return dev_;
86 }
87
88 const IP::Addr &addr() const
89 {
90 return addr_;
91 }
92
93 bool defined() const
94 {
95 return !dev_.empty() && addr_.defined();
96 }
97
98 std::string to_string() const
99 {
100 return dev_ + '/' + addr_.to_string();
101 }
102
103 private:
105 std::string dev_;
106};
107
117{
118 LinuxGW46Netlink(const std::string &iface_to_ignore, const std::string &addr = "")
119 : v4(addr.empty() ? IPv4::Addr::from_zero().to_string() : addr, iface_to_ignore, false),
120 v6(addr.empty() ? IPv6::Addr::from_zero().to_string() : addr, iface_to_ignore, true)
121 {
122 }
123
124 std::string to_string() const
125 {
126 std::string ret = "[";
127 if (v4.defined())
128 {
129 ret += "4:";
130 ret += v4.to_string();
131 }
132 if (v6.defined())
133 {
134 if (v4.defined())
135 ret += ' ';
136 ret += "6:";
137 ret += v6.to_string();
138 }
139 ret += "]";
140 return ret;
141 }
142
143 std::string dev() const
144 {
145 if (v4.defined())
146 return v4.dev();
147 else if (v6.defined())
148 return v6.dev();
149 else
150 throw LinuxGWNetlink::linux_gw_netlink_error("cannot determine gateway interface");
151 }
152
155};
156} // namespace openvpn
std::string to_string() const
Definition ip.hpp:528
bool defined() const
Definition ip.hpp:872
static Addr from_ipv6(IPv6::Addr addr)
Definition ip.hpp:268
static Addr from_ipv4(IPv4::Addr addr)
Definition ip.hpp:260
static RouteType from_string(const std::string &rtstr, const TITLE &title)
Definition route.hpp:68
#define OPENVPN_THROW(exc, stuff)
remote_address ipv6
std::string ret