Skip to content

Instantly share code, notes, and snippets.

@danestig
Forked from johan-bjareholt/local_computers_scanner.py
Last active September 15, 2015 10:27
Show Gist options
  • Save danestig/61b18c0d2ff0cf07a5c6 to your computer and use it in GitHub Desktop.
Save danestig/61b18c0d2ff0cf07a5c6 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import socket
import subprocess
import os
connected_ips = []
def start():
# Get ip and netmask
ip = socket.gethostbyname(socket.gethostname())
netmask = get_netmask(ip)
print("Your ip: " + ip)
print("Netmask: " + get_netmask(ip))
# Define netmask depth
depth = 0
while(netmask.split('.')[depth] < '255'):
depth+=1
# Prepare basemask
basemask = netmask.split('.')[:depth]
d = depth
while(d<=3):
basemask.append('0')
d+=1
for d in range(len(basemask)):
basemask[d] = int(basemask[d])
print(basemask)
# Check all ips recursively inside the mask
test_rec(basemask, depth)
print(connected_ips)
def test_rec(mask, depth):
if depth == 3 and mask[3] < 255:
ip = arrmask_to_str(mask)
try_ip(ip)
mask[3] += 1
test_rec(mask, depth)
elif mask[depth] < 255:
test_rec(mask, depth+1)
mask[3] = 0
mask[depth] += 1
test_rec(mask, depth)
def try_ip(ip):
try:
socket.gethostbyaddr(ip)
connected_ips.append(ip)
print("Device at " + ip)
except socket.herror:
pass
#print("Unknown host: " + ip)
def get_netmask(ip):
# Call ipconfig / ifconfig
if (os.name == 'nt'): # If this is running on windows
proc = subprocess.Popen('ipconfig',stdout=subprocess.PIPE)
flag="Subnet Mask".encode()
else: # else assume UNIX
proc = subprocess.Popen('ifconfig',stdout=subprocess.PIPE)
flag=ip.encode()
while True:
line = proc.stdout.readline()
if flag in line:
break
line = line.decode("utf-8")
line = line.rstrip() # remove \n
mask = line.split(' ')[-1] # Last ip in the message is broadcast
return mask
def arrmask_to_str(mask):
return (str(mask[0]) + '.' +
str(mask[1]) + '.' +
str(mask[2]) + '.' +
str(mask[3]))
if __name__ == '__main__':
start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment