python socket UDP-Based Broadcast

Standard library module socket implementation.

First introduced the name used:

  • AF_INET: IPv4
  • SOCK_DGRAM:UDP
  • SOL_SOCKET: Universal socket option
  • SO_BROADCAST: 广播

Service-Terminal:

import socket
import time
PORT = 6000
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
while True:
    time.sleep(1)
    s.sendto(b'Hello!', ('<broadcast>', PORT))

Client:

import socket
PORT = 6000
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((socket.gethostname(), PORT))
while True:
    data, address = s.recvfrom(1024)
    print(data.decode())

Explanation:

The server code implements the above transmission by UDP broadcast Hello!information to the client.

Compared with the conventional UDP transport, primarily for broadcast server adds code to open the broadcast function, and transmits the address information set <broadcast>.

Released four original articles · won praise 0 · Views 25

Guess you like

Origin blog.csdn.net/m0_46396257/article/details/104641490