user9409912
user9409912

Reputation:

(Python) Getting error when trying to scan range of ports for one IP address at a time

I am attempting to scan a range of ports specified by the user for one IP address at a time until the fourth octet reaches 255. However, I am running into an error that my variable named 'count' is not defined although I am defining it to =1 so the program runs through every IP address such as 53.234.12.1, 53.234.12.2, 53.234.12.3, etc.

This is what I am trying to have displayed in the interpreter after all is said and done: End Result

Here is my code:

import socket

server = 'google.com'


startPort = int(input("Enter started port number to scan: "))
endPort = int(input("Enter ending port number to scan: "))
threeOctet = str(input("Enter the first three octets of an IP to scan: "))
countFullIP = threeOctet + "." + str(count)
count = 1

for countFullIP in range(0,256):
    for count in range (startPort,endPort):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((server,countFullIP))
            print('IP',countFullIP)
        except:
            print('IP is invalid')
        try:
             print('Port',count,'is open')
        except:
             print('Port',count,'is closed')

Any assistance would be greatly appreciated. Thank you!

Upvotes: 1

Views: 113

Answers (1)

Reck
Reck

Reputation: 1436

Replace two lines

countFullIP = threeOctet + "." + str(count)
count = 1

to

count = 1
countFullIP = threeOctet + "." + str(count)

As you can see count is referenced before its assignment.

Updating the code upon additional requirement mentioned in comments.

import socket

server = 'google.com'

startPort = int(input("Enter started port number to scan: "))
endPort = int(input("Enter ending port number to scan: "))
threeOctet = str(input("Enter the first three octets of an IP to scan: "))

for count in range(0,256):
    countFullIP = threeOctet + "." + str(count)
    for count in range (startPort,endPort):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((server, countFullIP))
            print('IP',countFullIP)
        except:
            print('IP is invalid', countFullIP)
        try:
             print('Port',count,'is open')
        except:
             print('Port',count,'is closed')

Upvotes: 1

Related Questions