Tom Piper
Tom Piper

Reputation: 13

Simple Port Scanner in Python - Error: an integer is required

#!/usr/bin/python3
import socket

ip = input('Enter the IP address: ')
port = input('Enter the Port: ')

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

if s.connect_ex((ip,port)):
        print ('Port', port, 'is closed')
else:
        print ('Port', port, 'is open')

As you can see, it is a very simply port scanner that I have attempted to run (currently learning some Penetration Testing).

This is the error I get:

Traceback (most recent call last):
  File "./python.py", line 9, in <module>
    if s.connect_ex((ip,port)):
TypeError: an integer is required (got type str)

I assume that I need to set line 9 as an integer - how do I do this?

Cheers in advance.

Upvotes: 1

Views: 243

Answers (3)

albert
albert

Reputation: 8593

input() returns a string, which you need to convert into an integer. Converting strings to valid integers can be a rather complex task. For a first approach change

port = input('Enter the Port: ')

into

port = input('Enter the Port: ')
try:
    port = int(port)
except ValueError as err:
    print('Invalid input. Please try again.')

Upvotes: 0

Mike Delta
Mike Delta

Reputation: 808

port = int(input('Enter the Port: '))

Upvotes: 0

gonczor
gonczor

Reputation: 4146

Here: port = input('Enter the Port: ') you read user input which is a str and you pass it as port number (which should be as you've probably already guessed an int). You traceback is telling you exactly the same thing. You need to convert the port to integer with calling int(port)

Upvotes: 1

Related Questions