socket.bind

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • sashan

    socket.bind

    I'm writing a program using sockets. I'm binding to a port like this:

    PORT = 5000 # Arbitrary non-privileged port
    s = socket.socket(s ocket.AF_INET, socket.SOCK_STR EAM)
    s.bind((HOST, PORT))
    s.listen(1)

    Now sometimes the rest of the program crashes later for whatever reason.
    As a result this leaves a socket bound to port 5000. When I try to run
    my program again it crashes at

    s.bind((HOST, PORT))

    saying that the port is still in use. How do I unbind that port? I've
    killed the previous program using the system monitor in Gnome.

  • Peter Hansen

    #2
    Re: socket.bind

    sashan wrote:[color=blue]
    >
    > I'm writing a program using sockets. I'm binding to a port like this:
    >
    > PORT = 5000 # Arbitrary non-privileged port
    > s = socket.socket(s ocket.AF_INET, socket.SOCK_STR EAM)
    > s.bind((HOST, PORT))
    > s.listen(1)
    >
    > Now sometimes the rest of the program crashes later for whatever reason.
    > As a result this leaves a socket bound to port 5000. When I try to run
    > my program again it crashes at
    >
    > s.bind((HOST, PORT))
    >
    > saying that the port is still in use. How do I unbind that port? I've
    > killed the previous program using the system monitor in Gnome.[/color]

    You need to use setsockopt() to set the SO_REUSE_ADDR option:

    yourSock.setsoc kopt(socket.SOL _SOCKET, socket.SO_REUSE ADDR, 1)

    -Peter

    Comment

    • Jp Calderone

      #3
      Re: socket.bind

      On Sun, Oct 05, 2003 at 01:00:46PM +1300, sashan wrote:[color=blue]
      > I'm writing a program using sockets. I'm binding to a port like this:
      >
      > PORT = 5000 # Arbitrary non-privileged port
      > s = socket.socket(s ocket.AF_INET, socket.SOCK_STR EAM)
      > s.bind((HOST, PORT))
      > s.listen(1)
      >
      > Now sometimes the rest of the program crashes later for whatever reason.
      > As a result this leaves a socket bound to port 5000. When I try to run
      > my program again it crashes at
      >
      > s.bind((HOST, PORT))
      >
      > saying that the port is still in use. How do I unbind that port? I've
      > killed the previous program using the system monitor in Gnome.
      >[/color]

      Python programs don't crash (at least, hardly ever -- if the interpreter
      segfaults, you should file a bug report!). So, it's always possible to
      clean up resources you allocate.

      In this case, setting SO_REUSEADDR is a good solution to avoid needing to
      clean up, but for other resources you allocate, you might want to read up on
      the try/finally construct (http://python.org/doc/tut/node10.html, especially
      the last section), or use try/except and call a cleanup function in the
      except clause before re-raising the original exception.

      Jp


      Comment

      Working...