我想绑定一个套接字来侦听某个范围内的任何开放端口。通常我绑定到零,操作系统很好地给我一个随机的开放端口。但是现在我需要保持在防火墙指定的4000-5000
之间的某个范围内。如何向操作系统询问此范围内的开放端口?
我是用Python做的。我对跨平台解决方案很感兴趣,但我会选择特定于Linux的解决方案。
答案 0 :(得分:0)
你需要写一个函数来做到这一点。像这样的东西。
它只是在给定的范围内随机选择一个端口并尝试绑定它。如果已经采用,则引发套接字错误98。然后循环并选择另一个直到成功,或者在10次尝试后仍然不成功退出以防止死锁。主程序调用此函数并侦听套接字。如果需要,可以使用getsockname来显示端口。
import socket
import random
def bind_to_random_socket(low, up):
_counter = 0
foo = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
while True:
try:
_port = random.randint(low, up)
foo.bind(("localhost", _port))
return foo
except:
counter += 1
if counter > 10:
print "cannot find a free port within range"
exit(1)
_ns = bind_to_random_socket(4000, 4200)
# to get the port number:
_addr, _port = _ns.getsockname()
print _port
_ns.listen(1)
希望这会有所帮助。
哈努哈利
答案 1 :(得分:0)
为了完全相同的目的,我写了一小段代码
# SWAMI KARUPPASWAMI THUNNAI
import socket
class Ports:
"""
This class is ued to find all the open ports present
"""
__upper_bound = 0
__lower_bound = 0
__ip = "127.0.0.1" # change your i.p if it is not your machine IP
__ports = [] # our actively available ports
# used to set upper and lower bounds i.e the range of the ports to be scanned
def __init__(self,initial,final):
self.__lower_bound=initial
self.__upper_bound=final
# a method which scans for the range of ports
def scan_for_ports(self):
for i in range(self.__lower_bound,self.__upper_bound):
print("[SCANNING]: "+str(i))
check = self.is_port_opened(i)
if check == 0:
self.__ports.append(i) # append our opened port no
# a method to find whether a port is opened
def is_port_opened(self,portNo):
try:
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
connection = client.connect_ex((self.__ip,portNo)) # remember it is a tuple
port_opened = connection
client.close()
print(port_opened)
return port_opened
except socket.error as e:
print("SOCKET CANNOT BE CREATED! Do you have admin previlidges? or the port may be closed!")
print(e)
return -1
return -1
# A method to get the list of open ports
def get_list(self):
for i in self.__ports:
print("OPENED: "+str(i))
if __name__=="__main__":
ports = Ports(75,81)
ports.scan_for_ports()
ports.get_list()
现在,您可以轻松编写客户端以侦听特定端口。我已经在我的计算机上打开了一个端口(80),使用一个小的python脚本进行几分钟测试,结果很好看到这里!