1 \section{\module{socket
} ---
2 Low-level networking interface
}
4 \declaremodule{builtin
}{socket
}
5 \modulesynopsis{Low-level networking interface.
}
8 This module provides access to the BSD
\emph{socket
} interface.
9 It is available on all modern
\UNIX{} systems, Windows, MacOS, BeOS,
10 OS/
2, and probably additional platforms.
12 For an introduction to socket programming (in C), see the following
13 papers:
\citetitle{An Introductory
4.3BSD Interprocess Communication
14 Tutorial
}, by Stuart Sechrest and
\citetitle{An Advanced
4.3BSD
15 Interprocess Communication Tutorial
}, by Samuel J. Leffler et al,
16 both in the
\citetitle{\UNIX{} Programmer's Manual, Supplementary Documents
1}
17 (sections PS1:
7 and PS1:
8). The platform-specific reference material
18 for the various socket-related system calls are also a valuable source
19 of information on the details of socket semantics. For
\UNIX, refer
20 to the manual pages; for Windows, see the WinSock (or Winsock
2)
23 The Python interface is a straightforward transliteration of the
24 \UNIX{} system call and library interface for sockets to Python's
25 object-oriented style: the
\function{socket()
} function returns a
26 \dfn{socket object
}\obindex{socket
} whose methods implement the
27 various socket system calls. Parameter types are somewhat
28 higher-level than in the C interface: as with
\method{read()
} and
29 \method{write()
} operations on Python files, buffer allocation on
30 receive operations is automatic, and buffer length is implicit on send
33 Socket addresses are represented as a single string for the
34 \constant{AF_UNIX
} address family and as a pair
35 \code{(
\var{host
},
\var{port
})
} for the
\constant{AF_INET
} address
36 family, where
\var{host
} is a string representing
37 either a hostname in Internet domain notation like
38 \code{'daring.cwi.nl'
} or an IP address like
\code{'
100.50.200.5'
},
39 and
\var{port
} is an integral port number. Other address families are
40 currently not supported. The address format required by a particular
41 socket object is automatically selected based on the address family
42 specified when the socket object was created.
44 For IP addresses, two special forms are accepted instead of a host
45 address: the empty string represents
\constant{INADDR_ANY
}, and the string
46 \code{'<broadcast>'
} represents
\constant{INADDR_BROADCAST
}.
48 All errors raise exceptions. The normal exceptions for invalid
49 argument types and out-of-memory conditions can be raised; errors
50 related to socket or address semantics raise the error
51 \exception{socket.error
}.
53 Non-blocking mode is supported through the
54 \method{setblocking()
} method.
56 The module
\module{socket
} exports the following constants and functions:
59 \begin{excdesc
}{error
}
60 This exception is raised for socket- or address-related errors.
61 The accompanying value is either a string telling what went wrong or a
62 pair
\code{(
\var{errno
},
\var{string
})
}
63 representing an error returned by a system
64 call, similar to the value accompanying
\exception{os.error
}.
65 See the module
\refmodule{errno
}\refbimodindex{errno
}, which contains
66 names for the error codes defined by the underlying operating system.
69 \begin{datadesc
}{AF_UNIX
}
71 These constants represent the address (and protocol) families,
72 used for the first argument to
\function{socket()
}. If the
73 \constant{AF_UNIX
} constant is not defined then this protocol is
77 \begin{datadesc
}{SOCK_STREAM
}
81 \dataline{SOCK_SEQPACKET
}
82 These constants represent the socket types,
83 used for the second argument to
\function{socket()
}.
84 (Only
\constant{SOCK_STREAM
} and
85 \constant{SOCK_DGRAM
} appear to be generally useful.)
88 \begin{datadesc
}{SO_*
}
96 Many constants of these forms, documented in the
\UNIX{} documentation on
97 sockets and/or the IP protocol, are also defined in the socket module.
98 They are generally used in arguments to the
\method{setsockopt()
} and
99 \method{getsockopt()
} methods of socket objects. In most cases, only
100 those symbols that are defined in the
\UNIX{} header files are defined;
101 for a few symbols, default values are provided.
104 \begin{funcdesc
}{getfqdn
}{\optional{name
}}
105 Return a fully qualified domain name for
\var{name
}.
106 If
\var{name
} is omitted or empty, it is interpreted as the local
107 host. To find the fully qualified name, the hostname returned by
108 \function{gethostbyaddr()
} is checked, then aliases for the host, if
109 available. The first name which includes a period is selected. In
110 case no fully qualified domain name is available, the hostname is
115 \begin{funcdesc
}{gethostbyname
}{hostname
}
116 Translate a host name to IP address format. The IP address is
117 returned as a string, e.g.,
\code{'
100.50.200.5'
}. If the host name
118 is an IP address itself it is returned unchanged. See
119 \function{gethostbyname_ex()
} for a more complete interface.
122 \begin{funcdesc
}{gethostbyname_ex
}{hostname
}
123 Translate a host name to IP address format, extended interface.
124 Return a triple
\code{(hostname, aliaslist, ipaddrlist)
} where
125 \code{hostname
} is the primary host name responding to the given
126 \var{ip_address
},
\code{aliaslist
} is a (possibly empty) list of
127 alternative host names for the same address, and
\code{ipaddrlist
} is
128 a list of IP addresses for the same interface on the same
129 host (often but not always a single address).
132 \begin{funcdesc
}{gethostname
}{}
133 Return a string containing the hostname of the machine where
134 the Python interpreter is currently executing. If you want to know the
135 current machine's IP address, use
\code{gethostbyname(gethostname())
}.
136 Note:
\function{gethostname()
} doesn't always return the fully qualified
137 domain name; use
\code{gethostbyaddr(gethostname())
}
141 \begin{funcdesc
}{gethostbyaddr
}{ip_address
}
142 Return a triple
\code{(
\var{hostname
},
\var{aliaslist
},
143 \var{ipaddrlist
})
} where
\var{hostname
} is the primary host name
144 responding to the given
\var{ip_address
},
\var{aliaslist
} is a
145 (possibly empty) list of alternative host names for the same address,
146 and
\var{ipaddrlist
} is a list of IP addresses for the same interface
147 on the same host (most likely containing only a single address).
148 To find the fully qualified domain name, use the function
149 \function{getfqdn()
}.
152 \begin{funcdesc
}{getprotobyname
}{protocolname
}
153 Translate an Internet protocol name (e.g.\
\code{'icmp'
}) to a constant
154 suitable for passing as the (optional) third argument to the
155 \function{socket()
} function. This is usually only needed for sockets
156 opened in ``raw'' mode (
\constant{SOCK_RAW
}); for the normal socket
157 modes, the correct protocol is chosen automatically if the protocol is
161 \begin{funcdesc
}{getservbyname
}{servicename, protocolname
}
162 Translate an Internet service name and protocol name to a port number
163 for that service. The protocol name should be
\code{'tcp'
} or
167 \begin{funcdesc
}{socket
}{family, type
\optional{, proto
}}
168 Create a new socket using the given address family, socket type and
169 protocol number. The address family should be
\constant{AF_INET
} or
170 \constant{AF_UNIX
}. The socket type should be
\constant{SOCK_STREAM
},
171 \constant{SOCK_DGRAM
} or perhaps one of the other
\samp{SOCK_
} constants.
172 The protocol number is usually zero and may be omitted in that case.
175 \begin{funcdesc
}{fromfd
}{fd, family, type
\optional{, proto
}}
176 Build a socket object from an existing file descriptor (an integer as
177 returned by a file object's
\method{fileno()
} method). Address family,
178 socket type and protocol number are as for the
\function{socket()
} function
179 above. The file descriptor should refer to a socket, but this is not
180 checked --- subsequent operations on the object may fail if the file
181 descriptor is invalid. This function is rarely needed, but can be
182 used to get or set socket options on a socket passed to a program as
183 standard input or output (e.g.\ a server started by the
\UNIX{} inet
187 \begin{funcdesc
}{ntohl
}{x
}
188 Convert
32-bit integers from network to host byte order. On machines
189 where the host byte order is the same as network byte order, this is a
190 no-op; otherwise, it performs a
4-byte swap operation.
193 \begin{funcdesc
}{ntohs
}{x
}
194 Convert
16-bit integers from network to host byte order. On machines
195 where the host byte order is the same as network byte order, this is a
196 no-op; otherwise, it performs a
2-byte swap operation.
199 \begin{funcdesc
}{htonl
}{x
}
200 Convert
32-bit integers from host to network byte order. On machines
201 where the host byte order is the same as network byte order, this is a
202 no-op; otherwise, it performs a
4-byte swap operation.
205 \begin{funcdesc
}{htons
}{x
}
206 Convert
16-bit integers from host to network byte order. On machines
207 where the host byte order is the same as network byte order, this is a
208 no-op; otherwise, it performs a
2-byte swap operation.
211 \begin{funcdesc
}{inet_aton
}{ip_string
}
212 Convert an IP address from dotted-quad string format
213 (e.g.\ '
123.45.67.89') to
32-bit packed binary format, as a string four
214 characters in length.
216 Useful when conversing with a program that uses the standard C library
217 and needs objects of type
\ctype{struct in_addr
}, which is the C type
218 for the
32-bit packed binary this function returns.
220 If the IP address string passed to this function is invalid,
221 \exception{socket.error
} will be raised. Note that exactly what is
222 valid depends on the underlying C implementation of
223 \cfunction{inet_aton()
}.
226 \begin{funcdesc
}{inet_ntoa
}{packed_ip
}
227 Convert a
32-bit packed IP address (a string four characters in
228 length) to its standard dotted-quad string representation
229 (e.g. '
123.45.67.89').
231 Useful when conversing with a program that uses the standard C library
232 and needs objects of type
\ctype{struct in_addr
}, which is the C type
233 for the
32-bit packed binary this function takes as an argument.
235 If the string passed to this function is not exactly
4 bytes in
236 length,
\exception{socket.error
} will be raised.
239 \begin{datadesc
}{SocketType
}
240 This is a Python type object that represents the socket object type.
241 It is the same as
\code{type(socket(...))
}.
246 \seemodule{SocketServer
}{Classes that simplify writing network servers.
}
250 \subsection{Socket Objects
\label{socket-objects
}}
252 Socket objects have the following methods. Except for
253 \method{makefile()
} these correspond to
\UNIX{} system calls
254 applicable to sockets.
256 \begin{methoddesc
}[socket
]{accept
}{}
258 The socket must be bound to an address and listening for connections.
259 The return value is a pair
\code{(
\var{conn
},
\var{address
})
}
260 where
\var{conn
} is a
\emph{new
} socket object usable to send and
261 receive data on the connection, and
\var{address
} is the address bound
262 to the socket on the other end of the connection.
265 \begin{methoddesc
}[socket
]{bind
}{address
}
266 Bind the socket to
\var{address
}. The socket must not already be bound.
267 (The format of
\var{address
} depends on the address family --- see
268 above.)
\strong{Note:
} This method has historically accepted a pair
269 of parameters for
\constant{AF_INET
} addresses instead of only a
270 tuple. This was never intentional and is no longer be available in
274 \begin{methoddesc
}[socket
]{close
}{}
275 Close the socket. All future operations on the socket object will fail.
276 The remote end will receive no more data (after queued data is flushed).
277 Sockets are automatically closed when they are garbage-collected.
280 \begin{methoddesc
}[socket
]{connect
}{address
}
281 Connect to a remote socket at
\var{address
}.
282 (The format of
\var{address
} depends on the address family --- see
283 above.)
\strong{Note:
} This method has historically accepted a pair
284 of parameters for
\constant{AF_INET
} addresses instead of only a
285 tuple. This was never intentional and is no longer available in
286 Python
2.0 and later.
289 \begin{methoddesc
}[socket
]{connect_ex
}{address
}
290 Like
\code{connect(
\var{address
})
}, but return an error indicator
291 instead of raising an exception for errors returned by the C-level
292 \cfunction{connect()
} call (other problems, such as ``host not found,''
293 can still raise exceptions). The error indicator is
\code{0} if the
294 operation succeeded, otherwise the value of the
\cdata{errno
}
295 variable. This is useful, e.g., for asynchronous connects.
296 \strong{Note:
} This method has historically accepted a pair of
297 parameters for
\constant{AF_INET
} addresses instead of only a tuple.
298 This was never intentional and is no longer be available in Python
302 \begin{methoddesc
}[socket
]{fileno
}{}
303 Return the socket's file descriptor (a small integer). This is useful
304 with
\function{select.select()
}.
307 \begin{methoddesc
}[socket
]{getpeername
}{}
308 Return the remote address to which the socket is connected. This is
309 useful to find out the port number of a remote IP socket, for instance.
310 (The format of the address returned depends on the address family ---
311 see above.) On some systems this function is not supported.
314 \begin{methoddesc
}[socket
]{getsockname
}{}
315 Return the socket's own address. This is useful to find out the port
316 number of an IP socket, for instance.
317 (The format of the address returned depends on the address family ---
321 \begin{methoddesc
}[socket
]{getsockopt
}{level, optname
\optional{, buflen
}}
322 Return the value of the given socket option (see the
\UNIX{} man page
323 \manpage{getsockopt
}{2}). The needed symbolic constants
324 (
\constant{SO_*
} etc.) are defined in this module. If
\var{buflen
}
325 is absent, an integer option is assumed and its integer value
326 is returned by the function. If
\var{buflen
} is present, it specifies
327 the maximum length of the buffer used to receive the option in, and
328 this buffer is returned as a string. It is up to the caller to decode
329 the contents of the buffer (see the optional built-in module
330 \refmodule{struct
} for a way to decode C structures encoded as strings).
333 \begin{methoddesc
}[socket
]{listen
}{backlog
}
334 Listen for connections made to the socket. The
\var{backlog
} argument
335 specifies the maximum number of queued connections and should be at
336 least
1; the maximum value is system-dependent (usually
5).
339 \begin{methoddesc
}[socket
]{makefile
}{\optional{mode
\optional{, bufsize
}}}
340 Return a
\dfn{file object
} associated with the socket. (File objects
341 are described in
\ref{bltin-file-objects
}, ``File Objects.'')
342 The file object references a
\cfunction{dup()
}ped version of the
343 socket file descriptor, so the file object and socket object may be
344 closed or garbage-collected independently.
345 \index{I/O control!buffering
}The optional
\var{mode
}
346 and
\var{bufsize
} arguments are interpreted the same way as by the
347 built-in
\function{open()
} function.
350 \begin{methoddesc
}[socket
]{recv
}{bufsize
\optional{, flags
}}
351 Receive data from the socket. The return value is a string representing
352 the data received. The maximum amount of data to be received
353 at once is specified by
\var{bufsize
}. See the
\UNIX{} manual page
354 \manpage{recv
}{2} for the meaning of the optional argument
355 \var{flags
}; it defaults to zero.
358 \begin{methoddesc
}[socket
]{recvfrom
}{bufsize
\optional{, flags
}}
359 Receive data from the socket. The return value is a pair
360 \code{(
\var{string
},
\var{address
})
} where
\var{string
} is a string
361 representing the data received and
\var{address
} is the address of the
362 socket sending the data. The optional
\var{flags
} argument has the
363 same meaning as for
\method{recv()
} above.
364 (The format of
\var{address
} depends on the address family --- see above.)
367 \begin{methoddesc
}[socket
]{send
}{string
\optional{, flags
}}
368 Send data to the socket. The socket must be connected to a remote
369 socket. The optional
\var{flags
} argument has the same meaning as for
370 \method{recv()
} above. Returns the number of bytes sent.
373 \begin{methoddesc
}[socket
]{sendto
}{string
\optional{, flags
}, address
}
374 Send data to the socket. The socket should not be connected to a
375 remote socket, since the destination socket is specified by
376 \var{address
}. The optional
\var{flags
} argument has the same
377 meaning as for
\method{recv()
} above. Return the number of bytes sent.
378 (The format of
\var{address
} depends on the address family --- see above.)
381 \begin{methoddesc
}[socket
]{setblocking
}{flag
}
382 Set blocking or non-blocking mode of the socket: if
\var{flag
} is
0,
383 the socket is set to non-blocking, else to blocking mode. Initially
384 all sockets are in blocking mode. In non-blocking mode, if a
385 \method{recv()
} call doesn't find any data, or if a
386 \method{send()
} call can't immediately dispose of the data, a
387 \exception{error
} exception is raised; in blocking mode, the calls
388 block until they can proceed.
391 \begin{methoddesc
}[socket
]{setsockopt
}{level, optname, value
}
392 Set the value of the given socket option (see the
\UNIX{} manual page
393 \manpage{setsockopt
}{2}). The needed symbolic constants are defined in
394 the
\module{socket
} module (
\code{SO_*
} etc.). The value can be an
395 integer or a string representing a buffer. In the latter case it is
396 up to the caller to ensure that the string contains the proper bits
397 (see the optional built-in module
398 \refmodule{struct
}\refbimodindex{struct
} for a way to encode C
399 structures as strings).
402 \begin{methoddesc
}[socket
]{shutdown
}{how
}
403 Shut down one or both halves of the connection. If
\var{how
} is
404 \code{0}, further receives are disallowed. If
\var{how
} is
\code{1},
405 further sends are disallowed. If
\var{how
} is
\code{2}, further sends
406 and receives are disallowed.
409 Note that there are no methods
\method{read()
} or
\method{write()
};
410 use
\method{recv()
} and
\method{send()
} without
\var{flags
} argument
414 \subsection{Example
\label{socket-example
}}
416 Here are two minimal example programs using the TCP/IP protocol:\ a
417 server that echoes all data that it receives back (servicing only one
418 client), and a client using it. Note that a server must perform the
419 sequence
\function{socket()
},
\method{bind()
},
\method{listen()
},
420 \method{accept()
} (possibly repeating the
\method{accept()
} to service
421 more than one client), while a client only needs the sequence
422 \function{socket()
},
\method{connect()
}. Also note that the server
423 does not
\method{send()
}/
\method{recv()
} on the
424 socket it is listening on but on the new socket returned by
428 # Echo server program
431 HOST = '' # Symbolic name meaning the local host
432 PORT =
50007 # Arbitrary non-privileged port
433 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
436 conn, addr = s.accept()
437 print 'Connected by', addr
439 data = conn.recv(
1024)
446 # Echo client program
449 HOST = 'daring.cwi.nl' # The remote host
450 PORT =
50007 # The same port as used by the server
451 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
452 s.connect((HOST, PORT))
453 s.send('Hello, world')
456 print 'Received', `data`