Python send UDP packet

前端 未结 5 1776
盖世英雄少女心
盖世英雄少女心 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:05

    Here is a complete example that has been tested with Python 2.7.5 on CentOS 7.

    #!/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)
    

    The program reads a file, sample.csv from the current directory and sends each line in a separate UDP packet. If the program it were saved in a file named send-udp then one could run it by doing something like:

    $ python send-udp 192.168.1.2 30088
    

提交回复
热议问题