Last active
January 4, 2023 19:43
-
-
Save jlamimoso/765d7985c42706394da3f648729a7178 to your computer and use it in GitHub Desktop.
Python program which test the connection of a list of IP:PORT and returns the result in a dictionary. It uses non-blocking socket with select and connect_ex.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket, select | |
def checkIPs(list_ips): | |
socks = [] | |
fds = {} | |
ips = {} | |
for k in list_ips: | |
ip = k.split(':') | |
if len(ip) == 2: | |
ips[k] = {'conectado': False} | |
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) | |
s.setblocking(False) | |
try: | |
s.connect_ex((ip[0], int(ip[1]))) | |
socks.append(s) | |
fds[s.fileno()] = {'ip': k, 'socket': s} | |
except Exception as e: | |
print(e) | |
while len(socks): | |
rl, wl, el = select.select([], socks, [], 2) | |
if not wl: | |
break | |
for w in wl: | |
fd = w.fileno() | |
dic = fds[fd] | |
s = dic['socket'] | |
if (s.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) == 0): | |
ip = ips[dic['ip']] | |
ip['conectado'] = True | |
s.close() | |
socks.remove(s) | |
return ips | |
if __name__ == '__main__': | |
import time | |
list_ips = ['{}:80'.format(socket.gethostbyname('google.com')), | |
'{}:80'.format(socket.gethostbyname('yahoo.com')), | |
'{}:80'.format(socket.gethostbyname('uol.com.br')), | |
'127.0.0.1:9090', | |
'127.0.0.1:9091', | |
'127.0.0.1:9092'] | |
ini = round(time.time()*1000) | |
r = checkIPs(list_ips) | |
print (r) | |
fim = round(time.time()*1000) | |
print(fim-ini) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment