Advertisement
rfmonk

udp_remote.py

Jan 10th, 2014
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.48 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3.  
  4. import random
  5. import socket
  6. import sys
  7. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  8.  
  9. MAX = 65535
  10. PORT = 1060
  11.  
  12. if 2 <= len(sys.argv) <= 3 and sys.argv[1] == 'server':
  13.     interface = sys.argv[2] if len(sys.argv) > 2 else ''
  14.     s.bind((interface, PORT))
  15.     print 'Listening at', s.getsockname()
  16.     while True:
  17.         data, address = s.recvfrom(MAX)
  18.         if random.randint(0, 1):
  19.             print 'The client at', address, 'says:', repr(data)
  20.             s.sendto('Your data was %d bytes' % len(data), address)
  21.         else:
  22.             print 'Pretending to drop packet from', address
  23.  
  24. elif len(sys.argv) == 3 and sys.argv[1] == 'client':
  25.     hostname = sys.argv[2]
  26.     s.connect((hostname, PORT))
  27.     print 'Client socket name is', s.getsockname()
  28.     delay = 0.1
  29.     while True:
  30.         s.send('This is another message')
  31.         print 'Waiting up to', delay, 'seconds for a reply'
  32.         s.settimeout(delay)
  33.         try:
  34.             data = s.recv(MAX)
  35.         except socket.timeout:
  36.             delay *= 2  # wait even longer for the next request
  37.             if delay > 2.0:
  38.                 raise RuntimeError('I think the server is down')
  39.         except:
  40.             raise   # a real error, so we let the user see it
  41.         else:
  42.             break   # we are done, and can stop looping
  43.  
  44.     print 'The server says', repr(data)
  45.  
  46. else:
  47.     print >>sys.stderr, 'usage: udp_remote.py server [ <iface> ]'
  48.     print >>sys.stderr, '   or: udp_remote.py client <host>'
  49.     sys.exit(2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement