Casey McCarthy Casey McCarthy - 7 months ago 40
Python Question

Cannot iterate list of strings into connect function with socket

I am trying to determine if a list of webservers are listening on a port with the socket library. However I cannot get the iteration to successfully run through the list:

#!/usr/bin/python

import socket

myList = ['www.google.com', 'www.spoon.com']
scanList = []
port = 80

def resolveHost(x):
try:
h = socket.gethostbyname(x)
except:
pass
return h

def scan(host,port):
s = socket.socket()
s.connect(host,port)
print s.recv(3)


for x in myList:
scanList.append(resolveHost(x))

print scanList

for x in scanList:
scan(x,25)


This is returning:

Traceback (most recent call last):
['216.58.199.196', '207.32.184.61']
File "C:/Users/Casey/Desktop/projects/dsid_check.py", line 28, in <module>
scan(x,25)
File "C:/Users/Casey/Desktop/projects/dsid_check.py", line 18, in scan
s.connect(host,port)
File "C:\Python27\lib\socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
TypeError: connect() takes exactly one argument (2 given)

Process finished with exit code 1


Where I expect to see is the response from those pages, but I dont.

---------- edited source ------------

So I have modified my source to look as such:

#!/usr/bin/python

import socket

myList = ['www.espn.com', 'www.google.com', 'www.spoon.com']

scanList = []
port = 80

def resolveHost(x):
try:
h = socket.gethostbyname(x)
return h
except:
print "Could not resolve %s" % x

def scan(host,port):
hostR = resolveHost(host)
s = socket.socket()
s.settimeout(3)
s.connect((hostR,port))
try:
print s.recv(1024)
except:
print "Connection to %s timed out" % x


for x in myList:
scanList.append(resolveHost(x))

for x in scanList:
scan(x,port)


With this I am not able to connected to a list of web servers that should be online. Reading Alex's recommended library link now.

Answer

You need to pass the two arguments as a pair in a single tuple.

>>> import socket
>>> s = socket.socket()
>>> help(s.connect)

connect(...) method of socket._socketobject instance
    connect(address)

    Connect the socket to a remote address.  For IP sockets, the address
    is a pair (host, port).

>>> s.connect('127.0.0.1', 80)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/alexhall/.pyenv/versions/2.7.10/lib/python2.7/socket.py", line 228, in meth
    return getattr(self._sock,name)(*args)
TypeError: connect() takes exactly one argument (2 given)
>>> s.connect(('127.0.0.1', 80))  # works