Python3 socket module (port scanner)

i’ve been reading this python script for a really basic port scanner i’m having some hardtime understanding some specific parts of this code i.e. S.connect_ex() and also if result == 0 connect_ex() takes exactly one argument and if we do result = s.connect_ex((ip,port)) then the code works but with result = s.connect_ex(ip,port) doesn’t works more importantly what is this connect_ex()

both are at the end in the for loop would really appreciate if someone could help me out

here’s the code:

import sys
import socket
import datetime

if len(sys.argv) == 2:
    ip = socket.gethostbyname(sys.argv[1])

    print('incorrect syntax Man -_-')

print('_ '* 50)    
print('scanning target' + ip)
print('time started'+ str( )
print('_'* 50)

    for port in range(1 , 1000):
        s = socket.socket(socket.AF_INET , socket.SOCK_STREAM)
        result = s.connect_ex(ip,port)
        print(f'cheking port no: {port}')

        if result == 0:
            print(f'port {port} is open')   

except KeyboardInterrupt:
    print('exiting the programme')

except socket.gaierror:
    print('host name could not be resolved')    

except socket.error:
    print('couldnt connect to server')    

It’s described in the Python documentation for socket.connect_ex(). In short it’s a connect call that doesn’t raise an exception if it fails, it just returns something != 0.

socket.connect_ex() accepts one parameter, the target address. The socket module supports a lot of things other then IP and TCP, so the form of the address parameter varies. For TCP over IP as you’re using the address must be a tuple of (host, port). The inner parentheses in s.connect_ex((ip, port)) create that tuple. For details, read what the socket module documentation says about address families.