2017-05-28 26 views
0

我是Python的新手(截至上周),我仍然在掌握基本知识,所以请原谅我的任何无知。Python:检索当前机器上的套接字列表?

作为我家庭作业的一部分,我被要求制作一个基本的端口扫描仪,其中一个功能是检索当前机器上的套接字列表。我一直在四处寻找,并设法拼凑一段代码,允许我输入希望扫描的机器的IP地址,但我想尝试一下,以便自动扫描正在运行的计算机。

elif (userChoice == "4"): 

    print("You selected " + userChoice) 

    try: 

     s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # s will be equal to the command looking for the IPV4 addresses 

    except socket.error: 

     sys.exit("Failed to create socket.") # error handling message to be printed to the console should a socket failed to be created 

    print("Socket created") 

    hostAddress = input("Please enter host address to scan - example 'www.server.com': ") 
    print ("You entered " + hostAddress) 

    try: 
     remoteIP = socket.gethostbyname(hostAddress) 

    except socket.gaierror: 

      sys.exit("Hostname could not be resolved exiting") 

      ret = input("Hit return to go back to the menu") 

      continue 

    print("IP address of " + hostAddress + ' is ' + remoteIP) 

这是我的代码到目前为止。如果任何人都可以帮助我,或者告诉我是否我正在朝着正确的方向前进,我会非常感激。

此外,我作为一个noob,如果任何人有任何好的阅读材料的建议,以帮助我去掌握基本知识,我将非常感激。

谢谢。

+0

'hostAddress = 'localhost''或替代地'hostAddress =' 127.0.0.1''? –

回答

0

要检查远程服务器 - 开放端口

# For input hostAddress 
remoteIP = socket.gethostbyname(hostAddress) 
for port in range(1,1025): 
     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
     result = sock.connect_ex((remoteIP, port)) 
     if result == 0: 
      print("Port %s: Open"%port) 
     sock.close() 

=> Port 80: Open