2016-11-17 50 views
0

我不能google一下,並不能明白爲什麼這個代碼工作它的工作原理Python的socket.connect奇怪的行爲

Python 3.5.2 (default, Sep 28 2016, 18:08:09) 
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.38)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import socket 
>>> s = socket.socket(socket.SOCK_DGRAM) 
>>> s.connect(('127.0.0.1', 33000)) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ConnectionRefusedError: [Errno 61] Connection refused 
>>> s.family 
<AddressFamily.AF_INET: 2> 
>>> 
>>> 
>>> s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
>>> s.family 
<AddressFamily.AF_INET: 2> 
>>> s.connect(('127.0.0.1', 33000)) 
>>> 

編輯的方式:

Python 3.5.2 (default, Sep 28 2016, 18:08:09) 
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.38)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> s2 = socket.socket(socket.SOCK_DGRAM) 
KeyboardInterrupt 
>>> import socket 
>>> s = socket.socket(socket.SOCK_DGRAM) 
>>> s.connect(('127.0.0.1', 33000)) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ConnectionRefusedError: [Errno 61] Connection refused 
>>> s.family 
<AddressFamily.AF_INET: 2> 
>>> s.type 
<SocketKind.SOCK_STREAM: 1> 
>>> 

貌似這個是TCP套接字=)我猜Python做了一些檢查並丟棄了不正確的值,但沒有提供任何有關該技巧的信息。

+0

順便說一句,python2也是如此 –

回答

0

documentation

socket.socket([family[, type[, proto]]]) 

隨着socket.socket(socket.SOCK_DGRAM)使用SOCK_DGRAM家庭即使這是一個類型。這會導致奇怪的問題,如你看到的那個。

+0

是的!我已經看過stdlib socket.py源代碼,並且好像沒有對參數進行保護/檢查。這有點讓人困惑......謝謝 –

+0

對不起,我不小心刪除了我的評論。你的猜測在某種意義上是正確的。請看編輯 –

+0

@NodariLipartiya:'SOCK_DGRAM','AF_INET'等只是整數,所以很難檢查。 SOCK_STREAM(TCP)只是類型的默認值,即只給出單個參數時省略的參數。 –