-1

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

[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)
4

1 回答 1

0

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

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()
于 2016-04-14T17:18:00.467 回答