Reputation: 87
I wanted to create a piece of code which takes in 2 lists (1st is an IP list, 2nd is a Port list). using iteration, I have tried to achieve connection (some addresses in the list are not working.) and getting the first HTTP page in order to check if the address is alive or dead.
This is the code I wrote:
import socket
import sys
ipees = []
portees = []
text_file = open("/home/loggyipport.txt", "r")
lines = text_file.readlines()
def go():
for x in lines:
ip, port = x.split()
ipees.append(ip)
portees.append(port)
go()
def dfunc(ipees, portees):
for (ip, port) in zip(ipees, portees):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ip, int(port)))
s.send('GET / HTTP/1.0\r\n\r\n')
while 1:
buf = s.recv(1000)
if not buf:
break
sys.stdout.write(buf)
s.close()
dfunc(ipees, portees)
The script is running with no errors. The problem is that I get no output. Can someone figure out what is the problem? Does my for loop using the 'zip' function is correctly written?
Upvotes: 0
Views: 289
Reputation: 15433
In your dfunc function, the program successfully connects to the first IP and infinitely waits for data from the server because of that infinite loop. If all you want is to check that some data is received from the server, you do not need the while loop at all.
Here is a function that might do what you want:
def dfunc(ipees, portees):
for (ip, port) in zip(ipees, portees):
try:
s = socket.create_connection((ip, port), timeout=10)
s.send('GET / HTTP/1.0\r\n\r\n')
buf = s.recv(1000)
print buf
except socket.error:
print 'Could not connect to ({0}, {1})'.format(ip, port)
Upvotes: 1
Reputation: 4998
You don't return anything inside your functions, and you don't print anything to the console. The only time you do this is in dfunc(ipees, portees)
where you have sys.stdout.write(buf)
. Try adding a sys.stdout.flush
to flush the buffer and print to the screen.
sys.stdout.write(buf)
sys.stdout.flush()
Actually, there's one more issue I may have found. Does the script ever terminate? You have an infinite while
loop in dfunc
.
while 1:
buf = s.recv(1000)
I don't know much about socket.socket
but it looks as if that loop will never terminate.
Your
if not buf:
break
is not part of your loop. You have to fix the indentation on that, so it becomes part of your loop. Thanks to popovitsj for pointing it out!
Upvotes: 1