Getting a free TCP port & blocking it

theneb onetwofour at gmail.com
Fri Feb 29 19:17:11 EST 2008


Hi all,
I'm attempting to block a TCP port from any other application from
using it until I free it from python, this is so that:
1). Generate a random free user-space port
2). Generate the script for the external program with the port
3). Free the port before external program execution.

This is what I have so far:
class portFinder:
	port = None
	socketobj = None

	def __init__(self):
		i=2000
		portStatus=0
		while portStatus!=111:
			sockobj = socket(AF_INET, SOCK_STREAM)
			portStatus=sockobj.connect_ex(('localhost',i))
			if portStatus!=111:
				i+=1
			sockobj.close()
			self.socketobj=socket(AF_INET, SOCK_STREAM)
			self.socketobj.bind(('localhost',i))
			self.socketobj.setblocking(1)
			self.port=i
	def getPort(self):
		return self.port

	def free(self):
		self.socketobj.close()



More information about the Python-list mailing list