Finding whether services are open for ports between 1 to 100

We will create a program that will find whether any port is open between 1 to 100. We will be scanning ports on target machine ‘1.1.1.1’

First of all import socket module

import socket

Importing time module to set timeout for socket connection

import time

Specify target machine where port scanning require. In this case, we are using 1.1.1.1 as a target IP address

target = '1.1.1.1'

Using for loop and giving range from 1 to 100

for p in range(1,100):

In each loop, creating a socket and setting default timeout value to 1 second. We are creating a TCP based socket

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
socket.setdefaulttimeout(1)

Now using built in function socket.connect_ex(). This function returns 0 if the operation is successful. For any error, function returns number which is not zero. Function takes two parameters IP address and port number

Assigning output of function to variable result

result = s.connect_ex((target,p))

If the result is zero, print port is open otherwise port is closed

if result == 0:
    print('Port {} is open'.format(p))
else:
    print('Port {} is close'.format(p))

At last, closing the socket

s.close()

Output

Port 1 is close
Port 2 is close
Port 3 is close
Port 4 is close
Port 5 is close
Port 6 is close
Port 7 is close
Port 8 is close
Port 9 is close
Port 10 is close
Port 11 is close
Port 12 is close
Port 13 is close
Port 14 is close
Port 15 is close
Port 16 is close
Port 17 is close
Port 18 is close
Port 19 is close
Port 20 is close
Port 21 is close
Port 22 is close

Complete Code

import socket
import time

target = '1.1.1.1'


for p in range(1,100):
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
socket.setdefaulttimeout(1)
result = s.connect_ex((target,p))
if result == 0:
print('Port {} is open'.format(p))
else:
print('Port {} is close'.format(p))
s.close()
Advertisement

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s