A single string is used for the AF_UNIX address family.
A pair (host, port) is used for the AF_INET address family, where host is a string representing either a hostname in Internet domain notation like ‘daring.cwi.nl’ or an IPv4 address like ‘100.50.200.5’, and port is an integer
对于IPv4地址来说,如果host为空字符串,则表示INADDR_ANY任意地址;如果host为
,则表示 INADDR_BROADCAST 广播地址。
如果host用主机名表示,那么python会自动从系统host文件或DNS记录中选择第一个符合条件的IPv4地址。
socket.error
This exception is raised for socket-related errors. The accompanying value is either a string telling what went wrong or a pair (errno, string) representing an error returned by a system call, similar to the value accompanying os.error. See the module errno, which contains names for the error codes defined by the underlying operating system.
socket.herror
This exception is raised for address-related errors, i.e. for functions that use h_errno in the C API, including gethostbyname_ex() and gethostbyaddr().
The accompanying value is a pair (h_errno, string) representing an error returned by a library call. string represents the description of h_errno, as returned by the hstrerror() C function.The error value will match one of the EAI_*constants defined in this module.
socket.timeout
This exception is raised when a timeout occurs on a socket which has had timeouts enabled via a prior call to settimeout(). The accompanying value is a string whose value is currently always “timed out”.
地址簇 These constants represent the address (and protocol) families, used for the first argument to socket(). If the AF_UNIX constant is not defined then this protocol is unsupported.
socket.AF_UNIX
socket.AF_INET
socket.AF_INET6
socket类型 These constants represent the socket types, used for the second argument to socket(). (Only SOCK_STREAM and SOCK_DGRAM appear to be generally useful.)
socket.SOCK_STREAM
socket.SOCK_DGRAM
socket.SOCK_RAW
socket.SOCK_RDM
socket.SOCK_SEQPACKET
socket.setsockopt()常用参数选项 Many constants of these forms, documented in the Unix documentation on sockets and/or the IP protocol, are also defined in the socket module. They are generally used in arguments to the setsockopt() and getsockopt() methods of socket objects. In most cases, only those symbols that are defined in the Unix header files are defined; for a few symbols, default values are provided.
SO_*
socket.SOMAXCONN
MSG_*
SOL_*
IPPROTO_*
IPPORT_*
INADDR_*
IP_*
IPV6_*
EAI_*
AI_*
NI_*
TCP_*
socket.has_ipv6
This constant contains a boolean value which indicates if IPv6 is supported on this platform.
如果系统支持IPv6,则值为True,否则为False
socket.create_connection(address[, timeout[, source_address]])
连接到address(a 2-tuple (host, port))主机,并返回一个socket对象。如果host是非数字主机地址,那么会尝试用AF_INET和AF_INET6去解析它,然后尝试连接所有可能的地址,直到连接成功。
timeout默认使用socket.getdefaulttimeout()返回的值
source_address是形如(host, port)的元组,默认由系统提供。
socket.getaddrinfo(host, port[, family[, socktype[, proto[, flags]]]])
将host/port转换成5-元组的列表,元组包含链接主机所需要的所有信息。如
(family, socktype, proto, canonname, sockaddr)
host:字符串类型的主机名或IP地址,也可为None
port:int类型的端口号或字符串类型的服务名(形如http,ftp),也可以为None
family,socktype,proto三个参数默认值为0
falg的默认值为0。flag可以等于一个或多个AI_*常量,该值将影响函数返回结果。例如,如果flag=AI_NUMERICHOST,将不允许主机名进行解析,要是host是主机名,则会raise一个错误
函数返回结果(family, socktype, proto, canonname, sockaddr)中,family, socktype, proto都是整数,意味着它们可以直接传递给socket.socket()函数。canonname等于host的权威主机名,如果flags包括AI_CANONNAME 的话,否则为空字符串。sockaddr 等于一个描述socket address的元组,具体格式取决于family的值,如果family等于AF_INET,那么socketaddr等于(host,port);如果family等于AF_INET6,那么sockaddr等于(address, port, flow info, scope id)。sockaddr可以直接当作参数传递给socket.connect()。
example
>>> socket.getaddrinfo("www.python.org", 80, 0, 0, socket.SOL_TCP)
[(2, 1, 6, '', ('82.94.164.162', 80)),
(10, 1, 6, '', ('2001:888:2000:d::a2', 80, 0, 0))]
socket.getfqdn([name])
如果name缺省,那么返回本机主机名;否则返回指定name的所有主机名。这里调用了gethostbyaddr(),gethostname()。
socket.gethostbyname(hostname)
根据hostname返回IPv4地址。不支持IPv6。如果想要获得Ipv6地址,可以选择getaddrinfo()。
socket.gethostbyname_ex(hostname)
根据hostname返回一个元组,形如(hostname, aliaslist, ipaddrlist)
example 1
>>> gethostbyname_ex('www.baidu.com')
('www.a.shifen.com', ['www.baidu.com'], ['112.80.248.74', '112.80.248.73'])
example 2
>>> gethostbyname_ex('www.taobao.com')
('www.gslb.taobao.com.danuoyi.tbcache.com', ['www.taobao.com'], ['58.23.4.151', '58.23.4.141'])
socket.gethostname()
返回本机的主机名。可以利用gethostbyname(gethostname())得知本机IP地址
socket.gethostbyaddr(ip_address)
返回(hostname, aliaslist, ipaddrlist)
socket.getprotobyname(protocolname)
Translate an Internet protocol name (for example, ‘icmp’) to a constant suitable for passing as the (optional) third argument to the socket() function. This is usually only needed for sockets opened in “raw” mode (SOCK_RAW); for the normal socket modes, the correct protocol is chosen automatically if the protocol is omitted or zero.
socket.getservbyname(servicename[, protocolname])
将网络服务名称转换为端口号
example
>>>getservbyname('http')
80
>>> getservbyname('ftp')
21
>>> getservbyname('smtp')
25
socket.getservbyport(port[, protocolname])
将端口号转换为网络服务名
example
>>> getservbyport(80)
'http'
>>> getservbyport(21)
'ftp'
>>> getservbyport(25)
'smtp'
socket.socket([family[, type[, proto]]])
创建一个socket对象
family:AF_INET,AF_INET6,AF_UNIX(不适用与windows)
type:SOCK_STREAM,SOCK_DGRAM
proto:默认为0或缺省
socket.socketpair([family[, type[, proto]]])
创建一对连接好的socket对象。只适用于Unix
socket.fromfd(fd, family, type[, proto])
Duplicate the file descriptor fd (an integer as returned by a file object’s fileno() method) and build a socket object from the result. Address family, socket type and protocol number are as for the socket() function above. The file descriptor should refer to a socket, but this is not checked — subsequent operations on the object may fail if the file descriptor is invalid. This function is rarely needed, but can be used to get or set socket options on a socket passed to a program as standard input or output (such as a server started by the Unix inet daemon). The socket is assumed to be in blocking mode. Availability: Unix
socket.ntohl(x)
将来自网络的32bit的正整数x转换为用主机字节序表示的整数。
socket.ntohs(x)
将来自网络的16bit的正整数x转换为用主机字节序表示的整数。
socket.htonl(x)
将来自主机的32bit的正整数x转换为用网络字节序表示的整数。
socket.htons(x)
将来自主机的16bit的正整数x转换为用网络字节序表示的整数。
example
>>> htonl(1)
16777216L
解释:我此时用的电脑是小尾系统,1在内存中用16进制表示为01000000(内存地址左低右高),转换为网络字节序后(也就是大尾系统)在内存在用16进制表示为00000001。因此,当执行htonl(1)后,该结果在内存中用16进制表示为00000001,由于系统是小尾系统,所以读取内存后得到的结果为0x01000000=16777216L
>>> htons(1)
256
>>>ntohl(1)
16777216L
socket.inet_aton(ip_string)
将十进制形式的IP地址转换为二进制形式的IP地址
socket.inet_ntoa(packed_ip)
将二进制形式的IP地址转换为十进制形式的IP地址
socket.inet_pton(address_family, ip_string)
Unix适用
socket.inet_ntop(address_family, packed_ip)
Unix适用
socket.getdefaulttimeout()
Return the default timeout in seconds (float) for new socket objects. A value of None indicates that new socket objects have no timeout. When the socket module is first imported, the default is None.
返回新创建socket对象的默认timeout,如果返回None表示socket对象没有设置timeout。当socket模块是第一次import时,返回值为None。
socket.setdefaulttimeout(timeout)
Set the default timeout in seconds (float) for new socket objects. A value of None indicates that new socket objects have no timeout. When the socket module is first imported, the default is None.
为新创建的socket对象设置timeout。
socket.accept()
调用accept()方法之前,socket对象必须执行了bind((host,port))方法将socket绑定到某个端口,以及listen(n)方法监听该端口的连接。返回(conn, address),conn是新的已连接的socket对象,用来接受和发送数据,address是发起连接请求方的地址(host,port)
socket.bind(address)
在将socket对象绑定到一个地址之前该socket必须是未绑定状态,也就是说socket对象只能绑定一次。参数address取决于address_family
socket.close()
关闭socket连接,所有socket对象的方法将不可用。另一方和你连接的socket对象不再收到任何数据(在缓存队列数据刷新之后)。socket对象会被垃圾回收机制自动关闭。执行close()会立即释放该socket连接的所有资源,如果你不想这样做,可以调用shutdown()。
socket.connect(address)
连接到另一个远程socket,address格式取决于address family
socket.connect_ex(address)
类似connect(),但会返回一个错误指示,而不会raise一个错误而导致程序退出。如果连接成功,那么返回0,否则返回errno
socket.fileno()
返回一个socket的文件描述符,结合select.select()非常有用。在windows下该文件描述符可能会失去正常文件描述符的效果,但在Unix下没有此限制。
select(…)
select(rlist, wlist, xlist[, timeout]) -> (rlist, wlist, xlist)
Wait until one or more file descriptors are ready for some kind of I/O.
The first three arguments are sequences of file descriptors to be waited for:
rlist – wait until ready for reading
wlist – wait until ready for writing
xlist – wait for an “exceptional condition”
If only one kind of condition is required, pass [] for the other lists.
A file descriptor is either a socket or file object, or a small integer
gotten from a fileno() method call on one of those.The optional 4th argument specifies a timeout in seconds; it may be
a floating point number to specify fractions of seconds. If it is absent
or None, the call will never time out.The return value is a tuple of three lists corresponding to the first three
arguments; each contains the subset of the corresponding file descriptors
that are ready.* IMPORTANT NOTICE *
On Windows and OpenVMS, only sockets are supported; on Unix, all file
descriptors can be used.
socket.getpeername()
返回远程主机socket的地址
socket.getsockname()
返回本机socket的地址
socket.getsockopt(level, optname[, buflen])
Return the value of the given socket option (see the Unix man page getsockopt(2)). The needed symbolic constants (SO_* etc.) are defined in this module. If buflen is absent, an integer option is assumed and its integer value is returned by the function. If buflen is present, it specifies the maximum length of the buffer used to receive the option in, and this buffer is returned as a string. It is up to the caller to decode the contents of the buffer (see the optional built-in module struct for a way to decode C structures encoded as strings).
socket.listen(backlog)
设置监听连接queue的最大长度,最小等于0,最大值取决于系统,一般等于5
socket.makefile([mode[, bufsize]])
返回一个与socket对象相关联的file对象,socket对象必须是blocking模式而且没有设置timeout。socket对象和file对象的关闭操作或垃圾回收操作是互相独立的。参数mode与内建函数file()的参数mode一样。
socket.recv(bufsize[, flags])
从socket中接收数据,参数bufsize指定接受数据的大小,一般等于2的整数幂(如1024,4096)。返回值是字符串。flag默认等于0。
socket.recvfrom(bufsize[, flags])
类似于recv(),但是返回值等于(string,address),address是发送数据的socket的地址。flag默认为0。
socket.recvfrom_into(buffer[, nbytes[, flags]])
将接收的数据写入到buffer中。参数nbytes指定接收多少字节的数据,参数flag默认为0。返回值为(nbytes, address),nbytes等于接收到数据的字节数,address等于发送数据的socket的地址。
socket.recv_into(buffer[, nbytes[, flags]])
将接收的数据写入到buffer中。参数nbytes指定接收多少字节的数据,参数flag默认为0。返回值等于接收到数据的字节数。
socket.send(string[, flags])
发送string到已经处于连接状态的socket,返回值等于以发送数据的字节数。
该方法会检查数据是否全部传送完毕,如果还有数据没有传送完,它会尝试继续传送剩余的数据。
socket.sendall(string[, flags])
发送string到已经处于连接状态的socket,不同于send()方法,sendall()方法会一直发送数据知道所有数据是发送完毕。如果发送成功,返回值等于None,否则raise一个错误。
socket.sendto(string, flags, address)
发送string到远程主机的socket,socket对象必须是无连接状态。远程socket用address描述。
socket.setblocking(flag)
设置socket是否阻塞。flag等于0,非阻塞;flag等于其他值,阻塞。
如果socket设置为阻塞状态,那么send(),sendall()sendto(),recv(),recvfrom()等方法都会阻塞状态,直到缓冲区非空或非满。如果设置为非阻塞,那么当send()无法发送数据或recv()无法接收数据时,会产生错误。
默认情况下,socket为阻塞状态
socket.settimeout(value)
设置超时,value等于非负浮点数,单位为秒。如果发送或接收操作在限定时间内一直被阻塞,那么会产生timeout异常。如果value等于None,相当于setblocking(1),会一直阻塞下去。value等于0.0相当于setblocking(0),非阻塞。
socket.gettimeout()
返回timeout,非负浮点数或None。取决于最后一次setblocking()或settimeout()
Notice
Some notes on socket blocking and timeouts: A socket object can be in one of three modes: blocking, non-blocking, or timeout. Sockets are always created in blocking mode. In blocking mode, operations block until complete or the system returns an error (such as connection timed out). In non-blocking mode, operations fail (with an error that is unfortunately system-dependent) if they cannot be completed immediately. In timeout mode, operations fail if they cannot be completed within the timeout specified for the socket or if the system returns an error. The setblocking() method is simply a shorthand for certain settimeout() calls.
Timeout mode internally sets the socket in non-blocking mode. The blocking and timeout modes are shared between file descriptors and socket objects that refer to the same network endpoint. A consequence of this is that file objects returned by the makefile() method must only be used when the socket is in blocking mode; in timeout or non-blocking mode file operations that cannot be completed immediately will fail.
Note that the connect() operation is subject to the timeout setting, and in general it is recommended to call settimeout() before calling connect() or pass a timeout parameter to create_connection(). The system network stack may return a connection timeout error of its own regardless of any Python socket timeout setting
socket.setsockopt(level, optname, value)
Set the value of the given socket option (see the Unix manual page setsockopt(2)). The needed symbolic constants are defined in the socket module (SO_* etc.). The value can be an integer or a string representing a buffer. In the latter case it is up to the caller to ensure that the string contains the proper bits (see the optional built-in module struct for a way to encode C structures as strings).
socket.shutdown(how)
关闭“连接”,如果how等于SHUT_RD,禁止接收数据;如果how等于SHUT_WR,禁止发送数据;如果how等于SHUT_RDWR,禁止接收和发送数据。在Mac OS X系统上,how等于SHUT_WR不仅禁止本机socket发送数据,而且还禁止另一端的远程socket接收数据
socket.family
The socket family.
socket.type
The socket type.
socket.proto
The socket protocol.