Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python socket.connect -> timed out why?

Tags:

python

sockets

I'm fairly naive in this regard. I'm not sure why my connection is timing out. Thanks in advance.

#!/usr/bin/env python
import socket

def socket_to_me():
    socket.setdefaulttimeout(2)
    s = socket.socket()
    s.connect(("192.168.95.148",21))
    ans = s.recv(1024)
    print(ans)

the trace back generated by this code

Traceback (most recent call last):
  File "logger.py", line 12, in <module>
    socket_to_me()
  File "/home/drew/drewPlay/python/violent/networking.py", line 7, in socket_to_me
    s.connect(("192.168.95.148",21))
  File "/usr/lib/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
timeout: timed out
like image 578
Drew Verlee Avatar asked Dec 15 '12 04:12

Drew Verlee


People also ask

How do I fix socket timeout in Python?

How do I increase the socket timeout in Python? Then, you can get the socket timeout value by calling gettimeout() and alter the value by calling the settimeout() method. The timeout value passed to the settimeout() method can be in seconds (non-negative float) or None .

Why does socket timeout happen?

Socket timeouts can occur when attempting to connect to a remote server, or during communication, especially long-lived ones. They can be caused by any connectivity problem on the network, such as: A network partition preventing the two machines from communicating. The remote machine crashing.

What is socket timeout in Python?

A new Python socket by default doesn't have a timeout. Its timeout defaults to None. Not setting the connection timeout parameter can result in blocking socket mode. In blocking mode, operations block until complete or the system returns an error.


1 Answers

You don't need to alter the default timeouts for all new sockets, instead you can just set the timeout of that particular connection. The value is a bit low though, so increasing it to 10-15 seconds will hopefully do the trick.

First, do this:

s = socket.socket()

Then:

s.settimeout(10)

And you should use "try:" on the connect, and add:

except socket.error as socketerror:
    print("Error: ", socketerror)

This will bring up the systems error message in your output and handle the exception.

Modified version of your code:

def socket_to_me():
    try:
        s = socket.socket()
        s.settimeout(2)
        s.connect(("192.168.95.148",21))
        ans = s.recv(1024)
        print(ans)
        s.shutdown(1) # By convention, but not actually necessary
        s.close()     # Remember to close sockets after use!
    except socket.error as socketerror:
        print("Error: ", socketerror)
like image 162
Aleksander S Avatar answered Sep 22 '22 00:09

Aleksander S