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

    Join Date
    Oct 2004
    Rep Power

    detecting socket in use on localhost

    I am looking for some code to detect whether or not there is already a listener to a socket (tcp or udp) on the localhost.

    I am writing some software that can be run multiple times on a localhost and each will instantiate a listener within a known range of ports. I have checked several resources (Cookbook, Python Network Programming (Goerzen), Programming Python(Lutz)) but cannot find the crux.

    Anyone care to point me to some nice methods?
  2. #2
  3. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Woodland Hills, Los Angeles County, California, USA
    Rep Power
    You could always use try...except like this:
    #!/usr/bin/env python
    import socket
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.bind(("localhost", 80))
    except socket.error, (errno, strerror):
            print "Error code(%d), Error Message: %s " % (errno, strerror)
            print "Unknown error"
    You could check errno at the exception handler and see if it is the value for socket already in use (in my case, the value is 48)
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo

IMN logo majestic logo threadwatch logo seochat tools logo