简体   繁体   English

python 循环套接字连接

[英]python looping socket connections

Question regarding the python socket package关于 python 插座 package 的问题

My goal is to create a simple.network port scanner.我的目标是创建一个简单的网络端口扫描器。 This is the basic idea:这是基本思想:

#List of ports to scan
ports = [20,21,22,23,25,80]

#dictionary of port statuses
port_status = {}

#Create socket:
MY_SOCK = s.socket(s.AF_INET, s.SOCK_STREAM)

#For loop to scan each port
for port in ports:
    TARGET = ("192.168.12.123", port)
    
    #If connection is successful, result should be int 0
    result = MY_SOCK.connect_ex(TARGET)

    #save port and status as key/pair value
    port_status[port] = result

    #Terminate socket
    MY_SOCK.shutdown(s.SHUT_RDWR)
    MY_SOCK.close()

I am having an issue that after the first successful socket connection, it doesn't restart properly for the following sockets.我有一个问题,在第一次成功的套接字连接后,它没有为以下 sockets 正确重启。

With the syntax shown above, I get thrown an OSerror使用上面显示的语法,我得到了一个 OSerror

if I don't do a shutdown, it makes one successful connection then doesn't connect to the following ports.如果我不关机,它会建立一个成功的连接,然后不会连接到以下端口。

There must be something wrong with my closing of the socket.我关闭套接字一定有问题。

Any advice?有什么建议吗? Many thanks非常感谢

By running it line by line outside the loop, I managed to pinpoint the problem.通过在循环外逐行运行它,我设法查明了问题所在。

The issue is that if a connection fails, it throws an error because it could not terminate a failed connection问题是如果连接失败,它会抛出错误,因为它无法终止失败的连接

I solved it (incorporating h4z3's advice to move the socket creation into the for loop) in the following way:我通过以下方式解决了它(结合 h4z3 的建议将套接字创建移动到 for 循环中):

for port in ports:
    MY_SOCK = s.socket(s.AF_INET, s.SOCK_STREAM)
    TARGET = ("192.168.12.123", port)
    result = MY_SOCK.connect_ex(TARGET)
    port_status[port] = result

    #Only attempt to close connection if connection was successful (== 0)
    if result == 0:
        MY_SOCK.shutdown(s.SHUT_RDWR)
        MY_SOCK.close()

Thanks for the assistance感谢您的协助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM