Python unknown remote IP using Broadcast
Sometimes you want your beaglebone be installed using dhcp, but without a screen, we wouldn't know the IP address. These scripts will do the magic, as you can see, they need improvement, but it will be a start point.
Server script:
import netifaces as ni import netaddr import json from socket import * def get_address_info(): for _nic in ('eth0', 'eth1', 'en0', 'en1'): try: net_info = ni.ifaddresses(_nic)[2][0] except: continue else: print('Informacion para la interfaz:', _nic) break cidr = netaddr.IPNetwork('%s/%s' % (net_info['addr'], net_info['netmask'])) network = cidr.network gateway = ni.gateways().get('default')[2][0] # {2: ('172.16.205.1', 'eth0')} net_info['gateway'] = gateway net_info['network'] = str(network) return net_info def main(port): cs = socket(AF_INET, SOCK_DGRAM) cs.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) cs.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) cs.bind(('', port)) while 1: # FIXME: debe estar en un loop checkeando time.time() y un timeout por si viene GriZmio sin \n, pero # el mensaje es tan corto que funca igual data, addr = cs.recvfrom(1024) if data.strip() == 'GriZmio': # cs.sendto('{}\n'.format(json.dumps(get_address_info(), separators=(',', ':'))), addr) cs.sendto('{}\n'.format(json.dumps(get_address_info(), separators=(',', ':'))), ('255.255.255.255', addr[1])) main(port=9999)
Client code: from socket import * s = socket(AF_INET, SOCK_DGRAM) s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) s.sendto('GriZmio', ('255.255.255.255', 9999)) r = '' while not r.endswith('\n'): data, addr = s.recvfrom(1024) r += data print(r.strip())











