Vous êtes sur la page 1sur 18

1 17.2. socket - Io-IeveI netorkIng InterIace - Iython v2.7.

2 documentatIon
12/28/2011 08.14.23 AM http.//docs.python.org/IIbrary/socket.htmI
17.2. socke1 - Lowlevel neworkIng Inerface
Ths modue provdes ccess to the BSD socket nterfce. It s vbe on modern Unx
systems, Wndows, Mc OS X, BeOS, OS/2, nd probby ddton ptforms.
Note: Some behvor my be ptform dependent, snce cs re mde to the
opertng system socket APIs.
For n ntroducton to socket progrmmng (n C), see the foowng ppers: An
Introductory 4.3BSD Interprocess Communcton Tutor, by Sturt Sechrest nd An
Advnced 4.3BSD Interprocess Communcton Tutor, by Smue |. Leffer et , both n
the UNIX Progrmmers Mnu, Suppementry Documents 1 (sectons PS1:7 nd PS1:8).
The ptform-specfc reference mter for the vrous socket-reted system cs re so
vube source of nformton on the dets of socket semntcs. For Unx, refer to the
mnu pges; for Wndows, see the WnSock (or Wnsock 2) specfcton. For IPv6-redy
APIs, reders my wnt to refer to RFC 3493 tted Bsc Socket Interfce Extensons for
IPv6.
The Python nterfce s strghtforwrd trnsterton of the Unx system c nd brry
nterfce for sockets to Pythons ob|ect-orented stye: the socke1{) functon returns
socket object whose methods mpement the vrous socket system cs. Prmeter types
re somewht hgher-eve thn n the C nterfce: s wth read{) nd Wr1e{)
opertons on Python fes, buffer octon on receve opertons s utomtc, nd buffer
ength s mpct on send opertons.
Socket ddresses re represented s foows: A snge strng s used for the F_uNIX
ddress fmy. A pr {hos1, poJ1) s used for the F_INET ddress fmy, where host s
strng representng ether hostnme n Internet domn notton ke `daJ1g.cw1.`
or n IPv4 ddress ke `100.50.200.5`, nd port s n ntegr port number. For F_
INET6 ddress fmy, four-tupe {hos1, poJ1, 1ow11o, scope1d) s used, where
floinfo nd scopeid represents s16_1ow11o nd s16_scope_1d member n s1ruc1
sockaddr_n6 n C. For socke1 modue methods, floinfo nd scopeid cn be omtted |ust
for bckwrd comptbty. Note, however, omsson of scopeid cn cuse probems n
mnputng scoped IPv6 ddresses. Other ddress fmes re currenty not supported.
The ddress formt requred by prtcur socket ob|ect s utomtcy seected bsed
on the ddress fmy specfed when the socket ob|ect ws creted.
For IPv4 ddresses, two spec forms re ccepted nsted of host ddress: the empty
strng represents IN_NY, nd the strng `<bJoadcas1>` represents IN_
C5T. The behvor s not vbe for IPv6 for bckwrd comptbty, therefore,
you my wnt to vod these f you ntend to support IPv6 wth your Python progrms.
If you use hostnme n the host porton of IPv4/v6 socket ddress, the progrm my
show nondetermnstc behvor, s Python uses the frst ddress returned from the DNS
2 17.2. socket - Io-IeveI netorkIng InterIace - Iython v2.7.2 documentatIon
12/28/2011 08.14.23 AM http.//docs.python.org/IIbrary/socket.htmI
resouton. The socket ddress w be resoved dfferenty nto n ctu IPv4/v6 ddress,
dependng on the resuts from DNS resouton nd/or the host confgurton. For
determnstc behvor use numerc ddress n host porton.
Ne in version 2.5: AF_NETLINK sockets re represented s prs p1d, gJoups.
Ne in version 2.6: Lnux-ony support for TIPC s so vbe usng the F_TIPC
ddress fmy. TIPC s n open, non-IP bsed networked protoco desgned for use n
custered computer envronments. Addresses re represented by tupe, nd the feds
depend on the ddress type. The gener tupe form s {addJ_1ype, v1, v2, v3 |,
scope]), where:
addr_type s one of TIPC_ADDR_NAMESEO, TIPC_ADDR_NAME, or TIPC_ADDR_ID.
scope s one of TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, nd TIPC_NODE_SCOPE.
If addr_type s TIPC_ADDR_NAME, then vJ s the server type, v2 s the port dentfer,
nd v3 shoud be 0.
If addr_type s TIPC_ADDR_NAMESEO, then vJ s the server type, v2 s the ower port
number, nd v3 s the upper port number.
If addr_type s TIPC_ADDR_ID, then vJ s the node, v2 s the reference, nd v3
shoud be set to 0.
A errors rse exceptons. The norm exceptons for nvd rgument types nd out-of-
memory condtons cn be rsed; errors reted to socket or ddress semntcs rse the
error socke1.error.
Non-bockng mode s supported through se1b1ockng{). A generzton of ths bsed
on tmeouts s supported through se11meou1{).
The modue socke1 exports the foowng constnts nd functons:
exception socke1.error
Ths excepton s rsed for socket-reted errors. The ccompnyng vue s ether
strng teng wht went wrong or pr {eJJo, s1J1g) representng n error
returned by system c, smr to the vue ccompnyng os.error. See the
modue errno, whch contns nmes for the error codes defned by the underyng
opertng system.
Changed in version 2.6: socke1.error s now chd css of IError.
exception socke1.herror
Ths excepton s rsed for ddress-reted errors, .e. for functons tht use h_errno n
the C API, ncudng ge1hos1byname_ex{) nd ge1hos1byaddr{).
3 17.2. socket - Io-IeveI netorkIng InterIace - Iython v2.7.2 documentatIon
12/28/2011 08.14.23 AM http.//docs.python.org/IIbrary/socket.htmI
The ccompnyng vue s pr {h_eJJo, s1J1g) representng n error returned
by brry c. string represents the descrpton of h_errno, s returned by the
hs1rerror{) C functon.
exception socke1.gaerror
Ths excepton s rsed for ddress-reted errors, for ge1addrn1o{) nd
ge1namen1o{). The ccompnyng vue s pr {eJJoJ, s1J1g) representng n
error returned by brry c. string represents the descrpton of error, s returned
by the ga_s1rerror{) C functon. The error vue w mtch one of the EI_*
constnts defned n ths modue.
exception socke1.1meou1
Ths excepton s rsed when tmeout occurs on socket whch hs hd tmeouts
enbed v pror c to se11meou1{). The ccompnyng vue s strng whose
vue s currenty wys "tmed out".
Ne in version 2.3.
socke1.F_uNIX
socke1.F_INET
socke1.F_INET6
These constnts represent the ddress (nd protoco) fmes, used for the frst
rgument to socke1{). If the F_uNIX constnt s not defned then ths protoco s
unsupported.
socke1.5CK_5TEN
socke1.5CK_CN
socke1.5CK_W
socke1.5CK_N
socke1.5CK_5E0PCKET
These constnts represent the socket types, used for the second rgument to socke1
{). (Ony 5CK_5TEN nd 5CK_CN pper to be genery usefu.)
5_*
socke1.5NXCNN
N5C_*
5L_*
IPPT_*
IPPT_*
IN_*
IP_*
IPv6_*
4 17.2. socket - Io-IeveI netorkIng InterIace - Iython v2.7.2 documentatIon
12/28/2011 08.14.23 AM http.//docs.python.org/IIbrary/socket.htmI
EI_*
I_*
NI_*
TCP_*
Mny constnts of these forms, documented n the Unx documentton on sockets
nd/or the IP protoco, re so defned n the socket modue. They re genery used
n rguments to the se1sockop1{) nd ge1sockop1{) methods of socket ob|ects. In
most cses, ony those symbos tht re defned n the Unx heder fes re defned;
for few symbos, defut vues re provded.
5I_*
CvLL_*
Constnts for Wndows WSAIoct(). The constnts re used s rguments to the
oc11{) method of socket ob|ects.
Ne in version 2.6.
TIPC_*
TIPC reted constnts, mtchng the ones exported by the C socket API. See the TIPC
documentton for more nformton.
Ne in version 2.6.
socke1.has_pv6
Ths constnt contns booen vue whch ndctes f IPv6 s supported on ths
ptform.
Ne in version 2.3.
socke1.crea1e_connec1on(address|, timeout|, source_address||)
Convenence functon. Connect to address ( 2-tupe {hos1, poJ1)), nd return the
socket ob|ect. Pssng the opton timeout prmeter w set the tmeout on the
socket nstnce before ttemptng to connect. If no timeout s supped, the gob
defut tmeout settng returned by ge1de1au111meou1{) s used.
If supped, source_address must be 2-tupe {hos1, poJ1) for the socket to bnd to
s ts source ddress before connectng. If host or port re or 0 respectvey the OS
defut behvor w be used.
Ne in version 2.6.
Changed in version 2.7: source_address ws dded.
socke1.ge1addrn1o(host, port, family=0, socktype=0, proto=0, flags=0)
5 17.2. socket - Io-IeveI netorkIng InterIace - Iython v2.7.2 documentatIon
12/28/2011 08.14.23 AM http.//docs.python.org/IIbrary/socket.htmI
Trnste the host/port rgument nto sequence of 5-tupes tht contn the
necessry rguments for cretng socket connected to tht servce. host s domn
nme, strng representton of n IPv4/v6 ddress or None. port s strng servce
nme such s `h11p`, numerc port number or None. By pssng None s the vue
of host nd port, you cn pss hbLL to the underyng C API.
The family, socktype nd proto rguments cn be optony specfed n order to
nrrow the st of ddresses returned. Pssng zero s vue for ech of these
rguments seects the fu rnge of resuts. The flags rgument cn be one or sever
of the AT_* constnts, nd w nfuence how resuts re computed nd returned. For
exmpe, I_NuNEICh5T w dsbe domn nme resouton nd w rse n error
f host s domn nme.
The functon returns st of 5-tupes wth the foowng structure:
{1am1y, sock1ype, pJo1o, caoame, sockaddJ)
In these tupes, family, socktype, proto re ntegers nd re ment to be pssed to
the socke1{) functon. canonname w be strng representng the cnonc nme of
the host f I_CNNNNE s prt of the flags rgument; ese canonname w be empty.
sockaddr s tupe descrbng socket ddress, whose formt depends on the
returned family ( {addJess, poJ1) 2-tupe for F_INET, {addJess, poJ1, 1ow
11o, scope 1d) 4-tupe for F_INET6), nd s ment to be pssed to the
socke1.connec1{) method.
The foowng exmpe fetches ddress nformton for hypothetc TCP connecton
to www.py1ho.oJg on port 80 (resuts my dffer on your system f IPv6 snt enbed)
:
Ne in version 2.2.
socke1.ge11qdn(|name|)
Return fuy qufed domn nme for name. If name s omtted or empty, t s
nterpreted s the oc host. To fnd the fuy qufed nme, the hostnme returned
by ge1hos1byaddr{) s checked, foowed by ses for the host, f vbe. The frst
nme whch ncudes perod s seected. In cse no fuy qufed domn nme s
vbe, the hostnme s returned by ge1hos1name{) s returned.
Ne in version 2.0.
socke1.ge1hos1byname(hostname)
>>> socke1.ge1addJ11o{"www.py1ho.oJg", 80, 0, 0, socke1.S0L_TCP)
|{2, 1, 6, ``, {`82.94.164.162`, 80)),
{10, 1, 6, ``, {`2001.888.2000.d..a2`, 80, 0, 0))]
>>>
6 17.2. socket - Io-IeveI netorkIng InterIace - Iython v2.7.2 documentatIon
12/28/2011 08.14.23 AM http.//docs.python.org/IIbrary/socket.htmI
Trnste host nme to IPv4 ddress formt. The IPv4 ddress s returned s
strng, such s `100.50.200.5`. If the host nme s n IPv4 ddress tsef t s
returned unchnged. See ge1hos1byname_ex{) for more compete nterfce.
ge1hos1byname{) does not support IPv6 nme resouton, nd ge1addrn1o{) shoud
be used nsted for IPv4/v6 du stck support.
socke1.ge1hos1byname_ex(hostname)
Trnste host nme to IPv4 ddress formt, extended nterfce. Return trpe
{hos1ame, a1as1s1, 1paddJ1s1) where hostname s the prmry host nme
respondng to the gven ip_address, aliaslist s (possby empty) st of terntve
host nmes for the sme ddress, nd ipaddrlist s st of IPv4 ddresses for the
sme nterfce on the sme host (often but not wys snge ddress).
ge1hos1byname_ex{) does not support IPv6 nme resouton, nd ge1addrn1o{)
shoud be used nsted for IPv4/v6 du stck support.
socke1.ge1hos1name()
Return strng contnng the hostnme of the mchne where the Python nterpreter
s currenty executng.
If you wnt to know the current mchnes IP ddress, you my wnt to use
ge1hos1byame{ge1hos1ame{)). Ths operton ssumes tht there s vd
ddress-to-host mppng for the host, nd the ssumpton does not wys hod.
Note: ge1hos1name{) doesnt wys return the fuy qufed domn nme; use
ge11qd{) (see bove).
socke1.ge1hos1byaddr(ip_address)
Return trpe {hos1ame, a1as1s1, 1paddJ1s1) where hostname s the prmry
host nme respondng to the gven ip_address, aliaslist s (possby empty) st of
terntve host nmes for the sme ddress, nd ipaddrlist s st of IPv4/v6
ddresses for the sme nterfce on the sme host (most key contnng ony
snge ddress). To fnd the fuy qufed domn nme, use the functon ge11qdn{).
ge1hos1byaddr{) supports both IPv4 nd IPv6.
socke1.ge1namen1o(sockaddr, flags)
Trnste socket ddress sockaddr nto 2-tupe {hos1, poJ1). Dependng on the
settngs of flags, the resut cn contn fuy-qufed domn nme or numerc
ddress representton n host. Smry, port cn contn strng port nme or
numerc port number.
Ne in version 2.2.
socke1.ge1pro1obyname(protocolname)
Trnste n Internet protoco nme (for exmpe, `1cmp`) to constnt sutbe for
pssng s the (opton) thrd rgument to the socke1{) functon. Ths s usuy ony
7 17.2. socket - Io-IeveI netorkIng InterIace - Iython v2.7.2 documentatIon
12/28/2011 08.14.23 AM http.//docs.python.org/IIbrary/socket.htmI
needed for sockets opened n "rw" mode (5CK_W); for the norm socket modes,
the correct protoco s chosen utomtcy f the protoco s omtted or zero.
socke1.ge1servbyname(servicename|, protocolname|)
Trnste n Internet servce nme nd protoco nme to port number for tht
servce. The opton protoco nme, f gven, shoud be `1cp` or `udp`, otherwse
ny protoco w mtch.
socke1.ge1servbypor1(port|, protocolname|)
Trnste n Internet port number nd protoco nme to servce nme for tht
servce. The opton protoco nme, f gven, shoud be `1cp` or `udp`, otherwse
ny protoco w mtch.
socke1.socke1(|family|, type|, proto|||)
Crete new socket usng the gven ddress fmy, socket type nd protoco
number. The ddress fmy shoud be F_INET (the defut), F_INET6 or F_uNIX.
The socket type shoud be 5CK_5TEN (the defut), 5CK_CN or perhps one of
the other S0CK_ constnts. The protoco number s usuy zero nd my be omtted n
tht cse.
socke1.socke1par(|family|, type|, proto|||)
Bud pr of connected socket ob|ects usng the gven ddress fmy, socket type,
nd protoco number. Address fmy, socket type, nd protoco number re s for the
socke1{) functon bove. The defut fmy s F_uNIX f defned on the ptform;
otherwse, the defut s F_INET. Avbty: Unx.
Ne in version 2.4.
socke1.1rom1d(fd, family, type|, proto|)
Dupcte the fe descrptor fd (n nteger s returned by fe ob|ects 11eno{)
method) nd bud socket ob|ect from the resut. Address fmy, socket type nd
protoco number re s for the socke1{) functon bove. The fe descrptor shoud
refer to socket, but ths s not checked - subsequent opertons on the ob|ect my
f f the fe descrptor s nvd. Ths functon s rrey needed, but cn be used to
get or set socket optons on socket pssed to progrm s stndrd nput or output
(such s server strted by the Unx net demon). The socket s ssumed to be n
bockng mode. Avbty: Unx.
socke1.n1oh1(x)
Convert 32-bt postve ntegers from network to host byte order. On mchnes where
the host byte order s the sme s network byte order, ths s no-op; otherwse, t
performs 4-byte swp operton.
socke1.n1ohs(x)
8 17.2. socket - Io-IeveI netorkIng InterIace - Iython v2.7.2 documentatIon
12/28/2011 08.14.23 AM http.//docs.python.org/IIbrary/socket.htmI
Convert 16-bt postve ntegers from network to host byte order. On mchnes where
the host byte order s the sme s network byte order, ths s no-op; otherwse, t
performs 2-byte swp operton.
socke1.h1on1(x)
Convert 32-bt postve ntegers from host to network byte order. On mchnes where
the host byte order s the sme s network byte order, ths s no-op; otherwse, t
performs 4-byte swp operton.
socke1.h1ons(x)
Convert 16-bt postve ntegers from host to network byte order. On mchnes where
the host byte order s the sme s network byte order, ths s no-op; otherwse, t
performs 2-byte swp operton.
socke1.ne1_a1on(ip_string)
Convert n IPv4 ddress from dotted-qud strng formt (for exmpe, 123.45.67.89)
to 32-bt pcked bnry formt, s strng four chrcters n ength. Ths s usefu
when conversng wth progrm tht uses the stndrd C brry nd needs ob|ects
of type s1ruc1 n_addr, whch s the C type for the 32-bt pcked bnry ths functon
returns.
ne1_a1on{) so ccepts strngs wth ess thn three dots; see the Unx mnu pge
inet(3) for dets.
If the IPv4 ddress strng pssed to ths functon s nvd, socke1.error w be
rsed. Note tht excty wht s vd depends on the underyng C mpementton of
ne1_a1on{).
ne1_a1on{) does not support IPv6, nd ne1_p1on{) shoud be used nsted for
IPv4/v6 du stck support.
socke1.ne1_n1oa(packed_ip)
Convert 32-bt pcked IPv4 ddress ( strng four chrcters n ength) to ts
stndrd dotted-qud strng representton (for exmpe, 123.45.67.89). Ths s
usefu when conversng wth progrm tht uses the stndrd C brry nd needs
ob|ects of type s1ruc1 n_addr, whch s the C type for the 32-bt pcked bnry dt
ths functon tkes s n rgument.
If the strng pssed to ths functon s not excty 4 bytes n ength, socke1.error w
be rsed. ne1_n1oa{) does not support IPv6, nd ne1_n1op{) shoud be used
nsted for IPv4/v6 du stck support.
socke1.ne1_p1on(address_family, ip_string)
9 17.2. socket - Io-IeveI netorkIng InterIace - Iython v2.7.2 documentatIon
12/28/2011 08.14.23 AM http.//docs.python.org/IIbrary/socket.htmI
Convert n IP ddress from ts fmy-specfc strng formt to pcked, bnry formt.
ne1_p1on{) s usefu when brry or network protoco cs for n ob|ect of type
s1ruc1 n_addr (smr to ne1_a1on{)) or s1ruc1 n6_addr.
Supported vues for address_family re currenty F_INET nd F_INET6. If the IP
ddress strng ip_string s nvd, socke1.error w be rsed. Note tht excty wht
s vd depends on both the vue of address_family nd the underyng
mpementton of ne1_p1on{).
Avbty: Unx (mybe not ptforms).
Ne in version 2.3.
socke1.ne1_n1op(address_family, packed_ip)
Convert pcked IP ddress ( strng of some number of chrcters) to ts stndrd,
fmy-specfc strng representton (for exmpe, `7.10.0.5` or `5ae1.2b..8`)
ne1_n1op{) s usefu when brry or network protoco returns n ob|ect of type
s1ruc1 n_addr (smr to ne1_n1oa{)) or s1ruc1 n6_addr.
Supported vues for address_family re currenty F_INET nd F_INET6. If the strng
packed_ip s not the correct ength for the specfed ddress fmy, va1ueError w
be rsed. A socke1.error s rsed for errors from the c to ne1_n1op{).
Avbty: Unx (mybe not ptforms).
Ne in version 2.3.
socke1.ge1de1au111meou1()
Return the defut tmeout n seconds (fot) for new socket ob|ects. A vue of None
ndctes tht new socket ob|ects hve no tmeout. When the socket modue s frst
mported, the defut s None.
Ne in version 2.3.
socke1.se1de1au111meou1(timeout)
Set the defut tmeout n seconds (fot) for new socket ob|ects. A vue of None
ndctes tht new socket ob|ects hve no tmeout. When the socket modue s frst
mported, the defut s None.
Ne in version 2.3.
socke1.5ocke1Type
Ths s Python type ob|ect tht represents the socket ob|ect type. It s the sme s
1ype{socke1{...)).
10 17.2. socket - Io-IeveI netorkIng InterIace - Iython v2.7.2 documentatIon
12/28/2011 08.14.23 AM http.//docs.python.org/IIbrary/socket.htmI
See aso:
Modue 5ocke15erver
Csses tht smpfy wrtng network servers.
Modue ss1
A TLS/SSL wrpper for socket ob|ects.
17.2.1. Socke Dbjecs
Socket ob|ects hve the foowng methods. Except for make11e{) these correspond to
Unx system cs ppcbe to sockets.
socke1.accep1()
Accept connecton. The socket must be bound to n ddress nd stenng for
connectons. The return vue s pr {co, addJess) where conn s ne socket
ob|ect usbe to send nd receve dt on the connecton, nd address s the ddress
bound to the socket on the other end of the connecton.
socke1.bnd(address)
Bnd the socket to address. The socket must not redy be bound. (The formt of
address depends on the ddress fmy - see bove.)
Note: Ths method hs hstorcy ccepted pr of prmeters for F_INET
ddresses nsted of ony tupe. Ths ws never ntenton nd s no onger
vbe n Python 2.0 nd ter.
socke1.c1ose()
Cose the socket. A future opertons on the socket ob|ect w f. The remote end
w receve no more dt (fter queued dt s fushed). Sockets re utomtcy
cosed when they re grbge-coected.
Note: c1ose{) reeses the resource ssocted wth connecton but does not
necessry cose the connecton mmedtey. If you wnt to cose the connecton n
tmey fshon, c shu1doWn{) before c1ose{).
socke1.connec1(address)
Connect to remote socket t address. (The formt of address depends on the
ddress fmy - see bove.)
11 17.2. socket - Io-IeveI netorkIng InterIace - Iython v2.7.2 documentatIon
12/28/2011 08.14.23 AM http.//docs.python.org/IIbrary/socket.htmI
Note: Ths method hs hstorcy ccepted pr of prmeters for F_INET
ddresses nsted of ony tupe. Ths ws never ntenton nd s no onger
vbe n Python 2.0 nd ter.
socke1.connec1_ex(address)
Lke coec1{addJess), but return n error ndctor nsted of rsng n excepton
for errors returned by the C-eve connec1{) c (other probems, such s "host not
found," cn st rse exceptons). The error ndctor s 0 f the operton succeeded,
otherwse the vue of the errno vrbe. Ths s usefu to support, for exmpe,
synchronous connects.
Note: Ths method hs hstorcy ccepted pr of prmeters for F_INET
ddresses nsted of ony tupe. Ths ws never ntenton nd s no onger
vbe n Python 2.0 nd ter.
socke1.11eno()
Return the sockets fe descrptor ( sm nteger). Ths s usefu wth se1ec1.se1ec1
{).
Under Wndows the sm nteger returned by ths method cnnot be used where fe
descrptor cn be used (such s os.1dopen{)). Unx does not hve ths mtton.
socke1.ge1peername()
Return the remote ddress to whch the socket s connected. Ths s usefu to fnd out
the port number of remote IPv4/v6 socket, for nstnce. (The formt of the ddress
returned depends on the ddress fmy - see bove.) On some systems ths functon
s not supported.
socke1.ge1sockname()
Return the sockets own ddress. Ths s usefu to fnd out the port number of n IPv4/
v6 socket, for nstnce. (The formt of the ddress returned depends on the ddress
fmy - see bove.)
socke1.ge1sockop1(level, optname|, buflen|)
Return the vue of the gven socket opton (see the Unx mn pge getsockopt(2)).
The needed symboc constnts (5_* etc.) re defned n ths modue. If buflen s
bsent, n nteger opton s ssumed nd ts nteger vue s returned by the functon.
If buflen s present, t specfes the mxmum ength of the buffer used to receve the
opton n, nd ths buffer s returned s strng. It s up to the cer to decode the
contents of the buffer (see the opton but-n modue s1ruc1 for wy to decode C
structures encoded s strngs).
socke1.oc11(control, option)
12 17.2. socket - Io-IeveI netorkIng InterIace - Iython v2.7.2 documentatIon
12/28/2011 08.14.23 AM http.//docs.python.org/IIbrary/socket.htmI
Patform: Wndows
The oc11{) method s mted nterfce to the WSAIoct system nterfce. Pese
refer to the Wn32 documentton for more nformton.
On other ptforms, the generc 1cn11.1cn11{) nd 1cn11.oc11{) functons my be
used; they ccept socket ob|ect s ther frst rgument.
Ne in version 2.6.
socke1.1s1en(backlog)
Lsten for connectons mde to the socket. The backlog rgument specfes the
mxmum number of queued connectons nd shoud be t est 0; the mxmum
vue s system-dependent (usuy 5), the mnmum vue s forced to 0.
socke1.make11e(|mode|, bufsize||)
Return file object ssocted wth the socket. (Fe ob|ects re descrbed n File
Objects.) The fe ob|ect references dup{)ped verson of the socket fe descrptor, so
the fe ob|ect nd socket ob|ect my be cosed or grbge-coected ndependenty.
The socket must be n bockng mode (t cn not hve tmeout). The opton mode
nd bufsize rguments re nterpreted the sme wy s by the but-n 11e{)
functon.
Note: On Wndows, the fe-ke ob|ect creted by make11e{) cnnot be used
where fe ob|ect wth fe descrptor s expected, such s the strem rguments
of subprocess.Popen{).
socke1.recv(bufsize|, flags|)
Receve dt from the socket. The return vue s strng representng the dt
receved. The mxmum mount of dt to be receved t once s specfed by bufsize.
See the Unx mnu pge recv(2) for the menng of the opton rgument flags; t
defuts to zero.
Note: For best mtch wth hrdwre nd network retes, the vue of bufsize
shoud be retvey sm power of 2, for exmpe, 4096.
socke1.recv1rom(bufsize|, flags|)
Receve dt from the socket. The return vue s pr {s1J1g, addJess) where
string s strng representng the dt receved nd address s the ddress of the
socket sendng the dt. See the Unx mnu pge recv(2) for the menng of the
opton rgument flags; t defuts to zero. (The formt of address depends on the
ddress fmy - see bove.)
13 17.2. socket - Io-IeveI netorkIng InterIace - Iython v2.7.2 documentatIon
12/28/2011 08.14.23 AM http.//docs.python.org/IIbrary/socket.htmI
socke1.recv1rom_n1o(buffer|, nbytes|, flags||)
Receve dt from the socket, wrtng t nto buffer nsted of cretng new strng.
The return vue s pr {by1es, addJess) where nbytes s the number of bytes
receved nd address s the ddress of the socket sendng the dt. See the Unx
mnu pge recv(2) for the menng of the opton rgument flags; t defuts to
zero. (The formt of address depends on the ddress fmy - see bove.)
Ne in version 2.5.
socke1.recv_n1o(buffer|, nbytes|, flags||)
Receve up to nbytes bytes from the socket, storng the dt nto buffer rther thn
cretng new strng. If nbytes s not specfed (or 0), receve up to the sze vbe
n the gven buffer. Returns the number of bytes receved. See the Unx mnu pge
recv(2) for the menng of the opton rgument flags; t defuts to zero.
Ne in version 2.5.
socke1.send(string|, flags|)
Send dt to the socket. The socket must be connected to remote socket. The
opton flags rgument hs the sme menng s for recv{) bove. Returns the
number of bytes sent. Appctons re responsbe for checkng tht dt hs been
sent; f ony some of the dt ws trnsmtted, the ppcton needs to ttempt
devery of the remnng dt.
socke1.senda11(string|, flags|)
Send dt to the socket. The socket must be connected to remote socket. The
opton flags rgument hs the sme menng s for recv{) bove. Unke send{),
ths method contnues to send dt from string unt ether dt hs been sent or
n error occurs. None s returned on success. On error, n excepton s rsed, nd
there s no wy to determne how much dt, f ny, ws successfuy sent.
socke1.send1o(string|, flags|, address)
Send dt to the socket. The socket shoud not be connected to remote socket,
snce the destnton socket s specfed by address. The opton flags rgument hs
the sme menng s for recv{) bove. Return the number of bytes sent. (The formt
of address depends on the ddress fmy - see bove.)
socke1.se1b1ockng(flag)
Set bockng or non-bockng mode of the socket: f flag s 0, the socket s set to non-
bockng, ese to bockng mode. Inty sockets re n bockng mode. In non-
bockng mode, f recv{) c doesnt fnd ny dt, or f send{) c cnt
mmedtey dspose of the dt, error excepton s rsed; n bockng mode, the
14 17.2. socket - Io-IeveI netorkIng InterIace - Iython v2.7.2 documentatIon
12/28/2011 08.14.23 AM http.//docs.python.org/IIbrary/socket.htmI
cs bock unt they cn proceed. s.se1bock1g{0) s equvent to s.se111meou1
{0.0); s.se1bock1g{1) s equvent to s.se111meou1{hoe).
socke1.se11meou1(value)
Set tmeout on bockng socket opertons. The value rgument cn be
nonnegtve fot expressng seconds, or None. If fot s gven, subsequent socket
opertons w rse 1meou1 excepton f the tmeout perod value hs epsed
before the operton hs competed. Settng tmeout of None dsbes tmeouts on
socket opertons. s.se111meou1{0.0) s equvent to s.se1bock1g{0);
s.se111meou1{hoe) s equvent to s.se1bock1g{1).
Ne in version 2.3.
socke1.ge11meou1()
Return the tmeout n seconds (fot) ssocted wth socket opertons, or None f no
tmeout s set. Ths refects the st c to se1b1ockng{) or se11meou1{).
Ne in version 2.3.
Some notes on socket bockng nd tmeouts: A socket ob|ect cn be n one of three
modes: bockng, non-bockng, or tmeout. Sockets re wys creted n bockng mode.
In bockng mode, opertons bock unt compete or the system returns n error (such s
connecton tmed out). In non-bockng mode, opertons f (wth n error tht s
unfortuntey system-dependent) f they cnnot be competed mmedtey. In tmeout
mode, opertons f f they cnnot be competed wthn the tmeout specfed for the
socket or f the system returns n error. The se1b1ockng{) method s smpy
shorthnd for certn se11meou1{) cs.
Tmeout mode nterny sets the socket n non-bockng mode. The bockng nd tmeout
modes re shred between fe descrptors nd socket ob|ects tht refer to the sme
network endpont. A consequence of ths s tht fe ob|ects returned by the make11e{)
method must ony be used when the socket s n bockng mode; n tmeout or non-
bockng mode fe opertons tht cnnot be competed mmedtey w f.
Note tht the connec1{) operton s sub|ect to the tmeout settng, nd n gener t s
recommended to c se11meou1{) before cng connec1{) or pss tmeout prmeter
to crea1e_connec1on{). The system network stck my return connecton tmeout
error of ts own regrdess of ny Python socket tmeout settng.
socke1.se1sockop1(level, optname, value)
Set the vue of the gven socket opton (see the Unx mnu pge setsockopt(2)).
The needed symboc constnts re defned n the socke1 modue (5_* etc.). The
vue cn be n nteger or strng representng buffer. In the tter cse t s up to
the cer to ensure tht the strng contns the proper bts (see the opton but-n
modue s1ruc1 for wy to encode C structures s strngs).
15 17.2. socket - Io-IeveI netorkIng InterIace - Iython v2.7.2 documentatIon
12/28/2011 08.14.23 AM http.//docs.python.org/IIbrary/socket.htmI
socke1.shu1doWn(ho)
Shut down one or both hves of the connecton. If ho s 5huT_, further receves
re dsowed. If ho s 5huT_W, further sends re dsowed. If ho s 5huT_W,
further sends nd receves re dsowed. Dependng on the ptform, shuttng down
one hf of the connecton cn so cose the opposte hf (e.g. on Mc OS X,
shu1dow{ShbT_WR) does not ow further reds on the other end of the connecton).
Note tht there re no methods read{) or Wr1e{); use recv{) nd send{) wthout flags
rgument nsted.
Socket ob|ects so hve these (red-ony) ttrbutes tht correspond to the vues gven
to the socke1 constructor.
socke1.1am1y
The socket fmy.
Ne in version 2.5.
socke1.1ype
The socket type.
Ne in version 2.5.
socke1.pro1o
The socket protoco.
Ne in version 2.5.
17.2.2. Example
Here re four mnm exmpe progrms usng the TCP/IP protoco: server tht echoes
dt tht t receves bck (servcng ony one cent), nd cent usng t. Note tht
server must perform the sequence socke1{), bnd{), 1s1en{), accep1{) (possby
repetng the accep1{) to servce more thn one cent), whe cent ony needs the
sequence socke1{), connec1{). Aso note tht the server does not send{)/recv{) on the
socket t s stenng on but on the new socket returned by accep1{).
The frst two exmpes support IPv4 ony.
# Echo seIveI pIogIa
mpor1 socke1
h0ST = `` # Sybo1Ic nae eanIng a11 avaI1ab1e In1eI1aces
P0RT = 50007 # 4IbI1IaIy non-pIIvI1eged poI1
s = socke1.socke1{socke1.AF_ThET, socke1.S0CK_STREAh)
16 17.2. socket - Io-IeveI netorkIng InterIace - Iython v2.7.2 documentatIon
12/28/2011 08.14.23 AM http.//docs.python.org/IIbrary/socket.htmI
The next two exmpes re dentc to the bove two, but support both IPv4 nd IPv6.
The server sde w sten to the frst ddress fmy vbe (t shoud sten to both
nsted). On most of IPv6-redy systems, IPv6 w tke precedence nd the server my
not ccept IPv4 trffc. The cent sde w try to connect to the ddresses returned s
resut of the nme resouton, nd sends trffc to the frst one connected successfuy.
s.b1d{{h0ST, P0RT))
s.1s1e{1)
co, addJ = s.accep1{)
prn1 `Coec1ed by`, addJ
Wh1e 1.
da1a = co.Jecv{1024)
1 no1 da1a. break
co.sed{da1a)
co.cose{)
# Echo c1Ien1 pIogIa
mpor1 socke1
h0ST = `daJ1g.cw1.` # The Ieo1e hos1
P0RT = 50007 # The sae poI1 as used by 1he seIveI
s = socke1.socke1{socke1.AF_ThET, socke1.S0CK_STREAh)
s.coec1{{h0ST, P0RT))
s.sed{`heo, woJd`)
da1a = s.Jecv{1024)
s.cose{)
prn1 `Rece1ved`, JepJ{da1a)
# Echo seIveI pIogIa
mpor1 socke1
mpor1 sys
h0ST = hoe # Sybo1Ic nae eanIng a11 avaI1ab1e In1eI1aces
P0RT = 50007 # 4IbI1IaIy non-pIIvI1eged poI1
s = hoe
1or Jes n socke1.ge1addJ11o{h0ST, P0RT, socke1.AF_bhSPEC,
socke1.S0CK_STREAh, 0, socke1.AT_PASSTvE).
a1, sock1ype, pJo1o, caoame, sa = Jes
1ry.
s = socke1.socke1{a1, sock1ype, pJo1o)
excep1 socke1.eJJoJ, msg.
s = hoe
con1nue
1ry.
s.b1d{sa)
s.1s1e{1)
17 17.2. socket - Io-IeveI netorkIng InterIace - Iython v2.7.2 documentatIon
12/28/2011 08.14.23 AM http.//docs.python.org/IIbrary/socket.htmI
excep1 socke1.eJJoJ, msg.
s.cose{)
s = hoe
con1nue
break
1 s s hoe.
prn1 `coud o1 ope socke1`
sys.ex11{1)
co, addJ = s.accep1{)
prn1 `Coec1ed by`, addJ
Wh1e 1.
da1a = co.Jecv{1024)
1 no1 da1a. break
co.sed{da1a)
co.cose{)
# Echo c1Ien1 pIogIa
mpor1 socke1
mpor1 sys
h0ST = `daJ1g.cw1.` # The Ieo1e hos1
P0RT = 50007 # The sae poI1 as used by 1he seIveI
s = hoe
1or Jes n socke1.ge1addJ11o{h0ST, P0RT, socke1.AF_bhSPEC, socke1.S0CK_
STREAh).
a1, sock1ype, pJo1o, caoame, sa = Jes
1ry.
s = socke1.socke1{a1, sock1ype, pJo1o)
excep1 socke1.eJJoJ, msg.
s = hoe
con1nue
1ry.
s.coec1{sa)
excep1 socke1.eJJoJ, msg.
s.cose{)
s = hoe
con1nue
break
1 s s hoe.
prn1 `coud o1 ope socke1`
sys.ex11{1)
s.sed{`heo, woJd`)
da1a = s.Jecv{1024)
s.cose{)
prn1 `Rece1ved`, JepJ{da1a)
18 17.2. socket - Io-IeveI netorkIng InterIace - Iython v2.7.2 documentatIon
12/28/2011 08.14.23 AM http.//docs.python.org/IIbrary/socket.htmI
The st exmpe shows how to wrte very smpe network snffer wth rw sockets on
Wndows. The exmpe requres dmnstrtor prveges to modfy the nterfce:
Runnng n exmpe sever tmes wth too sm dey between executons, coud ed to
ths error:
socke1.eJJoJ. |EJJo 98] AddJess aJeady 1 use
Ths s becuse the prevous executon hs eft the socket n TThE_WATT stte, nd cnt
be mmedtey reused.
There s socke1 fg to set, n order to prevent ths, socke1.5_Eu5E:
the 5_Eu5E fg tes the kerne to reuse oc socket n TThE_WATT stte, wthout
wtng for ts ntur tmeout to expre.
mpor1 socke1
# 1he pub1Ic ne1|oIk In1eI1ace
h0ST = socke1.ge1hos1byame{socke1.ge1hos1ame{))
# cIea1e a Ia| socke1 and bInd I1 1o 1he pub1Ic In1eI1ace
s = socke1.socke1{socke1.AF_ThET, socke1.S0CK_RAW, socke1.TPPR0T0_TP)
s.b1d{{h0ST, 0))
# Jnc1ude JP headeIs
s.se1sockop1{socke1.TPPR0T0_TP, socke1.TP_h0RThCL, 1)
# IeceIve a11 packages
s.1oc1{socke1.ST0_RCvALL, socke1.RCvALL_0h)
# IeceIve a package
prn1 s.Jecv1Jom{65565)
# dIsab1ed pIoIscuous ode
s.1oc1{socke1.ST0_RCvALL, socke1.RCvALL_0FF)
s = socke1.socke1{socke1.AF_ThET, socke1.S0CK_STREAh)
s.se1sockop1{socke1.S0L_S0CKET, socke1.S0_REbSEA00R, 1)
s.b1d{{h0ST, P0RT))

Vous aimerez peut-être aussi