Drew Verlee
Drew Verlee

Reputation: 1900

python socket.connect -> timed out why?

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

Upvotes: 8

Views: 57111

Answers (3)

damanpreet singh
damanpreet singh

Reputation: 119

its a fake address, i think you are reading violent python if you want to make that work, type socket.gethostname() instead of fake ip address it will get connected to your machine.This is my code:

    def Socket_to_me(ip,port,time):
        try:
            s = socket.socket()
            s.settimeout(time)
            s.connect((ip,port))
            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) 

call the method by:
Socket_to_me(socket.gethostname(),1234,10)

Upvotes: 0

Charles Noon
Charles Noon

Reputation: 601

Change 192.168.95.148 to 127.0.0.1 (localhost - connecting to yourself) and run this program on the same machine. That way you'll have something to connect to.

Upvotes: 0

Aleksander S
Aleksander S

Reputation: 384

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)

Upvotes: 6

Related Questions