I have the following scripts:
import socket
import sys
import traceback
msg = socket.gethostbyname(socket.gethostname())
dest = ('<broadcast>',10100)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.sendto(msg, dest)
print "Sent."
while 1:
(buf,address)=s.recvfrom(10100)
if not len(buf):
break
print "Received from %s: %s" %(address, buf)
And then:
import socket
import traceback
import os
host = ''
port = 10100
sx = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sx.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sx.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sx.bind((host,port))
while 1:
try:
message, address = sx.recvfrom(10104)
print "Got data from", address
sx.sendto("ola",address)
except (KeyboardInterrupt, SystemExit):
raise
except:
traceback.print_exc()
I’m having some trouble having both of them on the same script.
I just wanted to learn more about sockets, etc, this is nothing in particular.
My idea was to have just one script in each machine (Raspberry Pi), and whenever they’re on the same network, one will know about the presence of the other.
Hope I had explained right.
Thanks for all the help.
I’ve found these two links.
The first one is really great, simple and is working like needed. May help someone else:
http://www.cs.bilgi.edu.tr/~mgencer/Ders%20Malzemeleri/IThingTaggedFile/p2p.py
https://github.com/zetaron/python-udp-p2p