Skip to content

Commit

Permalink
Switched to netifaces to find netmask. It simplify the code and will …
Browse files Browse the repository at this point in the history
…cover cases where ifconfig is not available
  • Loading branch information
ChristianTremblay committed Aug 21, 2020
1 parent 7bf7fd1 commit 7aeddc4
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 40 deletions.
51 changes: 11 additions & 40 deletions BAC0/core/functions/GetIPAddr.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import ipaddress
import sys
import re
import netifaces


class HostIP:
Expand Down Expand Up @@ -103,49 +104,19 @@ def _findSubnetMask(self, ip):
a default IP address when defining Script
:param ip: (str) optionnal IP address. If not provided, default to getIPAddr()
:param mask: (str) optionnal subnet mask. If not provided, will try to find one using ipconfig (Windows) or ifconfig (Linux or MAC)
:returns: broadcast IP Adress as String
"""
ip = ip

if "win32" in sys.platform:
try:
proc = subprocess.Popen("ipconfig", stdout=subprocess.PIPE)
while True:
line = proc.stdout.readline()
if ip.encode() in line:
break
mask = (
proc.stdout.readline()
.rstrip()
.split(b":")[-1]
.replace(b" ", b"")
.decode()
)
except:
raise NetworkInterfaceException("Cannot read IP parameters from OS")
else:
"""
This procedure could use more direct way of obtaining the broadcast IP
as it is really simple in Unix
ifconfig gives Bcast directly for example
or use something like :
iface = "eth0"
socket.inet_ntoa(fcntl.ioctl(socket.socket(socket.AF_INET, socket.SOCK_DGRAM), 35099, struct.pack('256s', iface))[20:24])
"""
pattern = re.compile(r"(255.\d{1,3}.\d{1,3}.\d{1,3})")

interfaces = netifaces.interfaces()
for nic in interfaces:
addresses = netifaces.ifaddresses(nic)
try:
proc = subprocess.Popen("ifconfig", stdout=subprocess.PIPE)
while True:
line = proc.stdout.readline()
if ip.encode() in line:
break
mask = re.findall(pattern, line.decode())[0]
except:
mask = "255.255.255.255"
return mask
for address in addresses[netifaces.AF_INET]:
if address["addr"] == ip:
return address["netmask"]
except KeyError:
pass
return "255.255.255.255"


def validate_ip_address(ip):
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
bacpypes>=0.18
netifaces

0 comments on commit 7aeddc4

Please sign in to comment.