简体   繁体   中英

Python DUP broadcast sender/receiver and broadcast IP address function

from broadcast sender

import socket, traceback

host = ''                               # Bind to all interfaces
port = 51423
broadcastaddr=findbroadcastaddr();
addr=(broadcastaddr, port)

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)                
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)   #broadcasr

data='hello from sender'

s.bind('', port)                  #socket binding to any host
s.sendto(data, addr):
s.close

1) This is a broadcast sender, I don't know the findbroadcastaddr function, basically if my network address is 192.1.3.0 then my broadcast address would be 192.1.3.255. Anybody know that function.

broadcast receiver i

mport socket

# Set the socket parameters
addr = ('', 33333)  # host, port

# Create socket and bind to address
UDPSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
UDPSock.bind(addr)

# Receive messages
while True:
    data, addr = UDPSock.recvfrom(1024)

2)1024 is the maximum number of data of bytes can be received. and the result from recvfrom breaks down into 2 fields ; the first part is data and second is where it comes from?

The following calculates a LAN broadcast address given the local machine's IP. It sets the 4th octet to 255, so host on 192.168.1.12 will get a LAN broadcast IP of 192.168.1.255

from socket import *

myip = gethostbyname(gethostname())
print 'My IP',myip

# XX: assumes /24 address
broadip = inet_ntoa( inet_aton(myip)[:3] + b'\xff' )
print 'LAN broadcast', broadip

I disagree with the answer provided by johntellsall , which merely "sets the 4th octet to 255".

You intend to calculate the broadcast address correctly, it depends on your netmask and not only your IP address. In some cases it may come down to setting the 4th octet to 0xFF .

The proper steps to calculate a broadcast address are:

  1. binary negate the netmask
  2. take the result and then OR it with the host IP address

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM