Adi Koch
Adi Koch

Reputation: 91

UDP Broadcast doesn't work, What is the problem?

I am running a code that supposed to send "Hey" in broadcast, the thing is that it doesn't work and I don't know why. Here is the code:

import socket  

def main():
    searcher_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    searcher_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    searcher_socket.sendto("Hey", ("255.255.255.255", 9010))
    response, address = searcher_socket.recvfrom(1024)
    print response

main()

I sniffed in Wireshark to check if something comes out of the computer but it seems like nothing is coming out..enter image description here

Someone can help please? Thanks in advance

Edit: I have tested the code on another computer that is connected to the network by cable and not on wifi and it worked. These two computers are sharing the same network. What can be the reason for the code to work on one computer and to fail on the another?

Second Edit - Solution: I found the solution. Because the computer is connected via wifi, in order to broadcast you need to bind first the socket with your ip address.

import socket  

def main():
    searcher_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    searcher_socket.bind(("192.168.1.11", 40400)) # 192.168.1.11 is my computer ip address
    searcher_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    searcher_socket.sendto("Hey", ("255.255.255.255", 9010))
    response, address = searcher_socket.recvfrom(1024)
    print response

main()

Upvotes: 0

Views: 1195

Answers (1)

Bohdan Kaminskyi
Bohdan Kaminskyi

Reputation: 144

In the code you have posted, function main is not called. Add main() call

Upvotes: 2

Related Questions