1

This is the code I am trying to run. But the program produces a socket.error. I have a network proxy with port 8080 which connects me to the Internet, what more details do I have to add here to create this socket connection?

import socket

mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('www.pythonlearn.com', 80))
mysock.send('GET http://www.pythonlearn.com/code/intro-short.txt HTTP/1.0\n\n')

while True:
    data = mysock.recv(512)
    if ( len(data) < 1 ) :
        break
    print data;

mysock.close()
Hilal Faiz
  • 19
  • 6
  • You have to connect to the proxy (`mysock.connect(('localhost', 8080))`). The proxy then will take care of connecting to `www.pythonlearn.com:80` – Andrea Corbellini Feb 11 '16 at 22:59
  • I tried to connect to the proxy by importing the socks library but I get redirected to a McAfee gateway link. It is probably because of the network's security measures, what should I do? – Hilal Faiz Feb 12 '16 at 21:37
  • You should read the documentation for the proxy server, or contact support (if customer support is an option) – Andrea Corbellini Feb 12 '16 at 23:13

2 Answers2

1

If I run your code I get the error TypeError: a bytes-like object is required, not 'str' from line 5.

Try using: mysock.send(b'GET http://www.pythonlearn.com/code/intro-short.txt HTTP/1.0\n\n') with the b before your string indicating a bytestring.

bastelflp
  • 9,362
  • 7
  • 32
  • 67
  • Try using `socks` to get through the proxy as given in [this answer](http://stackoverflow.com/a/2339260/5276734). – bastelflp Feb 11 '16 at 21:48
1

I too got a type error upon running your code, and did not have an error connecting the socket. When using the socket library, make use of the makefile method so you won't have to deal with annoying details.

mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
my_sock_input = mysock.makefile('r')
my_sock_output = mysock.makefile('w')

Now my_sock_input can use methods like readline(), without any details on bytes to reserve or wotnot. Same convenience stuff for output, but with write. Remember to close all of them!

As to your problem, I tried writing similar things using my makefile variables and I wasn't recieving any message back. So there is some other issue there.

Now, the solution. A simpler way to download a url and read its contents is using the urllib.request library. If you are on Python 2.7, just import urrlib.

import urllib.request

data =  urllib.request.urlopen('http://www.pythonlearn.com/code/intro-short.txt')
readable = data.read()
print(readable)
bastelflp
  • 9,362
  • 7
  • 32
  • 67
David Jay Brady
  • 1,034
  • 8
  • 20