Created
September 22, 2020 01:22
-
-
Save awesomebytes/bdebc083ee772240766fc89f39de438b to your computer and use it in GitHub Desktop.
Find roscores running in your network
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#/usr/bin/env python | |
import socket | |
import time | |
from multiprocessing import Process, Queue | |
def check_server(address, queue, port=11311): | |
# Create a TCP socket | |
s = socket.socket() | |
try: | |
s.connect((address, port)) | |
# print("Port open at IP %s (on port %s)" % (address, port)) | |
queue.put((True, address, port)) | |
except socket.error as e: | |
# print("Connection to %s on port %s failed: %s" % (address, port, e)) | |
queue.put((False, address, port)) | |
def get_own_ip(): | |
return ((([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")] or [[(s.connect(("8.8.8.8", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) + ["no IP found"])[0]) | |
def scan_for_roscore(own_ip=None, timeout=3.0): | |
""" | |
Scan for port 11311 open on a subnet. | |
""" | |
if own_ip is None: | |
own_ip = get_own_ip() | |
if own_ip: | |
ip_split = own_ip.split('.') | |
subnet = ip_split[:-1] | |
subnetstr = '.'.join(subnet) | |
processes = [] | |
q = Queue() | |
for i in range(1, 255): | |
ip = subnetstr + '.' + str(i) | |
p = Process(target=check_server, args=[ip, q]) | |
processes.append(p) | |
p.start() | |
# give a bit of time... | |
time.sleep(timeout) | |
found_ips = [] | |
for idx, p in enumerate(processes): | |
if p.exitcode is None: | |
# print("Terminating: " + str(idx)) | |
p.terminate() | |
else: | |
open_ip, address, port = q.get() | |
if open_ip: | |
found_ips.append(address) | |
for idx, p in enumerate(processes): | |
# print("joining " + str(idx)) | |
p.join() | |
print("Found ips: " + str(found_ips)) | |
return found_ips | |
else: | |
print("Could not get our own IP, can't scan our network.") | |
return [] | |
if __name__ == '__main__': | |
print(scan_for_roscore()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment