I have two ethernet cards, and I would like to send out UDP broadcast message on the local network(192.168.0.255) but it seams that the UDP message send out only the first ethernet card.
ip ="255.255.255.255"
UDPSocket = socket.socket( socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP )
UDPSocket.setsockopt( socket.SOL_SOCKET, socket.SO_BROADCAST, True )
UDPSocket.settimeout( timeout )
UDPSocket.sendto( msg.xmlmsg, ( ip, UDPport ) )
UDPSocket.close()
How can I specified that witch subnet would I send the message?
You have to bind the socket to a local address.
For a non-broadcast UDP socket you usually bind to the any address (0.0.0.0). You can also choose a particular port or let the system choose one for you (port 0). If you don't bind the socket explicitly it will be bound automatically to 0.0.0.0:0 on the first send.
To do broadcast is always recommended to do the bind explicitly and specify your own local address of the selected interface. If you do not need a particular port you can use port 0.
The accepted answer doesn't work for me, trying to send ICMP ECHO requests on a raw socket. I had to do this:
target = '8.8.8.8'
packet = bytearray(...)
sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
sock.setsockopt(socket.SOL_SOCKET, 25, 'eth0') # or whatever the name of the interface is
# 25 = SO_BINDTODEVICE
# Some Python installations will have the constant IN.SO_BINDTODEVICE which you can use here, YMMV
sock.sendto(packet, (target, 1))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With