Python3 Portscanner无法解决socket pr0blem问题

时间:2016-04-14 17:03:12

标签: python sockets port-scanning

当我运行此代码时,我收到此套接字错误:

  

[WinError 10038]尝试对非套接字

的操作进行操作

但即使我删除了s.close(),也会给我错误的结果。

这是一个端口扫描程序,它将尝试连接到我要扫描的服务器上的所有端口。我从中获取连接的内容存储在列表中。但由于某种原因,它给了我错误的结果。有人可以帮助我。

import socket
import threading

def scan_for_open_ports():
    #Creating variables
    OpenPorts = []
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = input('Host to scan: ')
    global port
    global OpenPorts
    port = 1
    #Scanning
    for i in range(65534):

        try:

            s.connect((host, port))
            s.shutdown(2)
            OpenPorts.append(port)
            print(str(port) + 'is open.')
            s.close()
            port += 1
        except socket.error as msg:
            print(msg)
            s.close()
    show_user()
def show_user():
    #Giving the user results
    print('------Open porst-----\n')
    print(OpenPorts)

1 个答案:

答案 0 :(得分:0)

那是因为您正在使用s.close()关闭套接字内的套接字并且您没有再次打开套接字并尝试连接已关闭的套接字已经。你应该在循环结束时关闭套接字,我还修改了你的代码以使OpenPorts全局并删除你定义的不必要的port变量并在你的内部递增for loop

import socket

OpenPorts = []


def scan_for_open_ports():

    # Creating variables
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = input('Host to scan: ')

    # Scanning
    for port in range(1, 65534):
        try:
            s.connect((host, port))
            OpenPorts.append(port)
            print(str(port) + 'is open.')
        except socket.error as msg:
            print(msg)
    s.close()

    show_user()


def show_user():
    # Giving the user results
    print('------Open ports-----\n')
    print(OpenPorts)

scan_for_open_ports()