簡體   English   中英

Python發送UDP數據包

[英]Python send UDP packet

我正在嘗試編寫一個程序來發送 UDP 數據包,如https://wiki.python.org/moin/UdpCommunication代碼似乎在 Python 2 中:

import socket

UDP_IP = "127.0.0.1"
UDP_PORT = 5005
MESSAGE = "Hello, World!"

print "UDP target IP:", UDP_IP
print "UDP target port:", UDP_PORT
print "message:", MESSAGE

sock = socket.socket(socket.AF_INET, # Internet
             socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))

如果我在打印的內容周圍加上括號,它只會將其打印在屏幕上。

我需要做什么才能完成這項工作?

使用 Python3x,您需要將字符串轉換為原始字節。 您必須將字符串編碼為字節。 通過網絡,您需要發送字節而不是字符。 您是對的,這適用於 Python 2x,因為在 Python 2x 中,套接字上的 socket.sendto 接受“普通”字符串而不是字節。 試試這個:

print("UDP target IP:", UDP_IP)
print("UDP target port:", UDP_PORT)
print("message:", MESSAGE)

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.sendto(bytes(MESSAGE, "utf-8"), (UDP_IP, UDP_PORT))

你的代碼對我來說是有效的。 我正在通過在 Linux 上使用netcat來驗證這一點。

使用 netcat,我可以做nc -ul 127.0.0.1 5005它將在以下位置偵聽數據包:

  • IP:127.0.0.1
  • 端口:5005
  • 協議:UDP

話雖如此,這是我在運行您的腳本時看到的輸出,同時運行 netcat。

[9:34am][wlynch@watermelon ~] nc -ul 127.0.0.1 5005
Hello, World!

如果您運行的是python 3,那么您需要將print 語句更改為print 函數,即在print 語句之后將內容放在方括號() 中。

除非您在127.0.0.1 port 5005上偵聽某些內容,否則您將看到以上所做的唯一一件事,因為您正在發送收到的數據包- 因此您需要在另一個控制台中實現並啟動示例的另一部分窗口第一,所以它正在等待消息。

上面的 Manoj 答案是正確的,但另一種選擇是使用 MESSAGE.encode() 或 encode('utf-8') 轉換為字節。 bytes 和 encode 大體相同,encode 與 python 2 兼容。更多信息請看這里

完整代碼:

import socket

UDP_IP = "127.0.0.1"
UDP_PORT = 5005
MESSAGE = "Hello, World!"

print("UDP target IP: %s" % UDP_IP)
print("UDP target port: %s" % UDP_PORT)
print("message: %s" % MESSAGE)

sock = socket.socket(socket.AF_INET, # Internet
                     socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE.encode(), (UDP_IP, UDP_PORT))

這是一個在 CentOS 7 上用 Python 2.7.5 測試過的完整示例。

#!/usr/bin/python

import sys, socket

def main(args):
    ip = args[1]
    port = int(args[2])
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    file = 'sample.csv'

    fp = open(file, 'r')
    for line in fp:
        sock.sendto(line.encode('utf-8'), (ip, port))
    fp.close()

main(sys.argv)

該程序從當前目錄讀取文件sample.csv並在單獨的 UDP 數據包中發送每一行。 如果該程序保存在名為send-udp的文件中,則可以通過執行以下操作來運行它:

$ python send-udp 192.168.1.2 30088

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM