简体   繁体   中英

Python socket.connect strange behaviour

I can't google it, and can't understand why this code works the way it works

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

Edited:

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

Looks like this is TCP socket =) I guess Python does some checks and drops incorrect values but does not provide any information about that trick.

From the documentation :

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

With socket.socket(socket.SOCK_DGRAM) you use SOCK_DGRAM as family even though this is a type. This will cause strange problems like the one you have seen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM