Help with sockets!

Dave Cole djc at itga.com.au
Thu Jan 6 23:50:33 EST 2000


> I've started tinkering with sockets in Python and have the following
> modified version of the example program in the library docs.
> 
> This is intended to forward everything from a port on one machine to
> a telnet port on another machine.
> 
> The program works fine except that when I terminate the connection the
> socket remains in use:
> 
> prompt% ./redir
> Listening for connections on X port 60016
> Connected by ('X.X.X.X', 62268)
> Forwarding to 23 on X
> Closing connections. Bye.
> prompt%
> prompt% ./redir
> Listening for connections on X port 60016
> Traceback (innermost last):
>   File "./redir", line 16, in ?
>     s.bind(FORWARD, PORT)
> socket.error: (125, 'Address already in use')
> 
> Any ideas why this isn't working? The sockets are being closed before
> the program terminates.

Try adding the following line:

> --- CUT HERE ---
> #!/usr/local/bin/python
> # Echo server (p143 Python lib man)
> from socket import *
> import select
> # from select import *
> 
> def sock_avail(x):
>         """Test whether data is available on the socket."""
>         return select.select([x], [], [], 0) == ([x], [], [])
> 
> FORWARD = 'host1'
> DEST = 'host2'
> PORT = 60016
> print 'Listening for connections on', FORWARD, 'port', PORT
> s = socket(AF_INET, SOCK_STREAM)

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

> s.bind(FORWARD, PORT)
> s.listen(1)
> conn, addr = s.accept()
> print 'Connected by', addr
> try:
>         s1 = socket(AF_INET, SOCK_STREAM)
>         s1.connect(DEST,23) # telnet port
>         print 'Forwarding to 23 on', DEST
>         while 1:
>                 if sock_avail(conn):
>                         data = conn.recv(1024)
>                         s1.send(data)
>                 if sock_avail(s1):
>                         data = s1.recv(1024)
>                         conn.send(data)
> except error:
>         s.close()
>         conn.close()
>         s1.close()
>         print 'Closing connections. Bye.'

- Dave



More information about the Python-list mailing list