I tried to run following program on my Mac terminal.

import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('www.py4inf.com', 80))
mysock.send('GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')

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

But it doesn't print anything and takes forever. I tried some online platform to execute and got error message

"""Traceback (most recent call last): File "main.py", line 6, in mysock.connect(('www.py4inf.com', 80)) File "/usr/lib64/python2.7/socket.py", line 228, in meth return getattr(self._sock,name)(*args) socket.error: [Errno 110] Connection timed out"""

I put print statement after True: and before line "data = " and it prints statement there and then takes forever.

My Python environment is

"Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin"

And in different computer, it works.

Can anybody identify an issue?

  • Please format code using markdown - see the FAQ - also please show code as text not a screenshot so we can copy, run and test it. Also can you connect to that URL on that computer using telnet etc – Mark Feb 28 '16 at 20:37

Your program runs well on my MAC OS Mavericks (aka 10.9.5) with Python 2.7.5 It prints:

HTTP/1.1 200 OK
Date: Sun, 27 Mar 2016 07:42:22 GMT
Server: Apache
Last-Modified: Fri, 04 Dec 2015 19:05:04 GMT
ETag: "e103c2f4-a7-526172f5b5d89"
Accept-Ranges: bytes
Content-Length: 167
Cache-Control: max-age=604800, public
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: origin, x-requested-with, content-type
Access-Control-Allow-Methods: GET
Connection: close
Content-Type: text/plain

But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fai
r sun and kill the envious moon
Who is already sick and pale with grief

I guess your program stuck while no answer was available within the TCP protocol time-out (either the server not responding or the link failing). If you want to avoid such case, you may put the "recv" statement in a separate thread and break after a time-out. I found much help for this in this page: eli.thegreenplace.net/2011/05/18/code-sample-socket-client-thread-in-python/

Hope this helps.


In the section where it says:

mysock.connect(('www.py4inf.com', 80))

There may be a slow internet connection - hence the fact its taking so long.

Also, clever python emulation websites won't let you run sockets on their emulators as you can spoof your IP and that can cause CyberSecurity issues.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .