1996-11-27 19:52:01 +00:00
|
|
|
#! /usr/bin/env python
|
1991-07-01 18:32:32 +00:00
|
|
|
|
|
|
|
# Client and server for udp (datagram) echo.
|
|
|
|
#
|
|
|
|
# Usage: udpecho -s [port] (to start a server)
|
|
|
|
# or: udpecho -c host [port] <file (client)
|
|
|
|
|
|
|
|
import sys
|
|
|
|
from socket import *
|
|
|
|
|
|
|
|
ECHO_PORT = 50000 + 7
|
|
|
|
BUFSIZE = 1024
|
|
|
|
|
|
|
|
def main():
|
|
|
|
if len(sys.argv) < 2:
|
|
|
|
usage()
|
1992-05-19 13:51:20 +00:00
|
|
|
if sys.argv[1] == '-s':
|
1991-07-01 18:32:32 +00:00
|
|
|
server()
|
1992-05-19 13:51:20 +00:00
|
|
|
elif sys.argv[1] == '-c':
|
1991-07-01 18:32:32 +00:00
|
|
|
client()
|
|
|
|
else:
|
|
|
|
usage()
|
|
|
|
|
|
|
|
def usage():
|
|
|
|
sys.stdout = sys.stderr
|
|
|
|
print 'Usage: udpecho -s [port] (server)'
|
|
|
|
print 'or: udpecho -c host [port] <file (client)'
|
|
|
|
sys.exit(2)
|
|
|
|
|
|
|
|
def server():
|
|
|
|
if len(sys.argv) > 2:
|
|
|
|
port = eval(sys.argv[2])
|
|
|
|
else:
|
|
|
|
port = ECHO_PORT
|
|
|
|
s = socket(AF_INET, SOCK_DGRAM)
|
2000-08-25 15:38:41 +00:00
|
|
|
s.bind(('', port))
|
1991-07-01 18:32:32 +00:00
|
|
|
print 'udp echo server ready'
|
|
|
|
while 1:
|
|
|
|
data, addr = s.recvfrom(BUFSIZE)
|
|
|
|
print 'server received', `data`, 'from', `addr`
|
|
|
|
s.sendto(data, addr)
|
|
|
|
|
|
|
|
def client():
|
|
|
|
if len(sys.argv) < 3:
|
|
|
|
usage()
|
|
|
|
host = sys.argv[2]
|
|
|
|
if len(sys.argv) > 3:
|
|
|
|
port = eval(sys.argv[3])
|
|
|
|
else:
|
|
|
|
port = ECHO_PORT
|
|
|
|
addr = host, port
|
|
|
|
s = socket(AF_INET, SOCK_DGRAM)
|
2000-08-25 15:38:41 +00:00
|
|
|
s.bind(('', 0))
|
1991-07-01 18:32:32 +00:00
|
|
|
print 'udp echo client ready, reading stdin'
|
|
|
|
while 1:
|
|
|
|
line = sys.stdin.readline()
|
|
|
|
if not line:
|
|
|
|
break
|
|
|
|
s.sendto(line, addr)
|
|
|
|
data, fromaddr = s.recvfrom(BUFSIZE)
|
|
|
|
print 'client received', `data`, 'from', `fromaddr`
|
|
|
|
|
|
|
|
main()
|