Python Test UDP status

Source: Internet
Author: User
Tags python script

Test the latency and packet loss of UDP between two machines with a Python script

#!/usr/bin/python#-*-coding:utf-8-*-import socketimport structimport randomimport timeimport logging#from __future__ Import divisionlogfile = "/tmp/check_wzry_%s.log"% time.strftime ("%y-%m-%d") Logging.basicconfig (level=logging. DEBUG, format= '% (asctime) s Srvzcheck [% (funcName) s]% (levelname) s% (message) s ', date fmt= '%y-%m-%d%h:%m:%s ', Filename=logfile, filemode= ' a ') Tcp_rsp_code = {0x00: "S Uccess ", 0x01:" Server_fail ", 0x02:" not_allowed ", 0x03:" Network_unreachable ", 0x04:" Host_unreachable ", 0 X05: "Refused", 0x06: "ttl_expired", 0x07: "command_not_supported", 0x08: "address_type_not_supported", 0x09: "Request_error", 0x0A: "Route_error", 0xEF: "unknown_error"}connection_timeout = 500connection_error = 501FORWARD_ER ROR = 600forward_rsp_error = 601internal_error = 400SUCCESS = 0x00class Client (object): Def __init__ (self, sbserver, SB Port): Self.sbserver = Sbserver        Self.sbport = Sbport self.serveraddr = (sbserver, sbport) Self.recvbuff = 1024x768 Self.teststr = ' subaotest ' Self.tstrlen = Len (self.teststr) Self.socket = Socket.socket (socket.af_inet, socket. SOCK_STREAM) def setTimeout (self, T): Self.socket.settimeout (t) def close (self): return self.socket.cl  OSE () def connect (self): Pass def __del__ (self): Self.socket.close () class Wzrymeasure (Client): def __init__ (self, Sbserver, Sbport): Super (Wzrymeasure, self). __init__ (Sbserver, sbport) Self.socket = socket. Socket (socket.af_inet, socket.  SOCK_DGRAM) Self.idx = 2052 Self.tid = 2053 def __createmeasuredata (self): ver = 0x01 cmd =  0x01 fin = 0xFE return struct.pack ("!2B2HB", ver, cmd, self.idx, Self.tid, Fin) def __checkrspdata (self, Data): ver, RSP, idx, tid, fin = Struct.unpack ("!2B2HB", Data) if RSP = = 0x00 and fin = = 0xfe:r Eturn RSP else:logging.warning ("Response data not match, [str:%s, end:%s]"% (RSP, FIN)) return RSP def forwarddata (self): try: # AAA = Time.time () self.settimeout (1) test Data = Self.__createmeasuredata () self.socket.sendto (TestData, self.serveraddr) Rspdata = Self.socke T.recv (self.recvbuff) # BBB = Time.time () # Print bbb-aaa return Self.__checkrspdata (rspd ATA) except socket.timeout:logging.exception ("Conntion '%s:%s ' timeout"% self.serveraddr) r Eturn connection_timeout except Socket.error, E:super (Wzrymeasure, self). Close () Logging.exc            Eption (e) return connection_error except Exception, E:super (Wzrymeasure, self). Close ()  Logging.exception (e) return Internal_error def run (self): return Self.forwarddata () def run (obj, OPT, echoserver): REt = 0 for echo in echoserver:echoparts = Echo.split (': ') z = obj (opt.server, Opt.port, Echoparts[0], Ech    OPARTS[1]) code = z.run () ret = code if code = = 0:break Print Retdef check_loss (): Success_num = [] delay = [] for I in Range (Ten): now = Time.time () if z.run () = = 0:last = T Ime.time () success_num.append (i) Every_delay = Last-now Delay.append (every_delay) r Eturn (10-len (Success_num)) *10,sum (delay)/len (delay) if __name__ = = "__main__": Import optparse parse = Optparse. Optionparser (usage= "Usage:%prog [Options] Echo_ip:echo echo_ip:port", version= "%prog 1.0 ") Parse.add_option ("-S ","--server ", dest=" Server ", help=" Wzry IP ", type=" string ") parse.add_option ("-P ","--port " , dest= "Port", action= "store", type= "int", help= "Wzry port") parse.add_option ("-P", "--testwzry", dest= "Prober", action            = "Store_true",         help= "Porber measure Check", Default=false) parse.add_option ("-L", "--check_loss", dest= "loss", action= "store_ True ", help=" check udp loss ", Default=false) parse.add_option ("-D ","--check_delay ", dest=" delay ", Action= "Store_true", help= "check UDP delay", default=false) opt, args = Parse.parse_args () Z = W Zrymeasure (Opt.server, Opt.port) if Opt.loss:print check_loss () [0] elif opt.delay:print check_loss () [1] else:print parse.print_help ()

How to use: Delay: demo.py-s $host-P $port-P-D delay

Packet loss: Demo.py-s $host-P $port-P-L loss

Python Test UDP status

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.