Python send UDP packet

前端 未结 5 1773
盖世英雄少女心
盖世英雄少女心 2021-01-30 06:23

I am trying to write a program to send UDP packets, as in https://wiki.python.org/moin/UdpCommunication The code appears to be in Python 2:

import socket

UDP_I         


        
5条回答
  •  臣服心动
    2021-01-30 07:02

    Manoj answer above is correct, but another option is to use MESSAGE.encode() or encode('utf-8') to convert to bytes. bytes and encode are mostly the same, encode is compatible with python 2. see here for more

    full code:

    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))
    

提交回复
热议问题