【问题标题】:Cannot listen for UDP packets in Python- socket.error: [Errno 49] Can't assign requested address无法在 Python-socket.error 中侦听 UDP 数据包:[Errno 49] 无法分配请求的地址
【发布时间】:2023-04-10 08:13:01
【问题描述】:

我正在尝试侦听我通过本地网络发送的 UDP 数据包。

我已经尝试过使用https://wiki.python.org/moin/UdpCommunication,没有任何乐趣和许多其他教程。

我正在从 Windows 笔记本电脑发送此数据包

import socket
import time

Host = '192.168.1.7'
Port = 5050
Message = 'hello world'+time.asctime()

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

while True:
   sock.sendto(Message(Host,Port)
   print 'sent', Message
   time.sleep(5)

我已使用以下方法尝试接收 UDP 数据包

import socket

Host = '192.168.1.138'
Port = 5050

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

sock.bind((Host, 5050))

while True:
    recieved = sock.recv(1024)
    print recieved

import socket


UDP_IP = "192.168.1.138"

UDP_PORT = 5050

sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)  # UDP

sock.bind((UDP_IP, UDP_PORT))


while True:

    data, addr = sock.recvfrom(1024)  # buffer size is 1024 bytes

    print "received message:", data

我在 localhost 上运行了以下接收方法并且工作得非常好,但是一旦我在我的局域网上分配了一个设备的 IP 地址,我就会得到以下信息:

/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Users/Myname/Desktop/untitled/recieve.py
Traceback (most recent call last):
  File "/Users/Myname/Desktop/untitled/recieve.py", line 12, in <module>
    sock.bind((UDP_IP, UDP_PORT))
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 228, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 49] Can't assign requested address

Process finished with exit code 1

我在 4 个不同的设备上测试了这个,它们都运行 python 2.7,这和我得到的消息是一样的。它在 Windows 7 笔记本电脑、MacBook、Kali Linux 笔记本电脑和 raspberryPi 上的 PIXEL Raspbian 上运行

【问题讨论】:

  • 也许你想做的是 sock.bind((None, UDP_PORT)) ?这样,您将在所有本地网络接口上接收传入数据包,而不仅仅是在 IP 地址为 192.168.1.138 的网络接口上。
  • 类似错误回滚(最近一次调用最后一次):文件“/Users/Faiz/Desktop/untitled/recieve.py”,第 12 行,在 sock.bind((None, UDP_PORT) ) 文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py”,第 228 行,方法返回 getattr(self._sock,name)(*args) TypeError: coercing到 Unicode:需要字符串或缓冲区,找到无类型
  • 糟糕,对不起,我的意思是:sock.bind(("", UDP_PORT))
  • 有效!!!谢谢!

标签: python sockets udp client-server


【解决方案1】:

如果您使用socket.bind(("localhost", 80))socket.bind(("127.0.0.1", 80)),您仍然会有一个“服务器”套接字,但它只能在同一台机器中可见。

您可以尝试socket.bind(("", 80)) 告诉套接字可以通过机器可能拥有的任何地址访问。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-13
    • 2017-05-08
    • 1970-01-01
    • 2013-10-15
    • 1970-01-01
    • 2013-08-08
    • 2016-08-18
    • 2015-05-26
    相关资源
    最近更新 更多