2017-04-18 84 views
0

我想綁定一個套接字來偵聽特定範圍內的任何打開的端口。通常情況下,我綁定到零,操作系統是好的,給我一個隨機的開放端口。但是現在我需要保持在一定範圍內,如防火牆指定的4000-5000。如何向操作系統請求此範圍內的開放端口?綁定到特定範圍的開放端口

我正在從Python這樣做。我對跨平臺解決方案感興趣,但會解決Linux特有的問題。

回答

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) 

希望這會有所幫助。

哈努哈利

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() 

現在,你可以很容易地編寫一個客戶端向特定端口上偵聽。我在我的電腦上用一個小的python腳本打開了一個端口(80)幾分鐘來測試,結果很好,請看這裏!

enter image description here

+0

我認爲,這是正確的,異常處理,面向對象的解決方案和跨platformed解決方案,您正在尋找。 –