The socket module in Python

Source: Internet
Author: User
Tags ip number set socket string format server port htons

This article refers to the first chapter of Python network programming


Import socket
Help (socket)

Functions:
Socket ()--Create a new socket object
Socketpair ()--Create a pair of new socket objects [*]
FROMFD ()--Create a socket object from an open file descriptor [*]
GetHostName ()--Return the current hostname
gethostbyname ()--Map a hostname to its IP number
GETHOSTBYADDR ()--Map an IP number or hostname to DNS info
Getservbyname ()--Map a service name and a protocol name to a port number
Getprotobyname ()--Map a protocol name (e.g. ' TCP ') to a number
Ntohs (), Ntohl ()--Convert, +--bit int from network to host byte order
Htons (), htonl ()--Convert, +--bit int from host to network byte order
Inet_aton ()--Convert IP addr string (123.45.67.89) to 32-bit packed format
Inet_ntoa ()--convert 32-bit packed format IP to string (123.45.67.89)
SSL ()--Secure Socket Layer support (only available if configured)
Socket.getdefaulttimeout ()--Get the default timeout value
Socket.setdefaulttimeout ()--Set the default timeout value
Create_connection ()--connects to a address, with an optional timeout and optional source address.

A brief introduction to the functions:

First, the Socket class method (directly can be called through the Socket Class)

1, gethostbyname ()--Map a hostname to its IP number

In [1]: Import Socketin [2]: Socket.gethostname () out[2]: ' God '

2, gethostbyname ()--Map a hostname to its IP number

In [6]: Import socket in [8]: Hostname=socket.gethostname () in [9]: Print Hostnamegodin [ten]: Socket.gethostbyname (Hostnam e) out[10]: ' 127.0.1.1 ' in [All]: Socket.gethostbyname (' www.baidu.com ') out[11]: ' 119.75.218.70 '

3, GETHOSTBYADDR ()--Map an IP number or hostname to DNS info

in [+]: import socket in [+]: socket.gethostbyaddr (' God ') out[13]: (' God ', [], [' 127.0.1.1 ']) in []: Socket.gethostbyad                                    Dr (' 119.75.218.70 ')---------------------------------------------------------------------------herror Traceback (most recent) <ipython-input-14-612b876e1ed4> in <module> ()----> 1 sockets. GETHOSTBYADDR (' 119.75.218.70 ') Herror: [Errno 2] Host name lookup failure

GetHostByName and gethostbyaddr two functions are dependent on DNS (the results are obtained first from/etc/hosts, and then the corresponding results are obtained in the DNS server).


4, protocol name, port number related
Getservbyport ()--Return the service name from a port number and protocol name.
Getservbyname ()--Map a service name and a protocol name to a port number

In [1]: Import Socketin [2]: socket.getservbyname (' http ') out[2]: 80In [4]: Socket.getservbyport (+) out[4]: ' FTP '

Note: Getservbyport and getservbyname two ways to obtain information should be obtained from/etc/services

5. IPV4 Address Translation
Inet_aton ()--Convert IP addr string (123.45.67.89) to 32-bit packed format
Inet_ntoa ()--convert 32-bit packed format IP to string (123.45.67.89)

in [+]: add = ' 127.0.0.1 ' in [max]: packed_addr = Socket.inet_aton (add) in [max]: ADDR2 = Socket.inet_ntoa (packed_addr) in [24 ]: Addr = = Addr2out[24]: True

Inet_ntop (...)
Inet_ntop (AF, PACKED_IP), string formatted IP address
Convert a packed IP address of the given family to string format.

Inet_pton (...)
Inet_pton (AF, IP), packed IP address string
Convert an IP address from string format to a packed string suitable for use with low-level network functions.

Inet_pton is often used to determine the validity of an address. For example, determine if an IPV6 address is valid

DEF&NBSP;VALIDIP6ADDR (address):     "" "    returns true if   ' Address '  is a valid IPv6 address.         >>> validip6addr (':: ')         True         >>> validip6addr (' aaaa:bbbb:cccc:dddd::1 ')          True        >>>  Validip6addr (' 1:2:3:4:5:6:7:8:9:10 ')         False         >>> validip6addr (' 12:10 ')          False     "" "    try:         socket.inet_pton (socket.af_inet6, address)     except  (Socket.error,  attributeerror):    &Nbsp;    return false    return true 


6, host byte order and network byte order between the conversion (this need to convert the data only limited to the number)
When writing low-level network applications, it may be necessary to handle low-level data that is transmitted between two devices via a cable. In this operation, the data emitted from the host operating system needs to be converted into a network format, or reversed, since the representations of these two types of data
Not the same way. (How the data is represented in the cable and how it is represented in the computer is not the same)

Ntohs (), Ntohl ()--Convert, +--bit int from network to host byte order
Htons (), htonl ()--Convert, +--bit int from host to network byte order

Note: The parameters of the above four functions are all numbers, and the return structure is all numbers.

In [all]: data = 1234In [+]: print ' data:%s\nntohs:%s\nntohl:%s '% (data,socket.ntohs (data), Socket.ntohl (data)) data : 1234ntohs:53764ntohl:3523477504in []: print ' data:%s\nhtons:%s\nhtonl:%s '% (data,socket.htons (data), SOCKET.HTONL (data)) data:1234htons:53764htonl:3523477504

All of the above functions belong to the socket class method and can be called directly through the socket class.

Second, socket instance call
1. Create a Socket instance
Socket ([family[, type[, Proto]]), socket object
Open a socket of the given type. The family argument specifies the address family;  It defaults to af_inet. The type argument specifies
Whether a stream (Sock_stream, this is the default) or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0,
Specifying the default protocol. Keyword arguments is accepted.

According to the English explanation above:
Family default value of Af_inet is usually the default
Type select Sock_stream (TCP) and Sock_dgram (UDP), the default value is Sock_stream
Proto defaults to 0, and we don't usually have a relationship.

To create a TCP socket instance

In [6]: Import Socketin [7]: S=socket.socket (socket.af_inet,socket. SOCK_STREAM)


OK, with the socket instance, you can use many of the socket instance methods. What do these methods have?

| Methods of Socket objects (keyword arguments not allowed):
|
| Accept ()--Accept a connection, returning new socket and client address
| Bind (addr)--bind the socket to a local address
| Close ()--Close the socket
| Connect (addr)-connect the socket to a remote address
| CONNECT_EX (addr)--Connect, return an error code instead of an exception
| DUP ()--return a new socket object identical to the current one [*]
| Fileno ()--Return underlying file descriptor
| Getpeername ()--Return remote address [*]
| GetSockName ()--return to local address
| GetSockOpt (level, optname[, Buflen])--Get socket options
| GetTimeout ()--return timeout or None
| Listen (n)--Start listening for incoming connections
| Makefile ([mode, [BufSize]])--Return a file object for the socket [*]
| Recv (buflen[, Flags])--Receive data
| Recv_into (buffer[, nbytes[, flags])--receive data (into a buffer)
| Recvfrom (buflen[, Flags])--Receive data and sender's address
| Recvfrom_into (buffer[, nbytes, [, flags])
| --Receive data and sender's address (into a buffer)
| Sendall (data[, Flags])--Send all data
| Send (data[, flags])--send data, may isn't send all of it
| SendTo (data[, flags], addr)--send data to a given address
| Setblocking (0 | 1)--set or clear the blocking I/O flag
| SetSockOpt (level, optname, value)--Set socket options
| settimeout (None | float)--set or clear the timeout
| Shutdown (how)--shut traffic in one or both directions

2. Set up and get the default socket timeout time

In [6]: Import Socketin [7]: S=socket.socket (socket.af_inet,socket. SOCK_STREAM) in [9]: S.gettimeout () # At this point the GetTimeout returns none, indicating that the socket does not have a set timeout processing in []: S.settimeout (max) in [All]: S.gettimeo UT () out[11]: 60.0


3. Modify, view socket Properties setsockopt and getsockopt

The help obtained through socket instance s is as follows:

Help (S.setsockopt)

SetSockOpt (...) method of Socket._socketobject instance
SetSockOpt (level, option, value)
Set a socket option. See the Unix Manual for level and option. The value argument can either is an integer or a string.


Help (S.getsockopt)

GetSockOpt (...) method of Socket._socketobject instance
GetSockOpt (level, option[, buffersize]), value
Get a socket option. See the Unix Manual for level and option. If a nonzero buffersize argument is given, the return value was a string of that length; Otherwise it is an integer.


Where the level, option parameters in setsockopt and getsockopt need to see the Uninx Help manual to go and get relevant information

The man 7 socket can see the relevant information, including a section of the following information:

Socket Options
The socket options listed below can is set by using setsockopt (2) and read with getsockopt (2) with the socket level set to  Sol_socket for all sock‐ets. Unless otherwise noted, Optval is a pointer to an int.


Describes the option field information for level Sol_socket and response

Example: Set buffer size for socket send and receive

In [1]: Import Socketin [3]: s = Socket.socket (socket.af_inet,socket. Sol_socket) in [4]: S.getsockopt (SOCKET. Sol_socket,socket. SO_RCVBUF) out[4]: 87380In [5]: s.getsockopt (socket. Sol_socket,socket. SO_SNDBUF) out[5]: 16384In [6]: s.setsockopt (socket. Sol_socket,socket. so_rcvbuf,4096) in [7]: s.getsockopt (socket. Sol_socket,socket. SO_RCVBUF) out[7]: 8192In [8]: s.setsockopt (socket. Sol_socket,socket. so_sndbuf,4096) in [9]: s.getsockopt (socket. Sol_socket,socket. SO_SNDBUF) out[9]: 8192


4. Change socket to block or non-blocking mode

By default, the TCP socket is in blocking mode. That is, unless an operation is completed, control is not returned to the program


The help obtained through socket instance s is as follows:

Setblocking (...) method of Socket._socketobject instance
Setblocking (flag)
Set the socket to blocking (flag is true) or non-blocking (false).
Setblocking (True) is equivalent to settimeout (None);
Setblocking (False) is equivalent to settimeout (0.0)


In [2]: s = Socket.socket (socket.af_inet,socket. Sol_socket) in [3]: s.setblocking (True)


5. Reusing socket addresses

Sometimes you want to always run a socket server on the same port, regardless of whether the connection was intentionally or unintentionally closed. Some feelings
, this is useful if the client program needs to connect to the specified server port all the time, because there is no need to change the server
Port

Example:

#! /usr/bin/env python# _*_ coding: utf-8 _*_import socketimport  SYSDEF&NBSP;REUSE_SOCKET_ADDR ():     sock = socket.socket (Socket.AF_INET,socket. SOCK_STREAM)     old_state = sock.getsockopt (socket. Sol_socket,socket. SO_REUSEADDR)     print  "old sock state: %s"  %old_state     sock.setsockopt (socket. Sol_socket,socket. so_reuseaddr,1)     new_state =  sock.getsockopt (socket. Sol_socket,socket. SO_REUSEADDR)     print  "new sock state: %s"  %new_state     local_port = 8282    srv = socket.socket (socket.AF_ Inet,socket. SOCK_STREAM)     #  At this time  socket  does not open from     srv.setsockopt ( Socket. Sol_socket,socket. so_reuseaddr,0)      srv.bind ('', Local_port))     srv.listen (1)     print  "listening on  port: %s  " %local_port    while True:         try:            conn, addr  = srv.accept ()             print  " connected by %s:%s " % (addr[0],addr[1])         except  KeyboardInterrupt:            break         except socket.error,msg:             print  '%s '  %msgif __name__ ==  ' __main__ ':  &NBSP;&NBSP;&NBSP;REUSE_SOCKET_ADDR ()

After running, repeat telnet to port 8282 on the other end to see what happens.

$ python testsocketreuse.py old sock state:0new sock state:1listening on port:8282 Connected by 127.0.0.1:52733


testsocketreuse.py script to execute test again after exiting

Old sock state:0new sock State:1traceback (most recent call last): File ' testsocketreuse.py ', line-up, in <module>    ; REUSE_SOCKET_ADDR () file "testsocketreuse.py", line A, in Reuse_socket_addr Srv.bind ((", local_port)) file"/usr/lib  /python2.7/socket.py ", line 224, in Meth return GetAttr (self._sock,name) (*args) Socket.error: [Errno 98] Address already In use

At this point the discovery Port has been reused and cannot be executed again, and this can be performed successfully after the port resource that is waiting to be reused is freed.


Enable Port reuse:

# at this point the socket is not turned on from using srv.setsockopt (socket. Sol_socket,socket. so_reuseaddr,1)


At this point, repeated execution of this script, there is no port reuse phenomenon.

This article is from the "Learning Notes" blog, so be sure to keep this source http://unixman.blog.51cto.com/10163040/1656641

The socket module in Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.