2012-12-15 2 views
3

나는이 점에서 상당히 순진하다. 왜 내 연결이 시간 초과되는지 확실하지 않습니다. 미리 감사드립니다. python socket.connect -> 시간 초과 이유?

#!/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) 

추적

다시 대신 그냥 특정 연결의 타임 아웃을 설정할 수 있습니다,이 코드 당신은 모든 새로운 소켓의 기본 시간 제한을 변경할 필요가 없습니다

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 
+1

포트 21에서 열려고하는 FTP 포트라고 가정합니다. FTP 클라이언트를 사용하여 연결하여 네트워크/FTP 서버가 정상인지 확인 했습니까? – PeterJ

답변

2

에 의해 생성. 값이 약간 낮기 때문에 10-15 초로 늘리면 트릭을 할 수 있습니다.

s.settimeout(10) 

그리고 당신은 사용 "노력"해야 다음

s = socket.socket() 

:

먼저 이렇게하려면 연결에 추가하십시오

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

이 나타납니다 출력에 시스템 오류 메시지를 표시하고 예외를 처리하십시오. 코드의

수정 된 버전 :

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) 
+0

이 코드가 효과가 있습니까? 내 시간은 아직 끝나지 않았 니? –

+0

IP가 로컬 네트워크에있는 것처럼 보이므로 테스트 할 수 없습니다. 문제는 s.recv 부분 일 수 있습니다. 서비스가 연결을 허용하는지 테스트하고 싶다면 s.close() 다음에 "return True"를 추가하고 socket_to_me()의 결과를 출력하십시오 –

+0

[Python 2 Socket HOWTO] (http://docs.python.org/2/howto/sockets.html)을 참조하십시오. –

0

127.0.0.1로 변경 192.168.95.148 (로컬 호스트 - 자신에게 연결)와 동일한 시스템에 this program를 실행합니다. 그렇게하면 연결할 대상이 생깁니다.