#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2004
    Posts
    49
    Rep Power
    11

    sockets & address already in use error


    Hi All,

    Fairly new to Python - got a module running a server on a designated port on the localhost. However, when I stop the server and try to run it again I get the following error:

    socket.error: (98, 'Address already in use')

    Unless, I choose a different port the error does not go away. My code is:

    import socket
    import os

    ip = 'localhost'
    port = 3458

    mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    mySocket.bind((ip,port))
    mySocket.listen(1)

    while True:
    channel,details = mySocket.accept()
    print 'Connection established with', details
    channel.send('Connection established to server\n')
    channel.send('Logging please wait...\n')
    os.popen('netstat -an>log.txt')
    channel.send('Done.\n')
    channel.close()

    Any ideas please?
  2. #2
  3. Mini me.
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Location
    Cambridge, UK
    Posts
    783
    Rep Power
    14
    Don't assume garbage collection will tidy up for you...
    port 3458 is open.

    Don't forget code tags.

    I would think a try/finally block would help - so whatever the reason you can always close the server port.

    grim
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2004
    Location
    Albuquerque, New Mexico
    Posts
    137
    Rep Power
    11
    Well, usually that error means that port is still in use. One way to prevent this is to close your sockets after using them with the close(). The only way (In my mind) to fix that is just wait for the connection to timeout or change to a different port.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2004
    Location
    Colorado, USA
    Posts
    68
    Rep Power
    11

    Port timeout


    I have written some server's in the past, and Nick is correct.
    If you do not explicitly tell the socket to close on termination of the server, you will need to wait for the OS to time it out.

    Do some googling on daemonizing a python script, and you can find some useful information on how to react to a SIGTERM, and you can make sure the socket is closed when you exit.
  8. #5
  9. Mini me.
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Location
    Cambridge, UK
    Posts
    783
    Rep Power
    14
    Originally Posted by djjhouse
    If you do not explicitly tell the socket to close on termination of the server, you will need to wait for the OS to time it out.

    and you can make sure the socket is closed when you exit.
    Sort of what I said but more clearly put.

    grim

IMN logo majestic logo threadwatch logo seochat tools logo