RPiAwesomeness
RPiAwesomeness

Reputation: 5159

Python - What's wrong with my socket code

I have a simple Python program I am currently developing and for some reason, it won't work.
The way the full program works is it has a list of 20 ports and it then loops through that list basically pinging the host on the selected port. Here's the code:

import socket
import sys

print '  +-====================================================-+'
print ' /                                                        \ '
print '|                       PyPortScanner                      |'
print '|                       by Ag3ntChr0m                      |'
print ' \                                                        /'
print '  +-====================================================-+'
print ''

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
    print 'Failed to create socket. Error code: ' + str(msg[0]) + 'Error message: ' + msg[1]
    sys.exit()
print 'Socket Created'

host = raw_input('Enter the desired host to scan: ')
port = [80, 443, 21, 22, 4567, 8080, 25, 3389, 23, 53, 1723, 110, 135, 445,
        139, 1863, 143, 8081, 10000, 1025]
portFail = []
print 'Scanning top 20 most often open ports ...'

try:
    remote_ip = socket.gethostbyname( host )

except socket.gaierror:
    #couldn't resolve host at port
    print 'Hostname could not be resolved. Program exiting'
    sys.exit()

print 'IP address of ' + host + ' is ' + remote_ip

print '+-===================================-+'
print '| Ports Scanned:----------------------|'
print '+-===================================-+'
print ''

#Connect to remote server
for i in range(0, 20):
    portScan = int(str(port[i]))    <----
    try:

        s.connect((remote_ip, portScan))
        print "\t" + str(portScan)
        s.close()

    except:

        portFail.append(portScan)
        err = True

raw_input('Press Enter to Continue...')

if err:
    print '+-=============================-+'
    print '| Failed Port Scan:-------------|'
    print '+-=============================-+'
    print ''
    size = len(portFail)
    for i in range(1, size):
        print "\t" + str(portFail[i])

When you run the program it then is supposed to

When I go to run the program it prints the first port on the list (80) under Ports Scanned, but the rest get placed under Failed Port Scan - even though I know at least some of they are open.

How would I get this program ping more ports than the first successfully?

Upvotes: 0

Views: 552

Answers (3)

pradyunsg
pradyunsg

Reputation: 19406

As pointed by @cnicutar, you cannot reuse a socket, but you always can start a new socket for every new connection.
You should use a for loop for scanning the ports, something like:

for p2scan in port:
    try:
        print "scanning: %s" % p2scan
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((remote_ip, p2scan))
    except:
        portFail.append(p2scan)
        err = True
    finally:
        s.close()

Upvotes: 0

TAS
TAS

Reputation: 2079

As noted in the answer from @cnicutar you can't reuse the socket. But you also should close() the socket after use in all cases as this will release the underlying resources. This can also be seen in the examples found in the api documentation.

When you are successfull at connecting to a port you should call shutdown() afterwards to ensure that it is closed.

Here is the relevant part of the code:

for portScan in port:
    try:
        print "scanning: %s" % portScan 
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((remote_ip, portScan))
        s.shutdown(socket.SHUT_RDWR)
    except:
        portFail.append(portScan)
        err = True
    finally:
        s.close()

I also took the liberty to simplify the loop.

NOTE: My experiment showed that shutdown() did not allow me to reuse the socket.

Upvotes: 0

cnicutar
cnicutar

Reputation: 182609

You can't just reuse the same socket and connect again. Try making a new socket each time:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((remote_ip, portScan))

Even if you close a socket, that doesn't put it back into a position where it can be reconnected.

Upvotes: 1

Related Questions