lang/python/ PingExample1
This pings every 192.168.1.x
address, compiles a list of those who replied (within 1 second which is fine for a LAN). It then looks in /etc/hosts
to see which are recognised and lists out which ip addresses (actually just the x
) have known names and which do not. I wrote this because the expensive Netgear Orbi doesn't allow you to call a local machine by an unqualified name (e.g. ping pi3
doesn't work unless pi3 is in the /etc/hosts
file).
The code:
#!/usr/bin/env python3
from threading import Thread
from subprocess import run, PIPE, DEVNULL
def ping(host):
m = run(["ping","-c1","-W1",host],stdout=DEVNULL,stderr=DEVNULL)
return m.returncode
def p(n):
host = f"192.168.1.{n}"
return ping(host) == 0
s = set()
def task(n):
if p(n):
s.add(n)
ts = []
def main():
for i in range(2,255):
t = Thread(target=task,args=(i,))
ts.append(t)
t.start()
for t in ts:
t.join()
print(" ".join(map(str,sorted(s))))
hosts = open("/etc/hosts").read().rstrip().splitlines()
hosts = list(filter(lambda t: t.startswith("192"),hosts))
hs = list(map(lambda t: int(t.split(" ")[0].split(".")[3]),hosts))
hm = { hs[i]:hosts[i] for i in range(len(hs)) }
for n in sorted(s):
if n in hm:
print(f"{n} : {hm[n]}")
else:
print(f"{n} unknown")
if __name__ == "__main__":
main()