Skip to content

Commit ccb5c92

Browse files
committed
New way to find gateway
1 parent 5036b8b commit ccb5c92

File tree

2 files changed

+57
-3
lines changed

2 files changed

+57
-3
lines changed

DynamicRoutingUpdater/NetworkAdapter.py

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import logging
2+
import re
23
import netifaces
34
from netaddr import IPAddress
45
from typing import Optional
5-
from .objects import IpData
6+
from .objects import IpData, Netstated
7+
import subprocess
68

79
logging.basicConfig(level=logging.INFO)
810

@@ -42,6 +44,12 @@ def getGateway(self) -> Optional[str]:
4244
except:
4345
logging.error(f"getGateway => {gw}")
4446
pass
47+
# If this is hit, then it could not find the gateway using traditional means
48+
netst = self.parseNetstat(nic_name=self.name)
49+
routable = [line for line in netst if line.flags.lower() == "G".lower()]
50+
use_route: Netstated = next(routable, None)
51+
if (use_route is not None):
52+
return use_route.gateway
4553
return None
4654

4755
def getNetmask(self) -> Optional[str]:
@@ -79,4 +87,31 @@ def getCidr(self, subnet: str) -> Optional[str]:
7987
pass
8088
return None
8189

82-
90+
91+
92+
def parseNetstat(self, nic_name: str) -> list[Netstated]:
93+
result = subprocess.getoutput(f"netstat -r -n -e -4 | grep {nic_name}").split("\n")
94+
if (len(result) == 0):
95+
return []
96+
else:
97+
entries: list[Netstated] = []
98+
for line in result:
99+
try:
100+
columns = re.split(r'\s+', line)
101+
entries.append(
102+
Netstated(
103+
destination=columns[0],
104+
gateway=columns[1],
105+
genmask=columns[2],
106+
flags=columns[3],
107+
metric=columns[4],
108+
ref=columns[5],
109+
use=columns[6],
110+
iface=columns[7]
111+
)
112+
)
113+
except:
114+
logging.exception("Failed to parse netstat")
115+
return entries
116+
117+

DynamicRoutingUpdater/objects.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,4 +85,23 @@ def __init__(self, interface: str, dynamic: bool, ttl: int, ip: str, prefix: str
8585
def __str__(self):
8686
return "\tIPv4 => {},\n\t Prefix => {},\n\t isDHCP => {},\n\t TTL => {}\n".format(self.ip_address, self.ip_address_prefix, self.is_dynamic, self.valid_life_time_in_sec())
8787

88-
88+
89+
class Netstated:
90+
destination: str = None
91+
gateway: str = None
92+
genmask: str = None
93+
flags: str = None
94+
metric: str = None
95+
ref: str = None
96+
use: str = None
97+
iface: str = None
98+
99+
def __init__(self, destination, gateway, genmask, flags, metric, ref, use, iface) -> None:
100+
self.destination = destination
101+
self.gateway = gateway
102+
self.genmask = genmask
103+
self.flags = flags
104+
self.metric = metric
105+
self.ref = ref
106+
self.use = use
107+
self.iface = iface

0 commit comments

Comments
 (0)