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()
-
2Disregard my comment. It was useless :-)Reut Sharabani– Reut Sharabani2015年08月13日 13:56:47 +00:00Commented Aug 13, 2015 at 13:56
-
1Examine your browser's configuration to determine if you have an HTTP proxy established. If so, your PC probably doesn't have connectivity to Google.Robᵩ– Robᵩ2015年08月13日 14:03:54 +00:00Commented Aug 13, 2015 at 14:03
-
It really looks like a proxy issue. Even if you companie does not block the website, the proxy require an authentication and a request to access to google.com. I wold say the same as @Robφ: check if you have a proxy authentication anywhere.FunkySayu– FunkySayu2015年08月13日 14:29:03 +00:00Commented Aug 13, 2015 at 14:29
-
I don't see where you issued a 'GET'. Why would you expect to receive anything?stark– stark2015年08月13日 14:32:10 +00:00Commented Aug 13, 2015 at 14:32
-
@stark I am using a (very weakly modified) version of the Python Socket DocumentationDotNetRussell– DotNetRussell2015年08月13日 14:33:37 +00:00Commented Aug 13, 2015 at 14:33
1 Answer 1
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.