DotNetRussell
DotNetRussell

Reputation: 9867

Python Socket Timing out

I am attempting to open a socket to google on port 80 but for the life of me I can't figure out why this is timing out. If I don't set a timeout it just hangs indefinitely.

I don't think my companies firewall is blocking this request. I can navigate to google.com in the browser so there shouldn't be any hangups here.

import socket

HOST = '173.194.121.39'   
PORT = 80             

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.settimeout(20)


data = s.recv(1024)
print(data)
s.close()

Upvotes: 2

Views: 133

Answers (1)

v1k45
v1k45

Reputation: 8250

This will work:

import socket

HOST = 'www.google.com'
PORT = 80

IP = socket.gethostbyname(HOST)

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((IP, PORT))

message = b"GET / HTTP/1.1\r\n\r\n"

s.sendall(message)

data = s.recv(1024)
print(data.decode('utf-8'))
s.close()

What was wrong with you code: Your code was directly using the IP, i tried looking up for the IP by hostname using socket.gethostbyname(). (i dont know why :P)

You were expecting data to be returned without sending any. I used s.sendall method to send a HTTP request (since you're using python3, the data must be sent in bytes). Also decoded the data returned to print.

I hope, it will work for you too.

Upvotes: 3

Related Questions