首先声明,这不是我写的,而是我找到的,但是别人写的相当好。
复制代码 代码如下:
# UDP multicast examples, Hugo Vincent, 2005-05-14.
import socket

def send(data, port=50000, addr='239.192.1.100'):
"""send(data[, port[, addr]]) - multicasts a UDP datagram."""
# Create the socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Make the socket multicast-aware, and set TTL.
s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 20) # Change TTL (=20) to suit
# Send the data
s.sendto(data, (addr, port))

def recv(port=50000, addr="239.192.1.100", buf_size=1024):
"""recv([port[, addr[,buf_size]]]) - waits for a datagram and returns the data."""

# Create the socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# Set some options to make it multicast-friendly
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
except AttributeError:
pass # Some systems don't support SO_REUSEPORT
s.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_TTL, 20)
s.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_LOOP, 1)

# Bind to the port
s.bind(('', port))

# Set some more multicast options
intf = socket.gethostbyname(socket.gethostname())
s.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_IF, socket.inet_aton(intf) + socket.inet_aton('0.0.0.0'))
s.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(addr) + socket.inet_aton('0.0.0.0'))

# Receive the data, then unregister multicast receive membership, then close the port
data, sender_addr = s.recvfrom(buf_size)
s.setsockopt(socket.SOL_IP, socket.IP_DROP_MEMBERSHIP, socket.inet_aton(addr) + socket.inet_aton('0.0.0.0'))
s.close()
return data


复制代码 代码如下:
#!/usr/bin/env python
from socket import *from time import sleep,time,ctime
HOST = '229.0.0.15'PORT = 9999BUFSIZ = 1024ADDR = (HOST, PORT)
udpCliSock = socket(AF_INET, SOCK_DGRAM)
data = 't'*200count = 0while(count<100 ): udpCliSock.sendto(data, ADDR) sleep(1) count = count+1
udpCliSock.close()
标签:
PYTHON,多播数据

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
内蒙古资源网 Copyright www.nmgbbs.com

评论“使用PYTHON接收多播数据的代码”

暂无“使用PYTHON接收多播数据的代码”评论...