Movatterモバイル変換


[0]ホーム

URL:


Previous PageUp One LevelNext PagePython Library ReferenceContentsModule IndexIndex
Previous:7.1.1 ExampleUp:7. Optional Operating SystemNext:7.2.1 Socket Objects

7.2socket -- Low-level networking interface

This module provides access to the BSDsocket interface.It is available on all modern Unix systems, Windows, MacOS, BeOS,OS/2, and probably additional platforms.

For an introduction to socket programming (in C), see the followingpapers:An Introductory 4.3BSD Interprocess CommunicationTutorial, by Stuart Sechrest andAn Advanced 4.3BSDInterprocess Communication Tutorial, by Samuel J. Leffler et al,both in theUnix Programmer's Manual, Supplementary Documents 1(sections PS1:7 and PS1:8). The platform-specific reference materialfor the various socket-related system calls are also a valuable sourceof information on the details of socket semantics. For Unix, referto the manual pages; for Windows, see the WinSock (or Winsock 2)specification.For IPv6-ready APIs, readers may want to refer toRFC 2553 titledBasic Socket Interface Extensions for IPv6.

The Python interface is a straightforward transliteration of theUnix system call and library interface for sockets to Python'sobject-oriented style: thesocket() function returns asocket object whose methods implement thevarious socket system calls. Parameter types are somewhathigher-level than in the C interface: as withread() andwrite() operations on Python files, buffer allocation onreceive operations is automatic, and buffer length is implicit on sendoperations.

Socket addresses are represented as follows:A single string is used for theAF_UNIX address family.A pair(host,port) is used for theAF_INET address family, wherehost is a stringrepresenting either a hostname in Internet domain notation like'daring.cwi.nl' or an IPv4 address like'100.50.200.5',andport is an integral port number.ForAF_INET6 address family, a four-tuple(host,port,flowinfo,scopeid) isused, whereflowinfo andscopeid representssin6_flowinfo andsin6_scope_id member instruct sockaddr_in6 in C.Forsocket module methods,flowinfo andscopeidcan be omitted just for backward compatibility. Note, however,omission ofscopeid can cause problems in manipulating scopedIPv6 addresses. Other address families are currently not supported.The address format required by a particular socket object isautomatically selected based on the address family specified when thesocket object was created.

For IPv4 addresses, two special forms are accepted instead of a hostaddress: the empty string representsINADDR_ANY, and the string'<broadcast>' representsINADDR_BROADCAST.The behavior is not available for IPv6 for backward compatibility,therefore, you may want to avoid these if you intend to support IPv6 withyour Python programs.

If you use a hostname in thehost portion of IPv4/v6 socketaddress, the program may show a nondeterministic behavior, as Pythonuses the first address returned from the DNS resolution. The socketaddress will be resolved differently into an actual IPv4/v6 address,depending on the results from DNS resolution and/or the hostconfiguration. For deterministic behavior use a numeric address inhost portion.

All errors raise exceptions. The normal exceptions for invalidargument types and out-of-memory conditions can be raised; errorsrelated to socket or address semantics raise the errorsocket.error.

Non-blocking mode is supported through thesetblocking() method.

The modulesocket exports the following constants and functions:

exceptionerror
This exception is raised for socket-related errors.The accompanying value is either a string telling what went wrong or apair(errno,string)representing an error returned by a systemcall, similar to the value accompanyingos.error.See the moduleerrno , which containsnames for the error codes defined by the underlying operating system.

exceptionherror
This exception is raised for address-related errors, i.e. forfunctions that useh_errno in the C API, includinggethostbyname_ex() andgethostbyaddr().

The accompanying value is a pair(h_errno,string)representing an error returned by a library call.stringrepresents the description ofh_errno, as returned bythehstrerror() C function.

exceptiongaierror
This exception is raised for address-related errors, forgetaddrinfo() andgetnameinfo().The accompanying value is a pair(error,string)representing an error returned by a library call.string represents the description oferror, as returnedby thegai_strerror() C function.

AF_UNIX
AF_INET
AF_INET6
These constants represent the address (and protocol) families,used for the first argument tosocket(). If theAF_UNIX constant is not defined then this protocol isunsupported.

SOCK_STREAM
SOCK_DGRAM
SOCK_RAW
SOCK_RDM
SOCK_SEQPACKET
These constants represent the socket types,used for the second argument tosocket().(OnlySOCK_STREAM andSOCK_DGRAM appear to be generally useful.)

SO_*
SOMAXCONN
MSG_*
SOL_*
IPPROTO_*
IPPORT_*
INADDR_*
IP_*
IPV6_*
EAI_*
AI_*
NI_*
TCP_*
Many constants of these forms, documented in the Unix documentation onsockets and/or the IP protocol, are also defined in the socket module.They are generally used in arguments to thesetsockopt() andgetsockopt() methods of socket objects. In most cases, onlythose symbols that are defined in the Unix header files are defined;for a few symbols, default values are provided.

getaddrinfo(host, port[, family, socktype, proto, flags])

Resolves thehost/port argument, into a sequence of5-tuples that contain all the necessary argument for the socketsmanipulation.host is a domain name, a string representation ofIPv4/v6 address orNone.port is a string service name (like``http''), a numericport number orNone.

The rest of the arguments are optional and must be numeric ifspecified. Forhost andport, by passing either an emptystring orNone, you can passNULL to the C API. Thegetaddrinfo() function returns a list of 5-tuples withthe following structure:

(family,socktype,proto,canonname,sockaddr).

family,socktype,proto are all integer and are meant tobe passed to thesocket() function.canonname is a string representing the canonical name of thehost.It can be a numeric IPv4/v6 address whenAI_CANONNAME is specifiedfor a numerichost.sockaddr is a tuple describing a socket address, as described above.SeeLib/httplib.py and other library filesfor a typical usage of the function.New in version 2.2.

getfqdn([name])
Return a fully qualified domain name forname.Ifname is omitted or empty, it is interpreted as the localhost. To find the fully qualified name, the hostname returned bygethostbyaddr() is checked, then aliases for the host, ifavailable. The first name which includes a period is selected. Incase no fully qualified domain name is available, the hostname isreturned.New in version 2.0.

gethostbyname(hostname)
Translate a host name to IPv4 address format. The IPv4 address isreturned as a string, such as'100.50.200.5'. If the host nameis an IPv4 address itself it is returned unchanged. Seegethostbyname_ex() for a more complete interface.gethostbyname() does not support IPv6 name resolution, andgetaddrinfo() should be used instead for IPv4/v6 dual stack support.

gethostbyname_ex(hostname)
Translate a host name to IPv4 address format, extended interface.Return a triple(hostname, aliaslist, ipaddrlist) wherehostname is the primary host name responding to the givenip_address,aliaslist is a (possibly empty) list ofalternative host names for the same address, andipaddrlist isa list of IPv4 addresses for the same interface on the samehost (often but not always a single address).gethostbyname_ex() does not support IPv6 name resolution, andgetaddrinfo() should be used instead for IPv4/v6 dual stack support.

gethostname()
Return a string containing the hostname of the machine where the Python interpreter is currently executing.If you want to know the current machine's IP address, you may want to usegethostbyname(gethostname()).This operation assumes that there is a valid address-to-host mapping forthe host, and the assumption does not always hold.Note:gethostname() doesn't always return the fully qualifieddomain name; usegethostbyaddr(gethostname())(see below).

gethostbyaddr(ip_address)
Return a triple(hostname,aliaslist,ipaddrlist) wherehostname is the primary host nameresponding to the givenip_address,aliaslist is a(possibly empty) list of alternative host names for the same address,andipaddrlist is a list of IPv4/v6 addresses for the same interfaceon the same host (most likely containing only a single address).To find the fully qualified domain name, use the functiongetfqdn().gethostbyaddr supports both IPv4 and IPv6.

getnameinfo(sockaddr, flags)
Translate a socket addresssockaddr into a 2-tuple(host,port).Depending on the settings offlags, the result can contain afully-qualified domain name or numeric address representation inhost. Similarly,port can contain a string port name or anumeric port number.New in version 2.2.

getprotobyname(protocolname)
Translate an Internet protocol name (for example,'icmp') to a constantsuitable for passing as the (optional) third argument to thesocket() function. This is usually only needed for socketsopened in ``raw'' mode (SOCK_RAW); for the normal socketmodes, the correct protocol is chosen automatically if the protocol isomitted or zero.

getservbyname(servicename, protocolname)
Translate an Internet service name and protocol name to a port numberfor that service. The protocol name should be'tcp' or'udp'.

socket(family, type[, proto])
Create a new socket using the given address family, socket type andprotocol number. The address family should beAF_INET,AF_INET6 orAF_UNIX. The socket type should beSOCK_STREAM,SOCK_DGRAM or perhaps one of the other "SOCK_" constants.The protocol number is usually zero and may be omitted in that case.

ssl(sock[, keyfile, certfile])
Initiate a SSL connection over the socketsock.keyfile isthe name of a PEM formatted file that contains your privatekey.certfile is a PEM formatted certificate chain file. Onsuccess, a newSSLObject is returned.

Warning:This does not do any certificate verification!

fromfd(fd, family, type[, proto])
Build a socket object from an existing file descriptor (an integer asreturned by a file object'sfileno() method). Address family,socket type and protocol number are as for thesocket() functionabove. The file descriptor should refer to a socket, but this is notchecked -- subsequent operations on the object may fail if the filedescriptor is invalid. This function is rarely needed, but can beused to get or set socket options on a socket passed to a program asstandard input or output (such as a server started by the Unix inetdaemon).Availability: Unix.

ntohl(x)
Convert 32-bit integers from network to host byte order. On machineswhere the host byte order is the same as network byte order, this is ano-op; otherwise, it performs a 4-byte swap operation.

ntohs(x)
Convert 16-bit integers from network to host byte order. On machineswhere the host byte order is the same as network byte order, this is ano-op; otherwise, it performs a 2-byte swap operation.

htonl(x)
Convert 32-bit integers from host to network byte order. On machineswhere the host byte order is the same as network byte order, this is ano-op; otherwise, it performs a 4-byte swap operation.

htons(x)
Convert 16-bit integers from host to network byte order. On machineswhere the host byte order is the same as network byte order, this is ano-op; otherwise, it performs a 2-byte swap operation.

inet_aton(ip_string)
Convert an IPv4 address from dotted-quad string format (for example,'123.45.67.89') to 32-bit packed binary format, as a string fourcharacters in length.

Useful when conversing with a program that uses the standard C libraryand needs objects of typestruct in_addr, which is the C typefor the 32-bit packed binary this function returns.

If the IPv4 address string passed to this function is invalid,socket.error will be raised. Note that exactly what isvalid depends on the underlying C implementation ofinet_aton().

inet_aton() does not support IPv6, andgetnameinfo() should be used instead for IPv4/v6 dual stacksupport.

inet_ntoa(packed_ip)
Convert a 32-bit packed IPv4 address (a string four characters inlength) to its standard dotted-quad string representation(for example, '123.45.67.89').

Useful when conversing with a program that uses the standard C libraryand needs objects of typestruct in_addr, which is the C typefor the 32-bit packed binary this function takes as an argument.

If the string passed to this function is not exactly 4 bytes inlength,socket.error will be raised.

inet_ntoa() does not support IPv6, andgetnameinfo() should be used instead for IPv4/v6 dual stacksupport.

SocketType
This is a Python type object that represents the socket object type.It is the same astype(socket(...)).

See Also:

ModuleSocketServer:
Classes that simplify writing network servers.


Subsections


Previous PageUp One LevelNext PagePython Library ReferenceContentsModule IndexIndex
Previous:7.1.1 ExampleUp:7. Optional Operating SystemNext:7.2.1 Socket Objects
Release 2.2.3, documentation updated on 30 May 2003.
SeeAbout this document... for information on suggesting changes.
[8]ページ先頭

©2009-2026 Movatter.jp