5
5
import platform
6
6
import logging
7
7
import asyncio
8
+ import shutil
8
9
from scapy .all import ARP , Ether , conf , AsyncSniffer , sendp
9
10
from .utils .path_utils import resource_path
10
11
from .utils .logger import CommonLogger
@@ -93,12 +94,11 @@ def get_device_name(ip, timeout=1):
93
94
return "Unknown"
94
95
95
96
def get_subnet_mask (ip ):
96
- if platform .system ().lower () == "windows" :
97
+ system = platform .system ().lower ()
98
+
99
+ if system == "windows" :
97
100
try :
98
101
output = subprocess .check_output ("ipconfig" , shell = True , text = True )
99
- os .makedirs ("output" , exist_ok = True )
100
- with open (os .path .join ("output" , "ipconfig_output.txt" ), "w" ) as f :
101
- f .write (output )
102
102
lines = output .splitlines ()
103
103
for i , line in enumerate (lines ):
104
104
if ip in line :
@@ -107,6 +107,48 @@ def get_subnet_mask(ip):
107
107
return lines [j ].split (":" )[- 1 ].strip ()
108
108
except Exception as e :
109
109
logger .error (f"Error retrieving subnet mask: { e } " )
110
+ else :
111
+ try :
112
+ try :
113
+ import netifaces # type: ignore
114
+
115
+ for iface in netifaces .interfaces ():
116
+ addrs = netifaces .ifaddresses (iface ).get (netifaces .AF_INET , [])
117
+ for addr in addrs :
118
+ if addr .get ("addr" ) == ip and addr .get ("netmask" ):
119
+ return addr .get ("netmask" )
120
+ except Exception as e :
121
+ logger .debug (f"netifaces unavailable or failed: { e } " )
122
+
123
+ if shutil .which ("ip" ):
124
+ output = subprocess .check_output (
125
+ ["ip" , "-o" , "-f" , "inet" , "addr" , "show" ], text = True
126
+ )
127
+ for line in output .splitlines ():
128
+ parts = line .split ()
129
+ if len (parts ) >= 4 and "/" in parts [3 ]:
130
+ addr , prefix = parts [3 ].split ("/" )
131
+ if addr == ip :
132
+ return str (ipaddress .IPv4Network (f"0.0.0.0/{ prefix } " ).netmask )
133
+
134
+ if shutil .which ("ifconfig" ):
135
+ output = subprocess .check_output ("ifconfig" , shell = True , text = True )
136
+ lines = output .splitlines ()
137
+ for i , line in enumerate (lines ):
138
+ if ip in line :
139
+ for j in range (i , min (i + 5 , len (lines ))):
140
+ if "netmask" in lines [j ].lower ():
141
+ tokens = lines [j ].split ()
142
+ if "netmask" in tokens :
143
+ idx = tokens .index ("netmask" ) + 1
144
+ if idx < len (tokens ):
145
+ mask = tokens [idx ]
146
+ if mask .startswith ("0x" ):
147
+ mask = str (ipaddress .IPv4Address (int (mask , 16 )))
148
+ return mask
149
+ except Exception as e :
150
+ logger .error (f"Error retrieving subnet mask: { e } " )
151
+
110
152
return "255.255.255.0"
111
153
112
154
def get_ip_range ():
0 commit comments