5 This module provides an interface to Berkeley socket IPC.
9 - Only AF_INET, AF_INET6 and AF_UNIX address families are supported in a
10 portable manner, though AF_PACKET is supported under Linux.
11 - No read/write operations (use sendall/recv or makefile instead).
12 - Additional restrictions apply on some non-Unix platforms (compensated
17 - socket.error: exception raised for socket specific errors
18 - socket.gaierror: exception raised for getaddrinfo/getnameinfo errors,
19 a subclass of socket.error
20 - socket.herror: exception raised for gethostby* errors,
21 a subclass of socket.error
22 - socket.fromfd(fd, family, type[, proto]) --> new socket object (created
23 from an existing file descriptor)
24 - socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')
25 - socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])
26 - socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com')
27 - socket.getprotobyname(protocolname) --> protocol number
28 - socket.getservbyname(servicename[, protocolname]) --> port number
29 - socket.getservbyport(portnumber[, protocolname]) --> service name
30 - socket.socket([family[, type [, proto]]]) --> new socket object
31 - socket.socketpair([family[, type [, proto]]]) --> (socket, socket)
32 - socket.ntohs(16 bit value) --> new int object
33 - socket.ntohl(32 bit value) --> new int object
34 - socket.htons(16 bit value) --> new int object
35 - socket.htonl(32 bit value) --> new int object
36 - socket.getaddrinfo(host, port [, family, socktype, proto, flags])
37 --> List of (family, socktype, proto, canonname, sockaddr)
38 - socket.getnameinfo(sockaddr, flags) --> (host, port)
39 - socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
40 - socket.has_ipv6: boolean value indicating if IPv6 is supported
41 - socket.inet_aton(IP address) -> 32-bit packed IP representation
42 - socket.inet_ntoa(packed IP) -> IP address string
43 - socket.getdefaulttimeout() -> None | float
44 - socket.setdefaulttimeout(None | float)
45 - an Internet socket address is a pair (hostname, port)
46 where hostname can be anything recognized by gethostbyname()
47 (including the dd.dd.dd.dd notation) and port is in host byte order
48 - where a hostname is returned, the dd.dd.dd.dd notation is used
49 - a UNIX domain socket address is a string specifying the pathname
50 - an AF_PACKET socket address is a tuple containing a string
51 specifying the ethernet interface and an integer specifying
52 the Ethernet protocol number to be received. For example:
53 ("eth0",0x1234). Optional 3rd,4th,5th elements in the tuple
54 specify packet-type and ha-type/addr.
56 Local naming conventions:
58 - names starting with sock_ are socket object methods
59 - names starting with socket_ are module-level functions
60 - names starting with PySocket are exported through socketmodule.h
67 #define MAX(x, y) ((x) < (y) ? (y) : (x))
69 /* Socket object documentation */
70 PyDoc_STRVAR(sock_doc
,
71 "socket([family[, type[, proto]]]) -> socket object\n\
73 Open a socket of the given type. The family argument specifies the\n\
74 address family; it defaults to AF_INET. The type argument specifies\n\
75 whether this is a stream (SOCK_STREAM, this is the default)\n\
76 or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0,\n\
77 specifying the default protocol. Keyword arguments are accepted.\n\
79 A socket object represents one endpoint of a network connection.\n\
81 Methods of socket objects (keyword arguments not allowed):\n\
83 accept() -- accept a connection, returning new socket and client address\n\
84 bind(addr) -- bind the socket to a local address\n\
85 close() -- close the socket\n\
86 connect(addr) -- connect the socket to a remote address\n\
87 connect_ex(addr) -- connect, return an error code instead of an exception\n\
88 dup() -- return a new socket object identical to the current one [*]\n\
89 fileno() -- return underlying file descriptor\n\
90 getpeername() -- return remote address [*]\n\
91 getsockname() -- return local address\n\
92 getsockopt(level, optname[, buflen]) -- get socket options\n\
93 gettimeout() -- return timeout or None\n\
94 listen(n) -- start listening for incoming connections\n\
95 makefile([mode, [bufsize]]) -- return a file object for the socket [*]\n\
96 recv(buflen[, flags]) -- receive data\n\
97 recvfrom(buflen[, flags]) -- receive data and sender's address\n\
98 sendall(data[, flags]) -- send all data\n\
99 send(data[, flags]) -- send data, may not send all of it\n\
100 sendto(data[, flags], addr) -- send data to a given address\n\
101 setblocking(0 | 1) -- set or clear the blocking I/O flag\n\
102 setsockopt(level, optname, value) -- set socket options\n\
103 settimeout(None | float) -- set or clear the timeout\n\
104 shutdown(how) -- shut down traffic in one or both directions\n\
106 [*] not available on all platforms!");
108 /* XXX This is a terrible mess of platform-dependent preprocessor hacks.
109 I hope some day someone can clean this up please... */
111 /* Hacks for gethostbyname_r(). On some non-Linux platforms, the configure
112 script doesn't get this right, so we hardcode some platform checks below.
113 On the other hand, not all Linux versions agree, so there the settings
114 computed by the configure script are needed! */
117 # undef HAVE_GETHOSTBYNAME_R_3_ARG
118 # undef HAVE_GETHOSTBYNAME_R_5_ARG
119 # undef HAVE_GETHOSTBYNAME_R_6_ARG
123 # undef HAVE_GETHOSTBYNAME_R
126 #ifdef HAVE_GETHOSTBYNAME_R
127 # if defined(_AIX) || defined(__osf__)
128 # define HAVE_GETHOSTBYNAME_R_3_ARG
129 # elif defined(__sun) || defined(__sgi)
130 # define HAVE_GETHOSTBYNAME_R_5_ARG
131 # elif defined(linux)
132 /* Rely on the configure script */
134 # undef HAVE_GETHOSTBYNAME_R
138 #if !defined(HAVE_GETHOSTBYNAME_R) && defined(WITH_THREAD) && \
140 # define USE_GETHOSTBYNAME_LOCK
143 /* On systems on which getaddrinfo() is believed to not be thread-safe,
144 (this includes the getaddrinfo emulation) protect access with a lock. */
145 #if defined(WITH_THREAD) && (defined(__APPLE__) || defined(__FreeBSD__) || \
146 defined(__OpenBSD__) || defined(__NetBSD__) || !defined(HAVE_GETADDRINFO))
147 #define USE_GETADDRINFO_LOCK
150 #ifdef USE_GETADDRINFO_LOCK
151 #define ACQUIRE_GETADDRINFO_LOCK PyThread_acquire_lock(netdb_lock, 1);
152 #define RELEASE_GETADDRINFO_LOCK PyThread_release_lock(netdb_lock);
154 #define ACQUIRE_GETADDRINFO_LOCK
155 #define RELEASE_GETADDRINFO_LOCK
158 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
159 # include "pythread.h"
162 #if defined(PYCC_VACPP)
165 # include <sys/ioctl.h>
171 #if ! defined(_SOCKADDR_LEN)
175 # include "TCPIP_IOCTL_ROUTINE"
181 #if defined(PYOS_OS2)
183 # define INCL_DOSERRORS
184 # define INCL_NOPMAPI
188 #if defined(__sgi) && _COMPILER_VERSION>700 && !_SGIAPI
189 /* make sure that the reentrant (gethostbyaddr_r etc)
190 functions are declared correctly if compiling with
191 MIPSPro 7.x in ANSI C mode (default) */
193 /* XXX Using _SGIAPI is the wrong thing,
194 but I don't know what the right thing is. */
195 #undef _SGIAPI /* to avoid warning */
199 #include <sys/socket.h>
200 #include <sys/types.h>
201 #include <netinet/in.h>
203 #define HAVE_GETADDRINFO 1
204 #define HAVE_GETNAMEINFO 1
207 #define HAVE_INET_PTON
211 /* Irix 6.5 fails to define this variable at all. This is needed
212 for both GCC and SGI's compiler. I'd say that the SGI headers
214 #if defined(__sgi) && !defined(INET_ADDRSTRLEN)
215 #define INET_ADDRSTRLEN 16
218 /* Generic includes */
219 #include <sys/types.h>
221 /* Generic socket object definitions and includes */
222 #define PySocket_BUILDING_SOCKET
223 #include "socketmodule.h"
225 /* Addressing includes */
229 /* Non-MS WINDOWS includes */
232 /* Headers needed for inet_ntoa() and inet_addr() */
234 # include <net/netdb.h>
235 # elif defined(PYOS_OS2) && defined(PYCC_VACPP)
237 typedef size_t socklen_t
;
239 # include <arpa/inet.h>
245 # include <sys/ioctl.h>
246 # include <socklib.h>
248 int h_errno
; /* not used */
249 # define INET_ADDRSTRLEN 16
254 /* MS_WINDOWS includes */
262 # define offsetof(type, member) ((size_t)(&((type *)0)->member))
266 # define O_NONBLOCK O_NDELAY
269 /* include Python's addrinfo.h unless it causes trouble */
270 #if defined(__sgi) && _COMPILER_VERSION>700 && defined(_SS_ALIGNSIZE)
271 /* Do not include addinfo.h on some newer IRIX versions.
272 * _SS_ALIGNSIZE is defined in sys/socket.h by 6.5.21,
273 * for example, but not by 6.5.10.
275 #elif defined(_MSC_VER) && _MSC_VER>1200
276 /* Do not include addrinfo.h for MSVC7 or greater. 'addrinfo' and
277 * EAI_* constants are defined in (the already included) ws2tcpip.h.
280 # include "addrinfo.h"
283 #ifndef HAVE_INET_PTON
284 int inet_pton(int af
, const char *src
, void *dst
);
285 const char *inet_ntop(int af
, const void *src
, char *dst
, socklen_t size
);
289 /* On OS X, getaddrinfo returns no error indication of lookup
290 failure, so we must use the emulation instead of the libinfo
291 implementation. Unfortunately, performing an autoconf test
292 for this bug would require DNS access for the machine performing
293 the configuration, which is not acceptable. Therefore, we
294 determine the bug just by checking for __APPLE__. If this bug
295 gets ever fixed, perhaps checking for sys/version.h would be
296 appropriate, which is 10/0 on the system with the bug. */
297 #ifndef HAVE_GETNAMEINFO
298 /* This bug seems to be fixed in Jaguar. Ths easiest way I could
299 Find to check for Jaguar is that it has getnameinfo(), which
300 older releases don't have */
301 #undef HAVE_GETADDRINFO
305 /* I know this is a bad practice, but it is the easiest... */
306 #if !defined(HAVE_GETADDRINFO)
307 /* avoid clashes with the C library definition of the symbol. */
308 #define getaddrinfo fake_getaddrinfo
309 #define gai_strerror fake_gai_strerror
310 #define freeaddrinfo fake_freeaddrinfo
311 #include "getaddrinfo.c"
313 #if !defined(HAVE_GETNAMEINFO)
314 #define getnameinfo fake_getnameinfo
315 #include "getnameinfo.c"
318 #if defined(MS_WINDOWS) || defined(__BEOS__)
319 /* BeOS suffers from the same socket dichotomy as Win32... - [cjh] */
320 /* seem to be a few differences in the API */
321 #define SOCKETCLOSE closesocket
322 #define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */
326 #define EAFNOSUPPORT WSAEAFNOSUPPORT
327 #define snprintf _snprintf
330 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
331 #define SOCKETCLOSE soclose
332 #define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
336 #define SOCKETCLOSE close
340 /* TCP/IP Services for VMS uses a maximum send/revc buffer length of 65535 */
341 #define SEGMENT_SIZE 65535
344 #if defined(HAVE_BLUETOOTH_H) || defined(HAVE_BLUETOOTH_BLUETOOTH_H)
345 #define USE_BLUETOOTH 1
346 #if defined(__FreeBSD__)
347 #define BTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP
348 #define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM
349 #define sockaddr_l2 sockaddr_l2cap
350 #define sockaddr_rc sockaddr_rfcomm
351 #define _BT_SOCKADDR_MEMB(s, proto) &((s)->sock_addr)
352 #define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb)
353 #define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)
355 #define _BT_SOCKADDR_MEMB(s, proto) (&((s)->sock_addr).bt_##proto)
356 #define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb)
357 #define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb)
358 #define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)
363 * Constants for getnameinfo()
365 #if !defined(NI_MAXHOST)
366 #define NI_MAXHOST 1025
368 #if !defined(NI_MAXSERV)
369 #define NI_MAXSERV 32
372 /* XXX There's a problem here: *static* functions are not supposed to have
373 a Py prefix (or use CapitalizedWords). Later... */
375 /* Global variable holding the exception type for errors detected
376 by this module (but not argument type or memory errors, etc.). */
377 static PyObject
*socket_error
;
378 static PyObject
*socket_herror
;
379 static PyObject
*socket_gaierror
;
380 static PyObject
*socket_timeout
;
383 /* Global variable which is !=0 if Python is running in a RISC OS taskwindow */
384 static int taskwindow
;
387 /* A forward reference to the socket type object.
388 The sock_type variable contains pointers to various functions,
389 some of which call new_sockobject(), which uses sock_type, so
390 there has to be a circular reference. */
391 static PyTypeObject sock_type
;
393 /* Convenience function to raise an error according to errno
394 and return a NULL pointer from a function. */
400 int err_no
= WSAGetLastError();
405 {WSAEINTR
, "Interrupted system call"},
406 {WSAEBADF
, "Bad file descriptor"},
407 {WSAEACCES
, "Permission denied"},
408 {WSAEFAULT
, "Bad address"},
409 {WSAEINVAL
, "Invalid argument"},
410 {WSAEMFILE
, "Too many open files"},
412 "The socket operation could not complete "
414 {WSAEINPROGRESS
, "Operation now in progress"},
415 {WSAEALREADY
, "Operation already in progress"},
416 {WSAENOTSOCK
, "Socket operation on non-socket"},
417 {WSAEDESTADDRREQ
, "Destination address required"},
418 {WSAEMSGSIZE
, "Message too long"},
419 {WSAEPROTOTYPE
, "Protocol wrong type for socket"},
420 {WSAENOPROTOOPT
, "Protocol not available"},
421 {WSAEPROTONOSUPPORT
, "Protocol not supported"},
422 {WSAESOCKTNOSUPPORT
, "Socket type not supported"},
423 {WSAEOPNOTSUPP
, "Operation not supported"},
424 {WSAEPFNOSUPPORT
, "Protocol family not supported"},
425 {WSAEAFNOSUPPORT
, "Address family not supported"},
426 {WSAEADDRINUSE
, "Address already in use"},
427 {WSAEADDRNOTAVAIL
, "Can't assign requested address"},
428 {WSAENETDOWN
, "Network is down"},
429 {WSAENETUNREACH
, "Network is unreachable"},
430 {WSAENETRESET
, "Network dropped connection on reset"},
431 {WSAECONNABORTED
, "Software caused connection abort"},
432 {WSAECONNRESET
, "Connection reset by peer"},
433 {WSAENOBUFS
, "No buffer space available"},
434 {WSAEISCONN
, "Socket is already connected"},
435 {WSAENOTCONN
, "Socket is not connected"},
436 {WSAESHUTDOWN
, "Can't send after socket shutdown"},
437 {WSAETOOMANYREFS
, "Too many references: can't splice"},
438 {WSAETIMEDOUT
, "Operation timed out"},
439 {WSAECONNREFUSED
, "Connection refused"},
440 {WSAELOOP
, "Too many levels of symbolic links"},
441 {WSAENAMETOOLONG
, "File name too long"},
442 {WSAEHOSTDOWN
, "Host is down"},
443 {WSAEHOSTUNREACH
, "No route to host"},
444 {WSAENOTEMPTY
, "Directory not empty"},
445 {WSAEPROCLIM
, "Too many processes"},
446 {WSAEUSERS
, "Too many users"},
447 {WSAEDQUOT
, "Disc quota exceeded"},
448 {WSAESTALE
, "Stale NFS file handle"},
449 {WSAEREMOTE
, "Too many levels of remote in path"},
450 {WSASYSNOTREADY
, "Network subsystem is unvailable"},
451 {WSAVERNOTSUPPORTED
, "WinSock version is not supported"},
453 "Successful WSAStartup() not yet performed"},
454 {WSAEDISCON
, "Graceful shutdown in progress"},
455 /* Resolver errors */
456 {WSAHOST_NOT_FOUND
, "No such host is known"},
457 {WSATRY_AGAIN
, "Host not found, or server failed"},
458 {WSANO_RECOVERY
, "Unexpected server error encountered"},
459 {WSANO_DATA
, "Valid name without requested data"},
460 {WSANO_ADDRESS
, "No address, look for MX record"},
465 const char *msg
= "winsock error";
467 for (msgp
= msgs
; msgp
->msg
; msgp
++) {
468 if (err_no
== msgp
->no
) {
474 v
= Py_BuildValue("(is)", err_no
, msg
);
476 PyErr_SetObject(socket_error
, v
);
484 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
485 if (sock_errno() != NO_ERROR
) {
489 int myerrorcode
= sock_errno();
491 /* Retrieve socket-related error message from MPTN.MSG file */
492 rc
= DosGetMessage(NULL
, 0, outbuf
, sizeof(outbuf
),
493 myerrorcode
- SOCBASEERR
+ 26,
496 if (rc
== NO_ERROR
) {
499 /* OS/2 doesn't guarantee a terminator */
500 outbuf
[msglen
] = '\0';
501 if (strlen(outbuf
) > 0) {
502 /* If non-empty msg, trim CRLF */
503 char *lastc
= &outbuf
[ strlen(outbuf
)-1 ];
504 while (lastc
> outbuf
&& isspace(*lastc
)) {
505 /* Trim trailing whitespace (CRLF) */
509 v
= Py_BuildValue("(is)", myerrorcode
, outbuf
);
511 PyErr_SetObject(socket_error
, v
);
520 if (_inet_error
.errnum
!= NULL
) {
522 v
= Py_BuildValue("(is)", errno
, _inet_err());
524 PyErr_SetObject(socket_error
, v
);
531 return PyErr_SetFromErrno(socket_error
);
536 set_herror(int h_error
)
540 #ifdef HAVE_HSTRERROR
541 v
= Py_BuildValue("(is)", h_error
, (char *)hstrerror(h_error
));
543 v
= Py_BuildValue("(is)", h_error
, "host not found");
546 PyErr_SetObject(socket_herror
, v
);
555 set_gaierror(int error
)
560 /* EAI_SYSTEM is not available on Windows XP. */
561 if (error
== EAI_SYSTEM
)
565 #ifdef HAVE_GAI_STRERROR
566 v
= Py_BuildValue("(is)", error
, gai_strerror(error
));
568 v
= Py_BuildValue("(is)", error
, "getaddrinfo failed");
571 PyErr_SetObject(socket_gaierror
, v
);
578 /* Function to perform the setting of socket blocking mode
579 internally. block = (1 | 0). */
581 internal_setblocking(PySocketSockObject
*s
, int block
)
589 Py_BEGIN_ALLOW_THREADS
592 setsockopt(s
->sock_fd
, SOL_SOCKET
, SO_NONBLOCK
,
593 (void *)(&block
), sizeof(int));
597 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
599 ioctl(s
->sock_fd
, FIONBIO
, (caddr_t
)&block
, sizeof(block
));
602 ioctl(s
->sock_fd
, FIONBIO
, (char *)&block
);
603 #else /* !PYOS_OS2 && !_VMS */
604 delay_flag
= fcntl(s
->sock_fd
, F_GETFL
, 0);
606 delay_flag
&= (~O_NONBLOCK
);
608 delay_flag
|= O_NONBLOCK
;
609 fcntl(s
->sock_fd
, F_SETFL
, delay_flag
);
610 #endif /* !PYOS_OS2 */
611 #else /* MS_WINDOWS */
613 ioctlsocket(s
->sock_fd
, FIONBIO
, (u_long
*)&block
);
614 #endif /* MS_WINDOWS */
617 socketioctl(s
->sock_fd
, FIONBIO
, (u_long
*)&block
);
619 #endif /* __BEOS__ */
622 /* Since these don't return anything */
626 /* Do a select() on the socket, if necessary (sock_timeout > 0).
627 The argument writing indicates the direction.
628 This does not raise an exception; we'll let our caller do that
629 after they've reacquired the interpreter lock.
630 Returns 1 on timeout, 0 otherwise. */
632 internal_select(PySocketSockObject
*s
, int writing
)
638 /* Nothing to do unless we're in timeout mode (not non-blocking) */
639 if (s
->sock_timeout
<= 0.0)
642 /* Guard against closed socket */
646 /* Construct the arguments to select */
647 tv
.tv_sec
= (int)s
->sock_timeout
;
648 tv
.tv_usec
= (int)((s
->sock_timeout
- tv
.tv_sec
) * 1e6
);
650 FD_SET(s
->sock_fd
, &fds
);
652 /* See if the socket is ready */
654 n
= select(s
->sock_fd
+1, NULL
, &fds
, NULL
, &tv
);
656 n
= select(s
->sock_fd
+1, &fds
, NULL
, NULL
, &tv
);
662 /* Initialize a new socket object. */
664 static double defaulttimeout
= -1.0; /* Default timeout for new sockets */
667 init_sockobject(PySocketSockObject
*s
,
668 SOCKET_T fd
, int family
, int type
, int proto
)
674 s
->sock_family
= family
;
676 s
->sock_proto
= proto
;
677 s
->sock_timeout
= defaulttimeout
;
679 s
->errorhandler
= &set_error
;
681 if (defaulttimeout
>= 0.0)
682 internal_setblocking(s
, 0);
686 socketioctl(s
->sock_fd
, 0x80046679, (u_long
*)&block
);
691 /* Create a new socket object.
692 This just creates the object and initializes it.
693 If the creation fails, return NULL and set an exception (implicit
696 static PySocketSockObject
*
697 new_sockobject(SOCKET_T fd
, int family
, int type
, int proto
)
699 PySocketSockObject
*s
;
700 s
= (PySocketSockObject
*)
701 PyType_GenericNew(&sock_type
, NULL
, NULL
);
703 init_sockobject(s
, fd
, family
, type
, proto
);
708 /* Lock to allow python interpreter to continue, but only allow one
709 thread to be in gethostbyname or getaddrinfo */
710 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
711 PyThread_type_lock netdb_lock
;
715 /* Convert a string specifying a host name or one of a few symbolic
716 names to a numeric IP address. This usually calls gethostbyname()
717 to do the work; the names "" and "<broadcast>" are special.
718 Return the length (IPv4 should be 4 bytes), or negative if
719 an error occurred; then an exception is raised. */
722 setipaddr(char *name
, struct sockaddr
*addr_ret
, size_t addr_ret_size
, int af
)
724 struct addrinfo hints
, *res
;
729 memset((void *) addr_ret
, '\0', sizeof(*addr_ret
));
730 if (name
[0] == '\0') {
732 memset(&hints
, 0, sizeof(hints
));
733 hints
.ai_family
= af
;
734 hints
.ai_socktype
= SOCK_DGRAM
; /*dummy*/
735 hints
.ai_flags
= AI_PASSIVE
;
736 Py_BEGIN_ALLOW_THREADS
737 ACQUIRE_GETADDRINFO_LOCK
738 error
= getaddrinfo(NULL
, "0", &hints
, &res
);
740 /* We assume that those thread-unsafe getaddrinfo() versions
741 *are* safe regarding their return value, ie. that a
742 subsequent call to getaddrinfo() does not destroy the
743 outcome of the first call. */
744 RELEASE_GETADDRINFO_LOCK
749 switch (res
->ai_family
) {
760 PyErr_SetString(socket_error
,
761 "unsupported address family");
766 PyErr_SetString(socket_error
,
767 "wildcard resolved to multiple address");
770 if (res
->ai_addrlen
< addr_ret_size
)
771 addr_ret_size
= res
->ai_addrlen
;
772 memcpy(addr_ret
, res
->ai_addr
, addr_ret_size
);
776 if (name
[0] == '<' && strcmp(name
, "<broadcast>") == 0) {
777 struct sockaddr_in
*sin
;
778 if (af
!= AF_INET
&& af
!= AF_UNSPEC
) {
779 PyErr_SetString(socket_error
,
780 "address family mismatched");
783 sin
= (struct sockaddr_in
*)addr_ret
;
784 memset((void *) sin
, '\0', sizeof(*sin
));
785 sin
->sin_family
= AF_INET
;
786 #ifdef HAVE_SOCKADDR_SA_LEN
787 sin
->sin_len
= sizeof(*sin
);
789 sin
->sin_addr
.s_addr
= INADDR_BROADCAST
;
790 return sizeof(sin
->sin_addr
);
792 if (sscanf(name
, "%d.%d.%d.%d%c", &d1
, &d2
, &d3
, &d4
, &ch
) == 4 &&
793 0 <= d1
&& d1
<= 255 && 0 <= d2
&& d2
<= 255 &&
794 0 <= d3
&& d3
<= 255 && 0 <= d4
&& d4
<= 255) {
795 struct sockaddr_in
*sin
;
796 sin
= (struct sockaddr_in
*)addr_ret
;
797 sin
->sin_addr
.s_addr
= htonl(
798 ((long) d1
<< 24) | ((long) d2
<< 16) |
799 ((long) d3
<< 8) | ((long) d4
<< 0));
800 sin
->sin_family
= AF_INET
;
801 #ifdef HAVE_SOCKADDR_SA_LEN
802 sin
->sin_len
= sizeof(*sin
);
806 memset(&hints
, 0, sizeof(hints
));
807 hints
.ai_family
= af
;
808 Py_BEGIN_ALLOW_THREADS
809 ACQUIRE_GETADDRINFO_LOCK
810 error
= getaddrinfo(name
, NULL
, &hints
, &res
);
811 #if defined(__digital__) && defined(__unix__)
812 if (error
== EAI_NONAME
&& af
== AF_UNSPEC
) {
813 /* On Tru64 V5.1, numeric-to-addr conversion fails
814 if no address family is given. Assume IPv4 for now.*/
815 hints
.ai_family
= AF_INET
;
816 error
= getaddrinfo(name
, NULL
, &hints
, &res
);
820 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
825 if (res
->ai_addrlen
< addr_ret_size
)
826 addr_ret_size
= res
->ai_addrlen
;
827 memcpy((char *) addr_ret
, res
->ai_addr
, addr_ret_size
);
829 switch (addr_ret
->sa_family
) {
837 PyErr_SetString(socket_error
, "unknown address family");
843 /* Create a string object representing an IP address.
844 This is always a string of the form 'dd.dd.dd.dd' (with variable
848 makeipaddr(struct sockaddr
*addr
, int addrlen
)
850 char buf
[NI_MAXHOST
];
853 error
= getnameinfo(addr
, addrlen
, buf
, sizeof(buf
), NULL
, 0,
859 return PyString_FromString(buf
);
864 /* Convert a string representation of a Bluetooth address into a numeric
865 address. Returns the length (6), or raises an exception and returns -1 if
866 an error occurred. */
869 setbdaddr(char *name
, bdaddr_t
*bdaddr
)
871 unsigned int b0
, b1
, b2
, b3
, b4
, b5
;
875 n
= sscanf(name
, "%X:%X:%X:%X:%X:%X%c",
876 &b5
, &b4
, &b3
, &b2
, &b1
, &b0
, &ch
);
877 if (n
== 6 && (b0
| b1
| b2
| b3
| b4
| b5
) < 256) {
886 PyErr_SetString(socket_error
, "bad bluetooth address");
891 /* Create a string representation of the Bluetooth address. This is always a
892 string of the form 'XX:XX:XX:XX:XX:XX' where XX is a two digit hexadecimal
893 value (zero padded if necessary). */
896 makebdaddr(bdaddr_t
*bdaddr
)
898 char buf
[(6 * 2) + 5 + 1];
900 sprintf(buf
, "%02X:%02X:%02X:%02X:%02X:%02X",
901 bdaddr
->b
[5], bdaddr
->b
[4], bdaddr
->b
[3],
902 bdaddr
->b
[2], bdaddr
->b
[1], bdaddr
->b
[0]);
903 return PyString_FromString(buf
);
908 /* Create an object representing the given socket address,
909 suitable for passing it back to bind(), connect() etc.
910 The family field of the sockaddr structure is inspected
911 to determine what kind of address it really is. */
915 makesockaddr(int sockfd
, struct sockaddr
*addr
, int addrlen
, int proto
)
918 /* No address -- may be recvfrom() from known socket */
924 /* XXX: BeOS version of accept() doesn't set family correctly */
925 addr
->sa_family
= AF_INET
;
928 switch (addr
->sa_family
) {
932 struct sockaddr_in
*a
;
933 PyObject
*addrobj
= makeipaddr(addr
, sizeof(*a
));
934 PyObject
*ret
= NULL
;
936 a
= (struct sockaddr_in
*)addr
;
937 ret
= Py_BuildValue("Oi", addrobj
, ntohs(a
->sin_port
));
946 struct sockaddr_un
*a
= (struct sockaddr_un
*) addr
;
947 return PyString_FromString(a
->sun_path
);
954 struct sockaddr_in6
*a
;
955 PyObject
*addrobj
= makeipaddr(addr
, sizeof(*a
));
956 PyObject
*ret
= NULL
;
958 a
= (struct sockaddr_in6
*)addr
;
959 ret
= Py_BuildValue("Oiii",
976 struct sockaddr_l2
*a
= (struct sockaddr_l2
*) addr
;
977 PyObject
*addrobj
= makebdaddr(&_BT_L2_MEMB(a
, bdaddr
));
978 PyObject
*ret
= NULL
;
980 ret
= Py_BuildValue("Oi",
982 _BT_L2_MEMB(a
, psm
));
990 struct sockaddr_rc
*a
= (struct sockaddr_rc
*) addr
;
991 PyObject
*addrobj
= makebdaddr(&_BT_RC_MEMB(a
, bdaddr
));
992 PyObject
*ret
= NULL
;
994 ret
= Py_BuildValue("Oi",
996 _BT_RC_MEMB(a
, channel
));
1002 #if !defined(__FreeBSD__)
1005 struct sockaddr_sco
*a
= (struct sockaddr_sco
*) addr
;
1006 return makebdaddr(&_BT_SCO_MEMB(a
, bdaddr
));
1013 #ifdef HAVE_NETPACKET_PACKET_H
1016 struct sockaddr_ll
*a
= (struct sockaddr_ll
*)addr
;
1019 /* need to look up interface name give index */
1020 if (a
->sll_ifindex
) {
1021 ifr
.ifr_ifindex
= a
->sll_ifindex
;
1022 if (ioctl(sockfd
, SIOCGIFNAME
, &ifr
) == 0)
1023 ifname
= ifr
.ifr_name
;
1025 return Py_BuildValue("shbhs#",
1027 ntohs(a
->sll_protocol
),
1035 /* More cases here... */
1038 /* If we don't know the address family, don't raise an
1039 exception -- return it as a tuple. */
1040 return Py_BuildValue("is#",
1043 sizeof(addr
->sa_data
));
1049 /* Parse a socket address argument according to the socket object's
1050 address family. Return 1 if the address was in the proper format,
1051 0 of not. The address is returned through addr_ret, its length
1055 getsockaddrarg(PySocketSockObject
*s
, PyObject
*args
,
1056 struct sockaddr
**addr_ret
, int *len_ret
)
1058 switch (s
->sock_family
) {
1060 #if defined(AF_UNIX)
1063 struct sockaddr_un
* addr
;
1066 addr
= (struct sockaddr_un
*)&(s
->sock_addr
).un
;
1067 if (!PyArg_Parse(args
, "t#", &path
, &len
))
1069 if (len
> sizeof addr
->sun_path
) {
1070 PyErr_SetString(socket_error
,
1071 "AF_UNIX path too long");
1074 addr
->sun_family
= s
->sock_family
;
1075 memcpy(addr
->sun_path
, path
, len
);
1076 addr
->sun_path
[len
] = 0;
1077 *addr_ret
= (struct sockaddr
*) addr
;
1078 #if defined(PYOS_OS2)
1079 *len_ret
= sizeof(*addr
);
1081 *len_ret
= len
+ sizeof(*addr
) - sizeof(addr
->sun_path
);
1085 #endif /* AF_UNIX */
1089 struct sockaddr_in
* addr
;
1092 addr
=(struct sockaddr_in
*)&(s
->sock_addr
).in
;
1093 if (!PyTuple_Check(args
)) {
1097 "AF_INET address must be tuple, not %.500s",
1098 args
->ob_type
->tp_name
);
1101 if (!PyArg_ParseTuple(args
, "eti:getsockaddrarg",
1102 "idna", &host
, &port
))
1104 result
= setipaddr(host
, (struct sockaddr
*)addr
,
1105 sizeof(*addr
), AF_INET
);
1109 addr
->sin_family
= AF_INET
;
1110 addr
->sin_port
= htons((short)port
);
1111 *addr_ret
= (struct sockaddr
*) addr
;
1112 *len_ret
= sizeof *addr
;
1119 struct sockaddr_in6
* addr
;
1121 int port
, flowinfo
, scope_id
, result
;
1122 addr
= (struct sockaddr_in6
*)&(s
->sock_addr
).in6
;
1123 flowinfo
= scope_id
= 0;
1124 if (!PyArg_ParseTuple(args
, "eti|ii",
1125 "idna", &host
, &port
, &flowinfo
,
1129 result
= setipaddr(host
, (struct sockaddr
*)addr
,
1130 sizeof(*addr
), AF_INET6
);
1134 addr
->sin6_family
= s
->sock_family
;
1135 addr
->sin6_port
= htons((short)port
);
1136 addr
->sin6_flowinfo
= flowinfo
;
1137 addr
->sin6_scope_id
= scope_id
;
1138 *addr_ret
= (struct sockaddr
*) addr
;
1139 *len_ret
= sizeof *addr
;
1144 #ifdef USE_BLUETOOTH
1147 switch (s
->sock_proto
) {
1150 struct sockaddr_l2
*addr
= (struct sockaddr_l2
*) _BT_SOCKADDR_MEMB(s
, l2
);
1153 _BT_L2_MEMB(addr
, family
) = AF_BLUETOOTH
;
1154 if (!PyArg_ParseTuple(args
, "si", &straddr
,
1155 &_BT_L2_MEMB(addr
, psm
))) {
1156 PyErr_SetString(socket_error
, "getsockaddrarg: "
1160 if (setbdaddr(straddr
, &_BT_L2_MEMB(addr
, bdaddr
)) < 0)
1163 *addr_ret
= (struct sockaddr
*) addr
;
1164 *len_ret
= sizeof *addr
;
1167 case BTPROTO_RFCOMM
:
1169 struct sockaddr_rc
*addr
= (struct sockaddr_rc
*) _BT_SOCKADDR_MEMB(s
, rc
);
1172 _BT_RC_MEMB(addr
, family
) = AF_BLUETOOTH
;
1173 if (!PyArg_ParseTuple(args
, "si", &straddr
,
1174 &_BT_RC_MEMB(addr
, channel
))) {
1175 PyErr_SetString(socket_error
, "getsockaddrarg: "
1179 if (setbdaddr(straddr
, &_BT_RC_MEMB(addr
, bdaddr
)) < 0)
1182 *addr_ret
= (struct sockaddr
*) addr
;
1183 *len_ret
= sizeof *addr
;
1186 #if !defined(__FreeBSD__)
1189 struct sockaddr_sco
*addr
= (struct sockaddr_sco
*) _BT_SOCKADDR_MEMB(s
, sco
);
1192 _BT_SCO_MEMB(addr
, family
) = AF_BLUETOOTH
;
1193 straddr
= PyString_AsString(args
);
1194 if (straddr
== NULL
) {
1195 PyErr_SetString(socket_error
, "getsockaddrarg: "
1199 if (setbdaddr(straddr
, &_BT_SCO_MEMB(addr
, bdaddr
)) < 0)
1202 *addr_ret
= (struct sockaddr
*) addr
;
1203 *len_ret
= sizeof *addr
;
1208 PyErr_SetString(socket_error
, "getsockaddrarg: unknown Bluetooth protocol");
1214 #ifdef HAVE_NETPACKET_PACKET_H
1217 struct sockaddr_ll
* addr
;
1219 char *interfaceName
;
1224 unsigned int halen
= 0;
1226 if (!PyArg_ParseTuple(args
, "si|iis#", &interfaceName
,
1227 &protoNumber
, &pkttype
, &hatype
,
1230 strncpy(ifr
.ifr_name
, interfaceName
, sizeof(ifr
.ifr_name
));
1231 ifr
.ifr_name
[(sizeof(ifr
.ifr_name
))-1] = '\0';
1232 if (ioctl(s
->sock_fd
, SIOCGIFINDEX
, &ifr
) < 0) {
1236 addr
= &(s
->sock_addr
.ll
);
1237 addr
->sll_family
= AF_PACKET
;
1238 addr
->sll_protocol
= htons((short)protoNumber
);
1239 addr
->sll_ifindex
= ifr
.ifr_ifindex
;
1240 addr
->sll_pkttype
= pkttype
;
1241 addr
->sll_hatype
= hatype
;
1243 PyErr_SetString(PyExc_ValueError
,
1244 "Hardware address must be 8 bytes or less");
1248 memcpy(&addr
->sll_addr
, haddr
, halen
);
1250 addr
->sll_halen
= halen
;
1251 *addr_ret
= (struct sockaddr
*) addr
;
1252 *len_ret
= sizeof *addr
;
1257 /* More cases here... */
1260 PyErr_SetString(socket_error
, "getsockaddrarg: bad family");
1267 /* Get the address length according to the socket object's address family.
1268 Return 1 if the family is known, 0 otherwise. The length is returned
1272 getsockaddrlen(PySocketSockObject
*s
, socklen_t
*len_ret
)
1274 switch (s
->sock_family
) {
1276 #if defined(AF_UNIX)
1279 *len_ret
= sizeof (struct sockaddr_un
);
1282 #endif /* AF_UNIX */
1286 *len_ret
= sizeof (struct sockaddr_in
);
1293 *len_ret
= sizeof (struct sockaddr_in6
);
1298 #ifdef USE_BLUETOOTH
1301 switch(s
->sock_proto
)
1305 *len_ret
= sizeof (struct sockaddr_l2
);
1307 case BTPROTO_RFCOMM
:
1308 *len_ret
= sizeof (struct sockaddr_rc
);
1310 #if !defined(__FreeBSD__)
1312 *len_ret
= sizeof (struct sockaddr_sco
);
1316 PyErr_SetString(socket_error
, "getsockaddrlen: "
1317 "unknown BT protocol");
1324 #ifdef HAVE_NETPACKET_PACKET_H
1327 *len_ret
= sizeof (struct sockaddr_ll
);
1332 /* More cases here... */
1335 PyErr_SetString(socket_error
, "getsockaddrlen: bad family");
1342 /* s.accept() method */
1345 sock_accept(PySocketSockObject
*s
)
1350 PyObject
*sock
= NULL
;
1351 PyObject
*addr
= NULL
;
1352 PyObject
*res
= NULL
;
1355 if (!getsockaddrlen(s
, &addrlen
))
1357 memset(addrbuf
, 0, addrlen
);
1360 newfd
= INVALID_SOCKET
;
1365 Py_BEGIN_ALLOW_THREADS
1366 timeout
= internal_select(s
, 0);
1368 newfd
= accept(s
->sock_fd
, (struct sockaddr
*) addrbuf
,
1370 Py_END_ALLOW_THREADS
1373 PyErr_SetString(socket_timeout
, "timed out");
1378 if (newfd
== INVALID_SOCKET
)
1382 return s
->errorhandler();
1384 /* Create the new object with unspecified family,
1385 to avoid calls to bind() etc. on it. */
1386 sock
= (PyObject
*) new_sockobject(newfd
,
1395 addr
= makesockaddr(s
->sock_fd
, (struct sockaddr
*)addrbuf
,
1396 addrlen
, s
->sock_proto
);
1400 res
= PyTuple_Pack(2, sock
, addr
);
1408 PyDoc_STRVAR(accept_doc
,
1409 "accept() -> (socket object, address info)\n\
1411 Wait for an incoming connection. Return a new socket representing the\n\
1412 connection, and the address of the client. For IP sockets, the address\n\
1413 info is a pair (hostaddr, port).");
1415 /* s.setblocking(flag) method. Argument:
1416 False -- non-blocking mode; same as settimeout(0)
1417 True -- blocking mode; same as settimeout(None)
1421 sock_setblocking(PySocketSockObject
*s
, PyObject
*arg
)
1425 block
= PyInt_AsLong(arg
);
1426 if (block
== -1 && PyErr_Occurred())
1429 s
->sock_timeout
= block
? -1.0 : 0.0;
1430 internal_setblocking(s
, block
);
1436 PyDoc_STRVAR(setblocking_doc
,
1437 "setblocking(flag)\n\
1439 Set the socket to blocking (flag is true) or non-blocking (false).\n\
1440 setblocking(True) is equivalent to settimeout(None);\n\
1441 setblocking(False) is equivalent to settimeout(0.0).");
1443 /* s.settimeout(timeout) method. Argument:
1444 None -- no timeout, blocking mode; same as setblocking(True)
1445 0.0 -- non-blocking mode; same as setblocking(False)
1446 > 0 -- timeout mode; operations time out after timeout seconds
1447 < 0 -- illegal; raises an exception
1450 sock_settimeout(PySocketSockObject
*s
, PyObject
*arg
)
1457 timeout
= PyFloat_AsDouble(arg
);
1458 if (timeout
< 0.0) {
1459 if (!PyErr_Occurred())
1460 PyErr_SetString(PyExc_ValueError
,
1461 "Timeout value out of range");
1466 s
->sock_timeout
= timeout
;
1467 internal_setblocking(s
, timeout
< 0.0);
1473 PyDoc_STRVAR(settimeout_doc
,
1474 "settimeout(timeout)\n\
1476 Set a timeout on socket operations. 'timeout' can be a float,\n\
1477 giving in seconds, or None. Setting a timeout of None disables\n\
1478 the timeout feature and is equivalent to setblocking(1).\n\
1479 Setting a timeout of zero is the same as setblocking(0).");
1481 /* s.gettimeout() method.
1482 Returns the timeout associated with a socket. */
1484 sock_gettimeout(PySocketSockObject
*s
)
1486 if (s
->sock_timeout
< 0.0) {
1491 return PyFloat_FromDouble(s
->sock_timeout
);
1494 PyDoc_STRVAR(gettimeout_doc
,
1495 "gettimeout() -> timeout\n\
1497 Returns the timeout in floating seconds associated with socket \n\
1498 operations. A timeout of None indicates that timeouts on socket \n\
1499 operations are disabled.");
1502 /* s.sleeptaskw(1 | 0) method */
1505 sock_sleeptaskw(PySocketSockObject
*s
,PyObject
*arg
)
1508 block
= PyInt_AsLong(arg
);
1509 if (block
== -1 && PyErr_Occurred())
1511 Py_BEGIN_ALLOW_THREADS
1512 socketioctl(s
->sock_fd
, 0x80046679, (u_long
*)&block
);
1513 Py_END_ALLOW_THREADS
1518 PyDoc_STRVAR(sleeptaskw_doc
,
1519 "sleeptaskw(flag)\n\
1521 Allow sleeps in taskwindows.");
1525 /* s.setsockopt() method.
1526 With an integer third argument, sets an integer option.
1527 With a string third argument, sets an option from a buffer;
1528 use optional built-in module 'struct' to encode the string. */
1531 sock_setsockopt(PySocketSockObject
*s
, PyObject
*args
)
1540 if (PyArg_ParseTuple(args
, "iii:setsockopt",
1541 &level
, &optname
, &flag
)) {
1542 buf
= (char *) &flag
;
1543 buflen
= sizeof flag
;
1547 if (!PyArg_ParseTuple(args
, "iis#:setsockopt",
1548 &level
, &optname
, &buf
, &buflen
))
1551 res
= setsockopt(s
->sock_fd
, level
, optname
, (void *)buf
, buflen
);
1553 return s
->errorhandler();
1558 PyDoc_STRVAR(setsockopt_doc
,
1559 "setsockopt(level, option, value)\n\
1561 Set a socket option. See the Unix manual for level and option.\n\
1562 The value argument can either be an integer or a string.");
1565 /* s.getsockopt() method.
1566 With two arguments, retrieves an integer option.
1567 With a third integer argument, retrieves a string buffer of that size;
1568 use optional built-in module 'struct' to decode the string. */
1571 sock_getsockopt(PySocketSockObject
*s
, PyObject
*args
)
1577 socklen_t buflen
= 0;
1580 /* We have incomplete socket support. */
1581 PyErr_SetString(socket_error
, "getsockopt not supported");
1585 if (!PyArg_ParseTuple(args
, "ii|i:getsockopt",
1586 &level
, &optname
, &buflen
))
1591 socklen_t flagsize
= sizeof flag
;
1592 res
= getsockopt(s
->sock_fd
, level
, optname
,
1593 (void *)&flag
, &flagsize
);
1595 return s
->errorhandler();
1596 return PyInt_FromLong(flag
);
1599 if (buflen
> 1024) {
1601 if (buflen
<= 0 || buflen
> 1024) {
1603 PyErr_SetString(socket_error
,
1604 "getsockopt buflen out of range");
1607 buf
= PyString_FromStringAndSize((char *)NULL
, buflen
);
1610 res
= getsockopt(s
->sock_fd
, level
, optname
,
1611 (void *)PyString_AS_STRING(buf
), &buflen
);
1614 return s
->errorhandler();
1616 _PyString_Resize(&buf
, buflen
);
1618 #endif /* __BEOS__ */
1621 PyDoc_STRVAR(getsockopt_doc
,
1622 "getsockopt(level, option[, buffersize]) -> value\n\
1624 Get a socket option. See the Unix manual for level and option.\n\
1625 If a nonzero buffersize argument is given, the return value is a\n\
1626 string of that length; otherwise it is an integer.");
1629 /* s.bind(sockaddr) method */
1632 sock_bind(PySocketSockObject
*s
, PyObject
*addro
)
1634 struct sockaddr
*addr
;
1638 if (!getsockaddrarg(s
, addro
, &addr
, &addrlen
))
1640 Py_BEGIN_ALLOW_THREADS
1641 res
= bind(s
->sock_fd
, addr
, addrlen
);
1642 Py_END_ALLOW_THREADS
1644 return s
->errorhandler();
1649 PyDoc_STRVAR(bind_doc
,
1652 Bind the socket to a local address. For IP sockets, the address is a\n\
1653 pair (host, port); the host must refer to the local host. For raw packet\n\
1654 sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");
1657 /* s.close() method.
1658 Set the file descriptor to -1 so operations tried subsequently
1659 will surely fail. */
1662 sock_close(PySocketSockObject
*s
)
1666 if ((fd
= s
->sock_fd
) != -1) {
1668 Py_BEGIN_ALLOW_THREADS
1669 (void) SOCKETCLOSE(fd
);
1670 Py_END_ALLOW_THREADS
1676 PyDoc_STRVAR(close_doc
,
1679 Close the socket. It cannot be used after this call.");
1682 internal_connect(PySocketSockObject
*s
, struct sockaddr
*addr
, int addrlen
,
1688 res
= connect(s
->sock_fd
, addr
, addrlen
);
1692 if (s
->sock_timeout
> 0.0) {
1693 if (res
< 0 && WSAGetLastError() == WSAEWOULDBLOCK
) {
1694 /* This is a mess. Best solution: trust select */
1698 tv
.tv_sec
= (int)s
->sock_timeout
;
1699 tv
.tv_usec
= (int)((s
->sock_timeout
- tv
.tv_sec
) * 1e6
);
1701 FD_SET(s
->sock_fd
, &fds
);
1703 FD_SET(s
->sock_fd
, &fds_exc
);
1704 res
= select(s
->sock_fd
+1, NULL
, &fds
, &fds_exc
, &tv
);
1706 res
= WSAEWOULDBLOCK
;
1708 } else if (res
> 0) {
1709 if (FD_ISSET(s
->sock_fd
, &fds
))
1710 /* The socket is in the writeable set - this
1714 /* As per MS docs, we need to call getsockopt()
1715 to get the underlying error */
1716 int res_size
= sizeof res
;
1717 /* It must be in the exception set */
1718 assert(FD_ISSET(s
->sock_fd
, &fds_exc
));
1719 if (0 == getsockopt(s
->sock_fd
, SOL_SOCKET
, SO_ERROR
,
1720 (char *)&res
, &res_size
))
1721 /* getsockopt also clears WSAGetLastError,
1722 so reset it back. */
1723 WSASetLastError(res
);
1725 res
= WSAGetLastError();
1728 /* else if (res < 0) an error occurred */
1733 res
= WSAGetLastError();
1737 if (s
->sock_timeout
> 0.0) {
1738 if (res
< 0 && errno
== EINPROGRESS
) {
1739 timeout
= internal_select(s
, 1);
1740 res
= connect(s
->sock_fd
, addr
, addrlen
);
1741 if (res
< 0 && errno
== EISCONN
)
1750 *timeoutp
= timeout
;
1755 /* s.connect(sockaddr) method */
1758 sock_connect(PySocketSockObject
*s
, PyObject
*addro
)
1760 struct sockaddr
*addr
;
1765 if (!getsockaddrarg(s
, addro
, &addr
, &addrlen
))
1768 Py_BEGIN_ALLOW_THREADS
1769 res
= internal_connect(s
, addr
, addrlen
, &timeout
);
1770 Py_END_ALLOW_THREADS
1773 PyErr_SetString(socket_timeout
, "timed out");
1777 return s
->errorhandler();
1782 PyDoc_STRVAR(connect_doc
,
1783 "connect(address)\n\
1785 Connect the socket to a remote address. For IP sockets, the address\n\
1786 is a pair (host, port).");
1789 /* s.connect_ex(sockaddr) method */
1792 sock_connect_ex(PySocketSockObject
*s
, PyObject
*addro
)
1794 struct sockaddr
*addr
;
1799 if (!getsockaddrarg(s
, addro
, &addr
, &addrlen
))
1802 Py_BEGIN_ALLOW_THREADS
1803 res
= internal_connect(s
, addr
, addrlen
, &timeout
);
1804 Py_END_ALLOW_THREADS
1806 return PyInt_FromLong((long) res
);
1809 PyDoc_STRVAR(connect_ex_doc
,
1810 "connect_ex(address) -> errno\n\
1812 This is like connect(address), but returns an error code (the errno value)\n\
1813 instead of raising an exception when an error occurs.");
1816 /* s.fileno() method */
1819 sock_fileno(PySocketSockObject
*s
)
1821 #if SIZEOF_SOCKET_T <= SIZEOF_LONG
1822 return PyInt_FromLong((long) s
->sock_fd
);
1824 return PyLong_FromLongLong((PY_LONG_LONG
)s
->sock_fd
);
1828 PyDoc_STRVAR(fileno_doc
,
1829 "fileno() -> integer\n\
1831 Return the integer file descriptor of the socket.");
1835 /* s.dup() method */
1838 sock_dup(PySocketSockObject
*s
)
1843 newfd
= dup(s
->sock_fd
);
1845 return s
->errorhandler();
1846 sock
= (PyObject
*) new_sockobject(newfd
,
1855 PyDoc_STRVAR(dup_doc
,
1856 "dup() -> socket object\n\
1858 Return a new socket object connected to the same system resource.");
1863 /* s.getsockname() method */
1866 sock_getsockname(PySocketSockObject
*s
)
1872 if (!getsockaddrlen(s
, &addrlen
))
1874 memset(addrbuf
, 0, addrlen
);
1875 Py_BEGIN_ALLOW_THREADS
1876 res
= getsockname(s
->sock_fd
, (struct sockaddr
*) addrbuf
, &addrlen
);
1877 Py_END_ALLOW_THREADS
1879 return s
->errorhandler();
1880 return makesockaddr(s
->sock_fd
, (struct sockaddr
*) addrbuf
, addrlen
,
1884 PyDoc_STRVAR(getsockname_doc
,
1885 "getsockname() -> address info\n\
1887 Return the address of the local endpoint. For IP sockets, the address\n\
1888 info is a pair (hostaddr, port).");
1891 #ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
1892 /* s.getpeername() method */
1895 sock_getpeername(PySocketSockObject
*s
)
1901 if (!getsockaddrlen(s
, &addrlen
))
1903 memset(addrbuf
, 0, addrlen
);
1904 Py_BEGIN_ALLOW_THREADS
1905 res
= getpeername(s
->sock_fd
, (struct sockaddr
*) addrbuf
, &addrlen
);
1906 Py_END_ALLOW_THREADS
1908 return s
->errorhandler();
1909 return makesockaddr(s
->sock_fd
, (struct sockaddr
*) addrbuf
, addrlen
,
1913 PyDoc_STRVAR(getpeername_doc
,
1914 "getpeername() -> address info\n\
1916 Return the address of the remote endpoint. For IP sockets, the address\n\
1917 info is a pair (hostaddr, port).");
1919 #endif /* HAVE_GETPEERNAME */
1922 /* s.listen(n) method */
1925 sock_listen(PySocketSockObject
*s
, PyObject
*arg
)
1930 backlog
= PyInt_AsLong(arg
);
1931 if (backlog
== -1 && PyErr_Occurred())
1933 Py_BEGIN_ALLOW_THREADS
1936 res
= listen(s
->sock_fd
, backlog
);
1937 Py_END_ALLOW_THREADS
1939 return s
->errorhandler();
1944 PyDoc_STRVAR(listen_doc
,
1947 Enable a server to accept connections. The backlog argument must be at\n\
1948 least 1; it specifies the number of unaccepted connection that the system\n\
1949 will allow before refusing new connections.");
1953 /* s.makefile(mode) method.
1954 Create a new open file object referring to a dupped version of
1955 the socket's file descriptor. (The dup() call is necessary so
1956 that the open file and socket objects may be closed independent
1958 The mode argument specifies 'r' or 'w' passed to fdopen(). */
1961 sock_makefile(PySocketSockObject
*s
, PyObject
*args
)
1963 extern int fclose(FILE *);
1978 if (!PyArg_ParseTuple(args
, "|si:makefile", &mode
, &bufsize
))
1981 if (strcmp(mode
,"rb") == 0) {
1985 if (strcmp(mode
,"wb") == 0) {
1991 if (((fd
= _open_osfhandle(s
->sock_fd
, _O_BINARY
)) < 0) ||
1992 ((fd
= dup(fd
)) < 0) || ((fp
= fdopen(fd
, mode
)) == NULL
))
1994 if ((fd
= dup(s
->sock_fd
)) < 0 || (fp
= fdopen(fd
, mode
)) == NULL
)
1999 return s
->errorhandler();
2001 f
= PyFile_FromFile(fp
, "<socket>", mode
, fclose
);
2003 PyFile_SetBufSize(f
, bufsize
);
2007 PyDoc_STRVAR(makefile_doc
,
2008 "makefile([mode[, buffersize]]) -> file object\n\
2010 Return a regular file object corresponding to the socket.\n\
2011 The mode and buffersize arguments are as for the built-in open() function.");
2016 /* s.recv(nbytes [,flags]) method */
2019 sock_recv(PySocketSockObject
*s
, PyObject
*args
)
2021 int len
, n
= 0, flags
= 0, timeout
;
2028 if (!PyArg_ParseTuple(args
, "i|i:recv", &len
, &flags
))
2032 PyErr_SetString(PyExc_ValueError
,
2033 "negative buffersize in recv");
2037 buf
= PyString_FromStringAndSize((char *) 0, len
);
2042 Py_BEGIN_ALLOW_THREADS
2043 timeout
= internal_select(s
, 0);
2045 n
= recv(s
->sock_fd
, PyString_AS_STRING(buf
), len
, flags
);
2046 Py_END_ALLOW_THREADS
2050 PyErr_SetString(socket_timeout
, "timed out");
2055 return s
->errorhandler();
2058 _PyString_Resize(&buf
, n
);
2060 read_buf
= PyString_AsString(buf
);
2062 while (read_length
!= 0) {
2063 unsigned int segment
;
2065 segment
= read_length
/SEGMENT_SIZE
;
2067 segment
= SEGMENT_SIZE
;
2070 segment
= read_length
;
2073 Py_BEGIN_ALLOW_THREADS
2074 timeout
= internal_select(s
, 0);
2076 n
= recv(s
->sock_fd
, read_buf
, segment
, flags
);
2077 Py_END_ALLOW_THREADS
2081 PyErr_SetString(socket_timeout
, "timed out");
2086 return s
->errorhandler();
2088 if (n
!= read_length
) {
2093 read_length
-= segment
;
2094 read_buf
+= segment
;
2096 if (_PyString_Resize(&buf
, (read_buf
- PyString_AsString(buf
))) < 0)
2104 PyDoc_STRVAR(recv_doc
,
2105 "recv(buffersize[, flags]) -> data\n\
2107 Receive up to buffersize bytes from the socket. For the optional flags\n\
2108 argument, see the Unix manual. When no data is available, block until\n\
2109 at least one byte is available or until the remote end is closed. When\n\
2110 the remote end is closed and all data is read, return the empty string.");
2113 /* s.recvfrom(nbytes [,flags]) method */
2116 sock_recvfrom(PySocketSockObject
*s
, PyObject
*args
)
2119 PyObject
*buf
= NULL
;
2120 PyObject
*addr
= NULL
;
2121 PyObject
*ret
= NULL
;
2122 int len
, n
= 0, flags
= 0, timeout
;
2125 if (!PyArg_ParseTuple(args
, "i|i:recvfrom", &len
, &flags
))
2128 if (!getsockaddrlen(s
, &addrlen
))
2130 buf
= PyString_FromStringAndSize((char *) 0, len
);
2134 Py_BEGIN_ALLOW_THREADS
2135 memset(addrbuf
, 0, addrlen
);
2136 timeout
= internal_select(s
, 0);
2138 n
= recvfrom(s
->sock_fd
, PyString_AS_STRING(buf
), len
, flags
,
2140 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
2141 (struct sockaddr
*)addrbuf
, &addrlen
2143 (void *)addrbuf
, &addrlen
2146 (struct sockaddr
*)addrbuf
, &addrlen
2149 Py_END_ALLOW_THREADS
2153 PyErr_SetString(socket_timeout
, "timed out");
2158 return s
->errorhandler();
2161 if (n
!= len
&& _PyString_Resize(&buf
, n
) < 0)
2164 if (!(addr
= makesockaddr(s
->sock_fd
, (struct sockaddr
*)addrbuf
,
2165 addrlen
, s
->sock_proto
)))
2168 ret
= PyTuple_Pack(2, buf
, addr
);
2176 PyDoc_STRVAR(recvfrom_doc
,
2177 "recvfrom(buffersize[, flags]) -> (data, address info)\n\
2179 Like recv(buffersize, flags) but also return the sender's address info.");
2181 /* s.send(data [,flags]) method */
2184 sock_send(PySocketSockObject
*s
, PyObject
*args
)
2187 int len
, n
= 0, flags
= 0, timeout
;
2192 if (!PyArg_ParseTuple(args
, "s#|i:send", &buf
, &len
, &flags
))
2196 Py_BEGIN_ALLOW_THREADS
2197 timeout
= internal_select(s
, 1);
2199 n
= send(s
->sock_fd
, buf
, len
, flags
);
2200 Py_END_ALLOW_THREADS
2203 PyErr_SetString(socket_timeout
, "timed out");
2207 return s
->errorhandler();
2209 /* Divide packet into smaller segments for */
2210 /* TCP/IP Services for OpenVMS */
2212 while (send_length
!= 0) {
2213 unsigned int segment
;
2215 segment
= send_length
/ SEGMENT_SIZE
;
2217 segment
= SEGMENT_SIZE
;
2220 segment
= send_length
;
2222 Py_BEGIN_ALLOW_THREADS
2223 timeout
= internal_select(s
, 1);
2225 n
= send(s
->sock_fd
, buf
, segment
, flags
);
2226 Py_END_ALLOW_THREADS
2228 PyErr_SetString(socket_timeout
, "timed out");
2232 return s
->errorhandler();
2234 send_length
-= segment
;
2238 return PyInt_FromLong((long)n
);
2241 PyDoc_STRVAR(send_doc
,
2242 "send(data[, flags]) -> count\n\
2244 Send a data string to the socket. For the optional flags\n\
2245 argument, see the Unix manual. Return the number of bytes\n\
2246 sent; this may be less than len(data) if the network is busy.");
2249 /* s.sendall(data [,flags]) method */
2252 sock_sendall(PySocketSockObject
*s
, PyObject
*args
)
2255 int len
, n
= 0, flags
= 0, timeout
;
2257 if (!PyArg_ParseTuple(args
, "s#|i:sendall", &buf
, &len
, &flags
))
2260 Py_BEGIN_ALLOW_THREADS
2262 timeout
= internal_select(s
, 1);
2265 n
= send(s
->sock_fd
, buf
, len
, flags
);
2271 Py_END_ALLOW_THREADS
2274 PyErr_SetString(socket_timeout
, "timed out");
2278 return s
->errorhandler();
2284 PyDoc_STRVAR(sendall_doc
,
2285 "sendall(data[, flags])\n\
2287 Send a data string to the socket. For the optional flags\n\
2288 argument, see the Unix manual. This calls send() repeatedly\n\
2289 until all data is sent. If an error occurs, it's impossible\n\
2290 to tell how much data has been sent.");
2293 /* s.sendto(data, [flags,] sockaddr) method */
2296 sock_sendto(PySocketSockObject
*s
, PyObject
*args
)
2300 struct sockaddr
*addr
;
2301 int addrlen
, len
, n
= 0, flags
, timeout
;
2304 if (!PyArg_ParseTuple(args
, "s#O:sendto", &buf
, &len
, &addro
)) {
2306 if (!PyArg_ParseTuple(args
, "s#iO:sendto",
2307 &buf
, &len
, &flags
, &addro
))
2311 if (!getsockaddrarg(s
, addro
, &addr
, &addrlen
))
2314 Py_BEGIN_ALLOW_THREADS
2315 timeout
= internal_select(s
, 1);
2317 n
= sendto(s
->sock_fd
, buf
, len
, flags
, addr
, addrlen
);
2318 Py_END_ALLOW_THREADS
2321 PyErr_SetString(socket_timeout
, "timed out");
2325 return s
->errorhandler();
2326 return PyInt_FromLong((long)n
);
2329 PyDoc_STRVAR(sendto_doc
,
2330 "sendto(data[, flags], address) -> count\n\
2332 Like send(data, flags) but allows specifying the destination address.\n\
2333 For IP sockets, the address is a pair (hostaddr, port).");
2336 /* s.shutdown(how) method */
2339 sock_shutdown(PySocketSockObject
*s
, PyObject
*arg
)
2344 how
= PyInt_AsLong(arg
);
2345 if (how
== -1 && PyErr_Occurred())
2347 Py_BEGIN_ALLOW_THREADS
2348 res
= shutdown(s
->sock_fd
, how
);
2349 Py_END_ALLOW_THREADS
2351 return s
->errorhandler();
2356 PyDoc_STRVAR(shutdown_doc
,
2359 Shut down the reading side of the socket (flag == SHUT_RD), the writing side\n\
2360 of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).");
2363 /* List of methods for socket objects */
2365 static PyMethodDef sock_methods
[] = {
2366 {"accept", (PyCFunction
)sock_accept
, METH_NOARGS
,
2368 {"bind", (PyCFunction
)sock_bind
, METH_O
,
2370 {"close", (PyCFunction
)sock_close
, METH_NOARGS
,
2372 {"connect", (PyCFunction
)sock_connect
, METH_O
,
2374 {"connect_ex", (PyCFunction
)sock_connect_ex
, METH_O
,
2377 {"dup", (PyCFunction
)sock_dup
, METH_NOARGS
,
2380 {"fileno", (PyCFunction
)sock_fileno
, METH_NOARGS
,
2382 #ifdef HAVE_GETPEERNAME
2383 {"getpeername", (PyCFunction
)sock_getpeername
,
2384 METH_NOARGS
, getpeername_doc
},
2386 {"getsockname", (PyCFunction
)sock_getsockname
,
2387 METH_NOARGS
, getsockname_doc
},
2388 {"getsockopt", (PyCFunction
)sock_getsockopt
, METH_VARARGS
,
2390 {"listen", (PyCFunction
)sock_listen
, METH_O
,
2393 {"makefile", (PyCFunction
)sock_makefile
, METH_VARARGS
,
2396 {"recv", (PyCFunction
)sock_recv
, METH_VARARGS
,
2398 {"recvfrom", (PyCFunction
)sock_recvfrom
, METH_VARARGS
,
2400 {"send", (PyCFunction
)sock_send
, METH_VARARGS
,
2402 {"sendall", (PyCFunction
)sock_sendall
, METH_VARARGS
,
2404 {"sendto", (PyCFunction
)sock_sendto
, METH_VARARGS
,
2406 {"setblocking", (PyCFunction
)sock_setblocking
, METH_O
,
2408 {"settimeout", (PyCFunction
)sock_settimeout
, METH_O
,
2410 {"gettimeout", (PyCFunction
)sock_gettimeout
, METH_NOARGS
,
2412 {"setsockopt", (PyCFunction
)sock_setsockopt
, METH_VARARGS
,
2414 {"shutdown", (PyCFunction
)sock_shutdown
, METH_O
,
2417 {"sleeptaskw", (PyCFunction
)sock_sleeptaskw
, METH_O
,
2420 {NULL
, NULL
} /* sentinel */
2424 /* Deallocate a socket object in response to the last Py_DECREF().
2425 First close the file description. */
2428 sock_dealloc(PySocketSockObject
*s
)
2430 if (s
->sock_fd
!= -1)
2431 (void) SOCKETCLOSE(s
->sock_fd
);
2432 s
->ob_type
->tp_free((PyObject
*)s
);
2437 sock_repr(PySocketSockObject
*s
)
2440 #if SIZEOF_SOCKET_T > SIZEOF_LONG
2441 if (s
->sock_fd
> LONG_MAX
) {
2442 /* this can occur on Win64, and actually there is a special
2443 ugly printf formatter for decimal pointer length integer
2444 printing, only bother if necessary*/
2445 PyErr_SetString(PyExc_OverflowError
,
2446 "no printf formatter to display "
2447 "the socket descriptor in decimal");
2453 "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
2454 (long)s
->sock_fd
, s
->sock_family
,
2457 return PyString_FromString(buf
);
2461 /* Create a new, uninitialized socket object. */
2464 sock_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
2468 new = type
->tp_alloc(type
, 0);
2470 ((PySocketSockObject
*)new)->sock_fd
= -1;
2471 ((PySocketSockObject
*)new)->sock_timeout
= -1.0;
2472 ((PySocketSockObject
*)new)->errorhandler
= &set_error
;
2478 /* Initialize a new socket object. */
2482 sock_initobj(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
2484 PySocketSockObject
*s
= (PySocketSockObject
*)self
;
2486 int family
= AF_INET
, type
= SOCK_STREAM
, proto
= 0;
2487 static char *keywords
[] = {"family", "type", "proto", 0};
2489 if (!PyArg_ParseTupleAndKeywords(args
, kwds
,
2490 "|iii:socket", keywords
,
2491 &family
, &type
, &proto
))
2494 Py_BEGIN_ALLOW_THREADS
2495 fd
= socket(family
, type
, proto
);
2496 Py_END_ALLOW_THREADS
2499 if (fd
== INVALID_SOCKET
)
2507 init_sockobject(s
, fd
, family
, type
, proto
);
2514 /* Type object for socket objects. */
2516 static PyTypeObject sock_type
= {
2517 PyObject_HEAD_INIT(0) /* Must fill in type value later */
2519 "_socket.socket", /* tp_name */
2520 sizeof(PySocketSockObject
), /* tp_basicsize */
2521 0, /* tp_itemsize */
2522 (destructor
)sock_dealloc
, /* tp_dealloc */
2527 (reprfunc
)sock_repr
, /* tp_repr */
2528 0, /* tp_as_number */
2529 0, /* tp_as_sequence */
2530 0, /* tp_as_mapping */
2534 PyObject_GenericGetAttr
, /* tp_getattro */
2535 0, /* tp_setattro */
2536 0, /* tp_as_buffer */
2537 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
2538 sock_doc
, /* tp_doc */
2539 0, /* tp_traverse */
2541 0, /* tp_richcompare */
2542 0, /* tp_weaklistoffset */
2544 0, /* tp_iternext */
2545 sock_methods
, /* tp_methods */
2550 0, /* tp_descr_get */
2551 0, /* tp_descr_set */
2552 0, /* tp_dictoffset */
2553 sock_initobj
, /* tp_init */
2554 PyType_GenericAlloc
, /* tp_alloc */
2555 sock_new
, /* tp_new */
2556 PyObject_Del
, /* tp_free */
2560 /* Python interface to gethostname(). */
2564 socket_gethostname(PyObject
*self
, PyObject
*args
)
2568 if (!PyArg_ParseTuple(args
, ":gethostname"))
2570 Py_BEGIN_ALLOW_THREADS
2571 res
= gethostname(buf
, (int) sizeof buf
- 1);
2572 Py_END_ALLOW_THREADS
2575 buf
[sizeof buf
- 1] = '\0';
2576 return PyString_FromString(buf
);
2579 PyDoc_STRVAR(gethostname_doc
,
2580 "gethostname() -> string\n\
2582 Return the current host name.");
2585 /* Python interface to gethostbyname(name). */
2589 socket_gethostbyname(PyObject
*self
, PyObject
*args
)
2593 struct sockaddr_storage addrbuf
;
2595 struct sockaddr_in addrbuf
;
2598 if (!PyArg_ParseTuple(args
, "s:gethostbyname", &name
))
2600 if (setipaddr(name
, (struct sockaddr
*)&addrbuf
, sizeof(addrbuf
), AF_INET
) < 0)
2602 return makeipaddr((struct sockaddr
*)&addrbuf
,
2603 sizeof(struct sockaddr_in
));
2606 PyDoc_STRVAR(gethostbyname_doc
,
2607 "gethostbyname(host) -> address\n\
2609 Return the IP address (a string of the form '255.255.255.255') for a host.");
2612 /* Convenience function common to gethostbyname_ex and gethostbyaddr */
2615 gethost_common(struct hostent
*h
, struct sockaddr
*addr
, int alen
, int af
)
2618 PyObject
*rtn_tuple
= (PyObject
*)NULL
;
2619 PyObject
*name_list
= (PyObject
*)NULL
;
2620 PyObject
*addr_list
= (PyObject
*)NULL
;
2624 /* Let's get real error message to return */
2626 set_herror(h_errno
);
2628 PyErr_SetString(socket_error
, "host not found");
2633 if (h
->h_addrtype
!= af
) {
2634 #ifdef HAVE_STRERROR
2635 /* Let's get real error message to return */
2636 PyErr_SetString(socket_error
,
2637 (char *)strerror(EAFNOSUPPORT
));
2641 "Address family not supported by protocol family");
2649 if (alen
< sizeof(struct sockaddr_in
))
2655 if (alen
< sizeof(struct sockaddr_in6
))
2662 if ((name_list
= PyList_New(0)) == NULL
)
2665 if ((addr_list
= PyList_New(0)) == NULL
)
2668 for (pch
= h
->h_aliases
; *pch
!= NULL
; pch
++) {
2670 tmp
= PyString_FromString(*pch
);
2674 status
= PyList_Append(name_list
, tmp
);
2681 for (pch
= h
->h_addr_list
; *pch
!= NULL
; pch
++) {
2688 struct sockaddr_in sin
;
2689 memset(&sin
, 0, sizeof(sin
));
2690 sin
.sin_family
= af
;
2691 #ifdef HAVE_SOCKADDR_SA_LEN
2692 sin
.sin_len
= sizeof(sin
);
2694 memcpy(&sin
.sin_addr
, *pch
, sizeof(sin
.sin_addr
));
2695 tmp
= makeipaddr((struct sockaddr
*)&sin
, sizeof(sin
));
2697 if (pch
== h
->h_addr_list
&& alen
>= sizeof(sin
))
2698 memcpy((char *) addr
, &sin
, sizeof(sin
));
2705 struct sockaddr_in6 sin6
;
2706 memset(&sin6
, 0, sizeof(sin6
));
2707 sin6
.sin6_family
= af
;
2708 #ifdef HAVE_SOCKADDR_SA_LEN
2709 sin6
.sin6_len
= sizeof(sin6
);
2711 memcpy(&sin6
.sin6_addr
, *pch
, sizeof(sin6
.sin6_addr
));
2712 tmp
= makeipaddr((struct sockaddr
*)&sin6
,
2715 if (pch
== h
->h_addr_list
&& alen
>= sizeof(sin6
))
2716 memcpy((char *) addr
, &sin6
, sizeof(sin6
));
2721 default: /* can't happen */
2722 PyErr_SetString(socket_error
,
2723 "unsupported address family");
2730 status
= PyList_Append(addr_list
, tmp
);
2737 rtn_tuple
= Py_BuildValue("sOO", h
->h_name
, name_list
, addr_list
);
2740 Py_XDECREF(name_list
);
2741 Py_XDECREF(addr_list
);
2746 /* Python interface to gethostbyname_ex(name). */
2750 socket_gethostbyname_ex(PyObject
*self
, PyObject
*args
)
2755 struct sockaddr_storage addr
;
2757 struct sockaddr_in addr
;
2759 struct sockaddr
*sa
;
2761 #ifdef HAVE_GETHOSTBYNAME_R
2762 struct hostent hp_allocated
;
2763 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
2764 struct hostent_data data
;
2767 int buf_len
= (sizeof buf
) - 1;
2770 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2773 #endif /* HAVE_GETHOSTBYNAME_R */
2775 if (!PyArg_ParseTuple(args
, "s:gethostbyname_ex", &name
))
2777 if (setipaddr(name
, (struct sockaddr
*)&addr
, sizeof(addr
), AF_INET
) < 0)
2779 Py_BEGIN_ALLOW_THREADS
2780 #ifdef HAVE_GETHOSTBYNAME_R
2781 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2782 result
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
,
2784 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
2785 h
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
, &errnop
);
2786 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
2787 memset((void *) &data
, '\0', sizeof(data
));
2788 result
= gethostbyname_r(name
, &hp_allocated
, &data
);
2789 h
= (result
!= 0) ? NULL
: &hp_allocated
;
2791 #else /* not HAVE_GETHOSTBYNAME_R */
2792 #ifdef USE_GETHOSTBYNAME_LOCK
2793 PyThread_acquire_lock(netdb_lock
, 1);
2795 h
= gethostbyname(name
);
2796 #endif /* HAVE_GETHOSTBYNAME_R */
2797 Py_END_ALLOW_THREADS
2798 /* Some C libraries would require addr.__ss_family instead of
2800 Therefore, we cast the sockaddr_storage into sockaddr to
2801 access sa_family. */
2802 sa
= (struct sockaddr
*)&addr
;
2803 ret
= gethost_common(h
, (struct sockaddr
*)&addr
, sizeof(addr
),
2805 #ifdef USE_GETHOSTBYNAME_LOCK
2806 PyThread_release_lock(netdb_lock
);
2811 PyDoc_STRVAR(ghbn_ex_doc
,
2812 "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
2814 Return the true host name, a list of aliases, and a list of IP addresses,\n\
2815 for a host. The host argument is a string giving a host name or IP number.");
2818 /* Python interface to gethostbyaddr(IP). */
2822 socket_gethostbyaddr(PyObject
*self
, PyObject
*args
)
2825 struct sockaddr_storage addr
;
2827 struct sockaddr_in addr
;
2829 struct sockaddr
*sa
= (struct sockaddr
*)&addr
;
2833 #ifdef HAVE_GETHOSTBYNAME_R
2834 struct hostent hp_allocated
;
2835 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
2836 struct hostent_data data
;
2839 int buf_len
= (sizeof buf
) - 1;
2842 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2845 #endif /* HAVE_GETHOSTBYNAME_R */
2850 if (!PyArg_ParseTuple(args
, "s:gethostbyaddr", &ip_num
))
2853 if (setipaddr(ip_num
, sa
, sizeof(addr
), af
) < 0)
2860 ap
= (char *)&((struct sockaddr_in
*)sa
)->sin_addr
;
2861 al
= sizeof(((struct sockaddr_in
*)sa
)->sin_addr
);
2865 ap
= (char *)&((struct sockaddr_in6
*)sa
)->sin6_addr
;
2866 al
= sizeof(((struct sockaddr_in6
*)sa
)->sin6_addr
);
2870 PyErr_SetString(socket_error
, "unsupported address family");
2873 Py_BEGIN_ALLOW_THREADS
2874 #ifdef HAVE_GETHOSTBYNAME_R
2875 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2876 result
= gethostbyaddr_r(ap
, al
, af
,
2877 &hp_allocated
, buf
, buf_len
,
2879 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
2880 h
= gethostbyaddr_r(ap
, al
, af
,
2881 &hp_allocated
, buf
, buf_len
, &errnop
);
2882 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
2883 memset((void *) &data
, '\0', sizeof(data
));
2884 result
= gethostbyaddr_r(ap
, al
, af
, &hp_allocated
, &data
);
2885 h
= (result
!= 0) ? NULL
: &hp_allocated
;
2887 #else /* not HAVE_GETHOSTBYNAME_R */
2888 #ifdef USE_GETHOSTBYNAME_LOCK
2889 PyThread_acquire_lock(netdb_lock
, 1);
2891 h
= gethostbyaddr(ap
, al
, af
);
2892 #endif /* HAVE_GETHOSTBYNAME_R */
2893 Py_END_ALLOW_THREADS
2894 ret
= gethost_common(h
, (struct sockaddr
*)&addr
, sizeof(addr
), af
);
2895 #ifdef USE_GETHOSTBYNAME_LOCK
2896 PyThread_release_lock(netdb_lock
);
2901 PyDoc_STRVAR(gethostbyaddr_doc
,
2902 "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
2904 Return the true host name, a list of aliases, and a list of IP addresses,\n\
2905 for a host. The host argument is a string giving a host name or IP number.");
2908 /* Python interface to getservbyname(name).
2909 This only returns the port number, since the other info is already
2910 known or not useful (like the list of aliases). */
2914 socket_getservbyname(PyObject
*self
, PyObject
*args
)
2916 char *name
, *proto
=NULL
;
2918 if (!PyArg_ParseTuple(args
, "s|s:getservbyname", &name
, &proto
))
2920 Py_BEGIN_ALLOW_THREADS
2921 sp
= getservbyname(name
, proto
);
2922 Py_END_ALLOW_THREADS
2924 PyErr_SetString(socket_error
, "service/proto not found");
2927 return PyInt_FromLong((long) ntohs(sp
->s_port
));
2930 PyDoc_STRVAR(getservbyname_doc
,
2931 "getservbyname(servicename[, protocolname]) -> integer\n\
2933 Return a port number from a service name and protocol name.\n\
2934 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
2935 otherwise any protocol will match.");
2938 /* Python interface to getservbyport(port).
2939 This only returns the service name, since the other info is already
2940 known or not useful (like the list of aliases). */
2944 socket_getservbyport(PyObject
*self
, PyObject
*args
)
2946 unsigned short port
;
2949 if (!PyArg_ParseTuple(args
, "H|s:getservbyport", &port
, &proto
))
2951 Py_BEGIN_ALLOW_THREADS
2952 sp
= getservbyport(htons(port
), proto
);
2953 Py_END_ALLOW_THREADS
2955 PyErr_SetString(socket_error
, "port/proto not found");
2958 return PyString_FromString(sp
->s_name
);
2961 PyDoc_STRVAR(getservbyport_doc
,
2962 "getservbyport(port[, protocolname]) -> string\n\
2964 Return the service name from a port number and protocol name.\n\
2965 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
2966 otherwise any protocol will match.");
2968 /* Python interface to getprotobyname(name).
2969 This only returns the protocol number, since the other info is
2970 already known or not useful (like the list of aliases). */
2974 socket_getprotobyname(PyObject
*self
, PyObject
*args
)
2977 struct protoent
*sp
;
2979 /* Not available in BeOS yet. - [cjh] */
2980 PyErr_SetString(socket_error
, "getprotobyname not supported");
2983 if (!PyArg_ParseTuple(args
, "s:getprotobyname", &name
))
2985 Py_BEGIN_ALLOW_THREADS
2986 sp
= getprotobyname(name
);
2987 Py_END_ALLOW_THREADS
2989 PyErr_SetString(socket_error
, "protocol not found");
2992 return PyInt_FromLong((long) sp
->p_proto
);
2996 PyDoc_STRVAR(getprotobyname_doc
,
2997 "getprotobyname(name) -> integer\n\
2999 Return the protocol number for the named protocol. (Rarely used.)");
3002 #ifdef HAVE_SOCKETPAIR
3003 /* Create a pair of sockets using the socketpair() function.
3004 Arguments as for socket() except the default family is AF_UNIX if
3005 defined on the platform; otherwise, the default is AF_INET. */
3009 socket_socketpair(PyObject
*self
, PyObject
*args
)
3011 PySocketSockObject
*s0
= NULL
, *s1
= NULL
;
3013 int family
, type
= SOCK_STREAM
, proto
= 0;
3014 PyObject
*res
= NULL
;
3016 #if defined(AF_UNIX)
3021 if (!PyArg_ParseTuple(args
, "|iii:socketpair",
3022 &family
, &type
, &proto
))
3024 /* Create a pair of socket fds */
3025 if (socketpair(family
, type
, proto
, sv
) < 0)
3027 s0
= new_sockobject(sv
[0], family
, type
, proto
);
3030 s1
= new_sockobject(sv
[1], family
, type
, proto
);
3033 res
= PyTuple_Pack(2, s0
, s1
);
3047 PyDoc_STRVAR(socketpair_doc
,
3048 "socketpair([family[, type[, proto]]]) -> (socket object, socket object)\n\
3050 Create a pair of socket objects from the sockets returned by the platform\n\
3051 socketpair() function.\n\
3052 The arguments are the same as for socket() except the default family is\n\
3053 AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");
3055 #endif /* HAVE_SOCKETPAIR */
3059 /* Create a socket object from a numeric file description.
3060 Useful e.g. if stdin is a socket.
3061 Additional arguments as for socket(). */
3065 socket_fromfd(PyObject
*self
, PyObject
*args
)
3067 PySocketSockObject
*s
;
3069 int family
, type
, proto
= 0;
3070 if (!PyArg_ParseTuple(args
, "iii|i:fromfd",
3071 &fd
, &family
, &type
, &proto
))
3073 /* Dup the fd so it and the socket can be closed independently */
3077 s
= new_sockobject(fd
, family
, type
, proto
);
3078 return (PyObject
*) s
;
3081 PyDoc_STRVAR(fromfd_doc
,
3082 "fromfd(fd, family, type[, proto]) -> socket object\n\
3084 Create a socket object from the given file descriptor.\n\
3085 The remaining arguments are the same as for socket().");
3091 socket_ntohs(PyObject
*self
, PyObject
*args
)
3095 if (!PyArg_ParseTuple(args
, "i:ntohs", &x1
)) {
3098 x2
= (int)ntohs((short)x1
);
3099 return PyInt_FromLong(x2
);
3102 PyDoc_STRVAR(ntohs_doc
,
3103 "ntohs(integer) -> integer\n\
3105 Convert a 16-bit integer from network to host byte order.");
3109 socket_ntohl(PyObject
*self
, PyObject
*arg
)
3113 if (PyInt_Check(arg
)) {
3114 x
= PyInt_AS_LONG(arg
);
3115 if (x
== (unsigned long) -1 && PyErr_Occurred())
3118 else if (PyLong_Check(arg
)) {
3119 x
= PyLong_AsUnsignedLong(arg
);
3120 if (x
== (unsigned long) -1 && PyErr_Occurred())
3125 /* only want the trailing 32 bits */
3126 y
= x
& 0xFFFFFFFFUL
;
3128 return PyErr_Format(PyExc_OverflowError
,
3129 "long int larger than 32 bits");
3135 return PyErr_Format(PyExc_TypeError
,
3136 "expected int/long, %s found",
3137 arg
->ob_type
->tp_name
);
3138 if (x
== (unsigned long) -1 && PyErr_Occurred())
3140 return PyInt_FromLong(ntohl(x
));
3143 PyDoc_STRVAR(ntohl_doc
,
3144 "ntohl(integer) -> integer\n\
3146 Convert a 32-bit integer from network to host byte order.");
3150 socket_htons(PyObject
*self
, PyObject
*args
)
3154 if (!PyArg_ParseTuple(args
, "i:htons", &x1
)) {
3157 x2
= (int)htons((short)x1
);
3158 return PyInt_FromLong(x2
);
3161 PyDoc_STRVAR(htons_doc
,
3162 "htons(integer) -> integer\n\
3164 Convert a 16-bit integer from host to network byte order.");
3168 socket_htonl(PyObject
*self
, PyObject
*arg
)
3172 if (PyInt_Check(arg
)) {
3173 x
= PyInt_AS_LONG(arg
);
3174 if (x
== (unsigned long) -1 && PyErr_Occurred())
3177 else if (PyLong_Check(arg
)) {
3178 x
= PyLong_AsUnsignedLong(arg
);
3179 if (x
== (unsigned long) -1 && PyErr_Occurred())
3184 /* only want the trailing 32 bits */
3185 y
= x
& 0xFFFFFFFFUL
;
3187 return PyErr_Format(PyExc_OverflowError
,
3188 "long int larger than 32 bits");
3194 return PyErr_Format(PyExc_TypeError
,
3195 "expected int/long, %s found",
3196 arg
->ob_type
->tp_name
);
3197 return PyInt_FromLong(htonl(x
));
3200 PyDoc_STRVAR(htonl_doc
,
3201 "htonl(integer) -> integer\n\
3203 Convert a 32-bit integer from host to network byte order.");
3205 /* socket.inet_aton() and socket.inet_ntoa() functions. */
3207 PyDoc_STRVAR(inet_aton_doc
,
3208 "inet_aton(string) -> packed 32-bit IP representation\n\
3210 Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
3211 binary format used in low-level network functions.");
3214 socket_inet_aton(PyObject
*self
, PyObject
*args
)
3217 #define INADDR_NONE (-1)
3219 #ifdef HAVE_INET_ATON
3222 /* Have to use inet_addr() instead */
3223 unsigned long packed_addr
;
3227 if (!PyArg_ParseTuple(args
, "s:inet_aton", &ip_addr
))
3231 #ifdef HAVE_INET_ATON
3232 if (inet_aton(ip_addr
, &buf
))
3233 return PyString_FromStringAndSize((char *)(&buf
),
3236 PyErr_SetString(socket_error
,
3237 "illegal IP address string passed to inet_aton");
3240 #else /* ! HAVE_INET_ATON */
3241 /* XXX Problem here: inet_aton('255.255.255.255') raises
3242 an exception while it should be a valid address. */
3243 packed_addr
= inet_addr(ip_addr
);
3245 if (packed_addr
== INADDR_NONE
) { /* invalid address */
3246 PyErr_SetString(socket_error
,
3247 "illegal IP address string passed to inet_aton");
3250 return PyString_FromStringAndSize((char *) &packed_addr
,
3251 sizeof(packed_addr
));
3255 PyDoc_STRVAR(inet_ntoa_doc
,
3256 "inet_ntoa(packed_ip) -> ip_address_string\n\
3258 Convert an IP address from 32-bit packed binary format to string format");
3261 socket_inet_ntoa(PyObject
*self
, PyObject
*args
)
3265 struct in_addr packed_addr
;
3267 if (!PyArg_ParseTuple(args
, "s#:inet_ntoa", &packed_str
, &addr_len
)) {
3271 if (addr_len
!= sizeof(packed_addr
)) {
3272 PyErr_SetString(socket_error
,
3273 "packed IP wrong length for inet_ntoa");
3277 memcpy(&packed_addr
, packed_str
, addr_len
);
3279 return PyString_FromString(inet_ntoa(packed_addr
));
3282 #ifdef HAVE_INET_PTON
3284 PyDoc_STRVAR(inet_pton_doc
,
3285 "inet_pton(af, ip) -> packed IP address string\n\
3287 Convert an IP address from string format to a packed string suitable\n\
3288 for use with low-level network functions.");
3291 socket_inet_pton(PyObject
*self
, PyObject
*args
)
3297 char packed
[MAX(sizeof(struct in_addr
), sizeof(struct in6_addr
))];
3299 char packed
[sizeof(struct in_addr
)];
3301 if (!PyArg_ParseTuple(args
, "is:inet_pton", &af
, &ip
)) {
3305 #if !defined(ENABLE_IPV6) && defined(AF_INET6)
3306 if(af
== AF_INET6
) {
3307 PyErr_SetString(socket_error
,
3308 "can't use AF_INET6, IPv6 is disabled");
3313 retval
= inet_pton(af
, ip
, packed
);
3315 PyErr_SetFromErrno(socket_error
);
3317 } else if (retval
== 0) {
3318 PyErr_SetString(socket_error
,
3319 "illegal IP address string passed to inet_pton");
3321 } else if (af
== AF_INET
) {
3322 return PyString_FromStringAndSize(packed
,
3323 sizeof(struct in_addr
));
3325 } else if (af
== AF_INET6
) {
3326 return PyString_FromStringAndSize(packed
,
3327 sizeof(struct in6_addr
));
3330 PyErr_SetString(socket_error
, "unknown address family");
3335 PyDoc_STRVAR(inet_ntop_doc
,
3336 "inet_ntop(af, packed_ip) -> string formatted IP address\n\
3338 Convert a packed IP address of the given family to string format.");
3341 socket_inet_ntop(PyObject
*self
, PyObject
*args
)
3348 char ip
[MAX(INET_ADDRSTRLEN
, INET6_ADDRSTRLEN
) + 1];
3350 char ip
[INET_ADDRSTRLEN
+ 1];
3353 /* Guarantee NUL-termination for PyString_FromString() below */
3354 memset((void *) &ip
[0], '\0', sizeof(ip
));
3356 if (!PyArg_ParseTuple(args
, "is#:inet_ntop", &af
, &packed
, &len
)) {
3360 if (af
== AF_INET
) {
3361 if (len
!= sizeof(struct in_addr
)) {
3362 PyErr_SetString(PyExc_ValueError
,
3363 "invalid length of packed IP address string");
3367 } else if (af
== AF_INET6
) {
3368 if (len
!= sizeof(struct in6_addr
)) {
3369 PyErr_SetString(PyExc_ValueError
,
3370 "invalid length of packed IP address string");
3375 PyErr_Format(PyExc_ValueError
,
3376 "unknown address family %d", af
);
3380 retval
= inet_ntop(af
, packed
, ip
, sizeof(ip
));
3382 PyErr_SetFromErrno(socket_error
);
3385 return PyString_FromString(retval
);
3389 PyErr_SetString(PyExc_RuntimeError
, "invalid handling of inet_ntop");
3393 #endif /* HAVE_INET_PTON */
3395 /* Python interface to getaddrinfo(host, port). */
3399 socket_getaddrinfo(PyObject
*self
, PyObject
*args
)
3401 struct addrinfo hints
, *res
;
3402 struct addrinfo
*res0
= NULL
;
3403 PyObject
*hobj
= NULL
;
3404 PyObject
*pobj
= (PyObject
*)NULL
;
3407 int family
, socktype
, protocol
, flags
;
3409 PyObject
*all
= (PyObject
*)NULL
;
3410 PyObject
*single
= (PyObject
*)NULL
;
3411 PyObject
*idna
= NULL
;
3413 family
= socktype
= protocol
= flags
= 0;
3415 if (!PyArg_ParseTuple(args
, "OO|iiii:getaddrinfo",
3416 &hobj
, &pobj
, &family
, &socktype
,
3417 &protocol
, &flags
)) {
3420 if (hobj
== Py_None
) {
3422 } else if (PyUnicode_Check(hobj
)) {
3423 idna
= PyObject_CallMethod(hobj
, "encode", "s", "idna");
3426 hptr
= PyString_AsString(idna
);
3427 } else if (PyString_Check(hobj
)) {
3428 hptr
= PyString_AsString(hobj
);
3430 PyErr_SetString(PyExc_TypeError
,
3431 "getaddrinfo() argument 1 must be string or None");
3434 if (PyInt_Check(pobj
)) {
3435 PyOS_snprintf(pbuf
, sizeof(pbuf
), "%ld", PyInt_AsLong(pobj
));
3437 } else if (PyString_Check(pobj
)) {
3438 pptr
= PyString_AsString(pobj
);
3439 } else if (pobj
== Py_None
) {
3440 pptr
= (char *)NULL
;
3442 PyErr_SetString(socket_error
, "Int or String expected");
3445 memset(&hints
, 0, sizeof(hints
));
3446 hints
.ai_family
= family
;
3447 hints
.ai_socktype
= socktype
;
3448 hints
.ai_protocol
= protocol
;
3449 hints
.ai_flags
= flags
;
3450 Py_BEGIN_ALLOW_THREADS
3451 ACQUIRE_GETADDRINFO_LOCK
3452 error
= getaddrinfo(hptr
, pptr
, &hints
, &res0
);
3453 Py_END_ALLOW_THREADS
3454 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
3456 set_gaierror(error
);
3460 if ((all
= PyList_New(0)) == NULL
)
3462 for (res
= res0
; res
; res
= res
->ai_next
) {
3464 makesockaddr(-1, res
->ai_addr
, res
->ai_addrlen
, protocol
);
3467 single
= Py_BuildValue("iiisO", res
->ai_family
,
3468 res
->ai_socktype
, res
->ai_protocol
,
3469 res
->ai_canonname
? res
->ai_canonname
: "",
3475 if (PyList_Append(all
, single
))
3489 return (PyObject
*)NULL
;
3492 PyDoc_STRVAR(getaddrinfo_doc
,
3493 "getaddrinfo(host, port [, family, socktype, proto, flags])\n\
3494 -> list of (family, socktype, proto, canonname, sockaddr)\n\
3496 Resolve host and port into addrinfo struct.");
3498 /* Python interface to getnameinfo(sa, flags). */
3502 socket_getnameinfo(PyObject
*self
, PyObject
*args
)
3504 PyObject
*sa
= (PyObject
*)NULL
;
3507 int port
, flowinfo
, scope_id
;
3508 char hbuf
[NI_MAXHOST
], pbuf
[NI_MAXSERV
];
3509 struct addrinfo hints
, *res
= NULL
;
3511 PyObject
*ret
= (PyObject
*)NULL
;
3513 flags
= flowinfo
= scope_id
= 0;
3514 if (!PyArg_ParseTuple(args
, "Oi:getnameinfo", &sa
, &flags
))
3516 if (!PyArg_ParseTuple(sa
, "si|ii",
3517 &hostp
, &port
, &flowinfo
, &scope_id
))
3519 PyOS_snprintf(pbuf
, sizeof(pbuf
), "%d", port
);
3520 memset(&hints
, 0, sizeof(hints
));
3521 hints
.ai_family
= AF_UNSPEC
;
3522 hints
.ai_socktype
= SOCK_DGRAM
; /* make numeric port happy */
3523 Py_BEGIN_ALLOW_THREADS
3524 ACQUIRE_GETADDRINFO_LOCK
3525 error
= getaddrinfo(hostp
, pbuf
, &hints
, &res
);
3526 Py_END_ALLOW_THREADS
3527 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
3529 set_gaierror(error
);
3533 PyErr_SetString(socket_error
,
3534 "sockaddr resolved to multiple addresses");
3537 switch (res
->ai_family
) {
3542 if (PyArg_ParseTuple(sa
, "si", &t1
, &t2
) == 0) {
3543 PyErr_SetString(socket_error
,
3544 "IPv4 sockaddr must be 2 tuple");
3552 struct sockaddr_in6
*sin6
;
3553 sin6
= (struct sockaddr_in6
*)res
->ai_addr
;
3554 sin6
->sin6_flowinfo
= flowinfo
;
3555 sin6
->sin6_scope_id
= scope_id
;
3560 error
= getnameinfo(res
->ai_addr
, res
->ai_addrlen
,
3561 hbuf
, sizeof(hbuf
), pbuf
, sizeof(pbuf
), flags
);
3563 set_gaierror(error
);
3566 ret
= Py_BuildValue("ss", hbuf
, pbuf
);
3574 PyDoc_STRVAR(getnameinfo_doc
,
3575 "getnameinfo(sockaddr, flags) --> (host, port)\n\
3577 Get host and port for a sockaddr.");
3580 /* Python API to getting and setting the default timeout value. */
3583 socket_getdefaulttimeout(PyObject
*self
)
3585 if (defaulttimeout
< 0.0) {
3590 return PyFloat_FromDouble(defaulttimeout
);
3593 PyDoc_STRVAR(getdefaulttimeout_doc
,
3594 "getdefaulttimeout() -> timeout\n\
3596 Returns the default timeout in floating seconds for new socket objects.\n\
3597 A value of None indicates that new socket objects have no timeout.\n\
3598 When the socket module is first imported, the default is None.");
3601 socket_setdefaulttimeout(PyObject
*self
, PyObject
*arg
)
3608 timeout
= PyFloat_AsDouble(arg
);
3609 if (timeout
< 0.0) {
3610 if (!PyErr_Occurred())
3611 PyErr_SetString(PyExc_ValueError
,
3612 "Timeout value out of range");
3617 defaulttimeout
= timeout
;
3623 PyDoc_STRVAR(setdefaulttimeout_doc
,
3624 "setdefaulttimeout(timeout)\n\
3626 Set the default timeout in floating seconds for new socket objects.\n\
3627 A value of None indicates that new socket objects have no timeout.\n\
3628 When the socket module is first imported, the default is None.");
3631 /* List of functions exported by this module. */
3633 static PyMethodDef socket_methods
[] = {
3634 {"gethostbyname", socket_gethostbyname
,
3635 METH_VARARGS
, gethostbyname_doc
},
3636 {"gethostbyname_ex", socket_gethostbyname_ex
,
3637 METH_VARARGS
, ghbn_ex_doc
},
3638 {"gethostbyaddr", socket_gethostbyaddr
,
3639 METH_VARARGS
, gethostbyaddr_doc
},
3640 {"gethostname", socket_gethostname
,
3641 METH_VARARGS
, gethostname_doc
},
3642 {"getservbyname", socket_getservbyname
,
3643 METH_VARARGS
, getservbyname_doc
},
3644 {"getservbyport", socket_getservbyport
,
3645 METH_VARARGS
, getservbyport_doc
},
3646 {"getprotobyname", socket_getprotobyname
,
3647 METH_VARARGS
,getprotobyname_doc
},
3649 {"fromfd", socket_fromfd
,
3650 METH_VARARGS
, fromfd_doc
},
3652 #ifdef HAVE_SOCKETPAIR
3653 {"socketpair", socket_socketpair
,
3654 METH_VARARGS
, socketpair_doc
},
3656 {"ntohs", socket_ntohs
,
3657 METH_VARARGS
, ntohs_doc
},
3658 {"ntohl", socket_ntohl
,
3660 {"htons", socket_htons
,
3661 METH_VARARGS
, htons_doc
},
3662 {"htonl", socket_htonl
,
3664 {"inet_aton", socket_inet_aton
,
3665 METH_VARARGS
, inet_aton_doc
},
3666 {"inet_ntoa", socket_inet_ntoa
,
3667 METH_VARARGS
, inet_ntoa_doc
},
3668 #ifdef HAVE_INET_PTON
3669 {"inet_pton", socket_inet_pton
,
3670 METH_VARARGS
, inet_pton_doc
},
3671 {"inet_ntop", socket_inet_ntop
,
3672 METH_VARARGS
, inet_ntop_doc
},
3674 {"getaddrinfo", socket_getaddrinfo
,
3675 METH_VARARGS
, getaddrinfo_doc
},
3676 {"getnameinfo", socket_getnameinfo
,
3677 METH_VARARGS
, getnameinfo_doc
},
3678 {"getdefaulttimeout", (PyCFunction
)socket_getdefaulttimeout
,
3679 METH_NOARGS
, getdefaulttimeout_doc
},
3680 {"setdefaulttimeout", socket_setdefaulttimeout
,
3681 METH_O
, setdefaulttimeout_doc
},
3682 {NULL
, NULL
} /* Sentinel */
3687 #define OS_INIT_DEFINED
3695 _kernel_swi(0x43380, &r
, &r
);
3696 taskwindow
= r
.r
[0];
3705 #define OS_INIT_DEFINED
3707 /* Additional initialization and cleanup for Windows */
3721 ret
= WSAStartup(0x0101, &WSAData
);
3723 case 0: /* No error */
3724 Py_AtExit(os_cleanup
);
3725 return 1; /* Success */
3726 case WSASYSNOTREADY
:
3727 PyErr_SetString(PyExc_ImportError
,
3728 "WSAStartup failed: network not ready");
3730 case WSAVERNOTSUPPORTED
:
3734 "WSAStartup failed: requested version not supported");
3737 PyOS_snprintf(buf
, sizeof(buf
),
3738 "WSAStartup failed: error code %d", ret
);
3739 PyErr_SetString(PyExc_ImportError
, buf
);
3742 return 0; /* Failure */
3745 #endif /* MS_WINDOWS */
3749 #define OS_INIT_DEFINED
3751 /* Additional initialization for OS/2 */
3758 int rc
= sock_init();
3761 return 1; /* Success */
3764 PyOS_snprintf(reason
, sizeof(reason
),
3765 "OS/2 TCP/IP Error# %d", sock_errno());
3766 PyErr_SetString(PyExc_ImportError
, reason
);
3768 return 0; /* Failure */
3770 /* No need to initialise sockets with GCC/EMX */
3771 return 1; /* Success */
3775 #endif /* PYOS_OS2 */
3778 #ifndef OS_INIT_DEFINED
3782 return 1; /* Success */
3787 /* C API table - always add new things to the end for binary
3790 PySocketModule_APIObject PySocketModuleAPI
=
3797 /* Initialize the _socket module.
3799 This module is actually called "_socket", and there's a wrapper
3800 "socket.py" which implements some additional functionality. On some
3801 platforms (e.g. Windows and OS/2), socket.py also implements a
3802 wrapper for the socket type that provides missing functionality such
3803 as makefile(), dup() and fromfd(). The import of "_socket" may fail
3804 with an ImportError exception if os-specific initialization fails.
3805 On Windows, this does WINSOCK initialization. When WINSOCK is
3806 initialized succesfully, a call to WSACleanup() is scheduled to be
3810 PyDoc_STRVAR(socket_doc
,
3811 "Implementation module for socket operations.\n\
3813 See the socket module for documentation.");
3818 PyObject
*m
, *has_ipv6
;
3823 sock_type
.ob_type
= &PyType_Type
;
3824 m
= Py_InitModule3(PySocket_MODULE_NAME
,
3828 socket_error
= PyErr_NewException("socket.error", NULL
, NULL
);
3829 if (socket_error
== NULL
)
3831 PySocketModuleAPI
.error
= socket_error
;
3832 Py_INCREF(socket_error
);
3833 PyModule_AddObject(m
, "error", socket_error
);
3834 socket_herror
= PyErr_NewException("socket.herror",
3835 socket_error
, NULL
);
3836 if (socket_herror
== NULL
)
3838 Py_INCREF(socket_herror
);
3839 PyModule_AddObject(m
, "herror", socket_herror
);
3840 socket_gaierror
= PyErr_NewException("socket.gaierror", socket_error
,
3842 if (socket_gaierror
== NULL
)
3844 Py_INCREF(socket_gaierror
);
3845 PyModule_AddObject(m
, "gaierror", socket_gaierror
);
3846 socket_timeout
= PyErr_NewException("socket.timeout",
3847 socket_error
, NULL
);
3848 if (socket_timeout
== NULL
)
3850 Py_INCREF(socket_timeout
);
3851 PyModule_AddObject(m
, "timeout", socket_timeout
);
3852 Py_INCREF((PyObject
*)&sock_type
);
3853 if (PyModule_AddObject(m
, "SocketType",
3854 (PyObject
*)&sock_type
) != 0)
3856 Py_INCREF((PyObject
*)&sock_type
);
3857 if (PyModule_AddObject(m
, "socket",
3858 (PyObject
*)&sock_type
) != 0)
3864 has_ipv6
= Py_False
;
3866 Py_INCREF(has_ipv6
);
3867 PyModule_AddObject(m
, "has_ipv6", has_ipv6
);
3870 if (PyModule_AddObject(m
, PySocket_CAPI_NAME
,
3871 PyCObject_FromVoidPtr((void *)&PySocketModuleAPI
, NULL
)
3875 /* Address families (we only support AF_INET and AF_UNIX) */
3877 PyModule_AddIntConstant(m
, "AF_UNSPEC", AF_UNSPEC
);
3879 PyModule_AddIntConstant(m
, "AF_INET", AF_INET
);
3881 PyModule_AddIntConstant(m
, "AF_INET6", AF_INET6
);
3882 #endif /* AF_INET6 */
3883 #if defined(AF_UNIX)
3884 PyModule_AddIntConstant(m
, "AF_UNIX", AF_UNIX
);
3885 #endif /* AF_UNIX */
3887 /* Amateur Radio AX.25 */
3888 PyModule_AddIntConstant(m
, "AF_AX25", AF_AX25
);
3891 PyModule_AddIntConstant(m
, "AF_IPX", AF_IPX
); /* Novell IPX */
3895 PyModule_AddIntConstant(m
, "AF_APPLETALK", AF_APPLETALK
);
3898 /* Amateur radio NetROM */
3899 PyModule_AddIntConstant(m
, "AF_NETROM", AF_NETROM
);
3902 /* Multiprotocol bridge */
3903 PyModule_AddIntConstant(m
, "AF_BRIDGE", AF_BRIDGE
);
3907 PyModule_AddIntConstant(m
, "AF_ATMPVC", AF_ATMPVC
);
3910 /* Reserved for Werner's ATM */
3911 PyModule_AddIntConstant(m
, "AF_AAL5", AF_AAL5
);
3914 /* Reserved for X.25 project */
3915 PyModule_AddIntConstant(m
, "AF_X25", AF_X25
);
3918 PyModule_AddIntConstant(m
, "AF_INET6", AF_INET6
); /* IP version 6 */
3921 /* Amateur Radio X.25 PLP */
3922 PyModule_AddIntConstant(m
, "AF_ROSE", AF_ROSE
);
3925 /* Reserved for DECnet project */
3926 PyModule_AddIntConstant(m
, "AF_DECnet", AF_DECnet
);
3929 /* Reserved for 802.2LLC project */
3930 PyModule_AddIntConstant(m
, "AF_NETBEUI", AF_NETBEUI
);
3933 /* Security callback pseudo AF */
3934 PyModule_AddIntConstant(m
, "AF_SECURITY", AF_SECURITY
);
3937 /* PF_KEY key management API */
3938 PyModule_AddIntConstant(m
, "AF_KEY", AF_KEY
);
3942 PyModule_AddIntConstant(m
, "AF_NETLINK", AF_NETLINK
);
3945 /* Alias to emulate 4.4BSD */
3946 PyModule_AddIntConstant(m
, "AF_ROUTE", AF_ROUTE
);
3950 PyModule_AddIntConstant(m
, "AF_ASH", AF_ASH
);
3954 PyModule_AddIntConstant(m
, "AF_ECONET", AF_ECONET
);
3958 PyModule_AddIntConstant(m
, "AF_ATMSVC", AF_ATMSVC
);
3961 /* Linux SNA Project (nutters!) */
3962 PyModule_AddIntConstant(m
, "AF_SNA", AF_SNA
);
3966 PyModule_AddIntConstant(m
, "AF_IRDA", AF_IRDA
);
3970 PyModule_AddIntConstant(m
, "AF_PPPOX", AF_PPPOX
);
3973 /* Wanpipe API Sockets */
3974 PyModule_AddIntConstant(m
, "AF_WANPIPE", AF_WANPIPE
);
3978 PyModule_AddIntConstant(m
, "AF_LLC", AF_LLC
);
3981 #ifdef USE_BLUETOOTH
3982 PyModule_AddIntConstant(m
, "AF_BLUETOOTH", AF_BLUETOOTH
);
3983 PyModule_AddIntConstant(m
, "BTPROTO_L2CAP", BTPROTO_L2CAP
);
3984 #if !defined(__FreeBSD__)
3985 PyModule_AddIntConstant(m
, "BTPROTO_SCO", BTPROTO_SCO
);
3987 PyModule_AddIntConstant(m
, "BTPROTO_RFCOMM", BTPROTO_RFCOMM
);
3988 PyModule_AddObject(m
, "BDADDR_ANY", Py_BuildValue("s", "00:00:00:00:00:00"));
3989 PyModule_AddObject(m
, "BDADDR_LOCAL", Py_BuildValue("s", "00:00:00:FF:FF:FF"));
3992 #ifdef HAVE_NETPACKET_PACKET_H
3993 PyModule_AddIntConstant(m
, "AF_PACKET", AF_PACKET
);
3994 PyModule_AddIntConstant(m
, "PF_PACKET", PF_PACKET
);
3995 PyModule_AddIntConstant(m
, "PACKET_HOST", PACKET_HOST
);
3996 PyModule_AddIntConstant(m
, "PACKET_BROADCAST", PACKET_BROADCAST
);
3997 PyModule_AddIntConstant(m
, "PACKET_MULTICAST", PACKET_MULTICAST
);
3998 PyModule_AddIntConstant(m
, "PACKET_OTHERHOST", PACKET_OTHERHOST
);
3999 PyModule_AddIntConstant(m
, "PACKET_OUTGOING", PACKET_OUTGOING
);
4000 PyModule_AddIntConstant(m
, "PACKET_LOOPBACK", PACKET_LOOPBACK
);
4001 PyModule_AddIntConstant(m
, "PACKET_FASTROUTE", PACKET_FASTROUTE
);
4005 PyModule_AddIntConstant(m
, "SOCK_STREAM", SOCK_STREAM
);
4006 PyModule_AddIntConstant(m
, "SOCK_DGRAM", SOCK_DGRAM
);
4008 /* We have incomplete socket support. */
4009 PyModule_AddIntConstant(m
, "SOCK_RAW", SOCK_RAW
);
4010 PyModule_AddIntConstant(m
, "SOCK_SEQPACKET", SOCK_SEQPACKET
);
4011 #if defined(SOCK_RDM)
4012 PyModule_AddIntConstant(m
, "SOCK_RDM", SOCK_RDM
);
4017 PyModule_AddIntConstant(m
, "SO_DEBUG", SO_DEBUG
);
4019 #ifdef SO_ACCEPTCONN
4020 PyModule_AddIntConstant(m
, "SO_ACCEPTCONN", SO_ACCEPTCONN
);
4023 PyModule_AddIntConstant(m
, "SO_REUSEADDR", SO_REUSEADDR
);
4025 #ifdef SO_EXCLUSIVEADDRUSE
4026 PyModule_AddIntConstant(m
, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE
);
4030 PyModule_AddIntConstant(m
, "SO_KEEPALIVE", SO_KEEPALIVE
);
4033 PyModule_AddIntConstant(m
, "SO_DONTROUTE", SO_DONTROUTE
);
4036 PyModule_AddIntConstant(m
, "SO_BROADCAST", SO_BROADCAST
);
4038 #ifdef SO_USELOOPBACK
4039 PyModule_AddIntConstant(m
, "SO_USELOOPBACK", SO_USELOOPBACK
);
4042 PyModule_AddIntConstant(m
, "SO_LINGER", SO_LINGER
);
4045 PyModule_AddIntConstant(m
, "SO_OOBINLINE", SO_OOBINLINE
);
4048 PyModule_AddIntConstant(m
, "SO_REUSEPORT", SO_REUSEPORT
);
4051 PyModule_AddIntConstant(m
, "SO_SNDBUF", SO_SNDBUF
);
4054 PyModule_AddIntConstant(m
, "SO_RCVBUF", SO_RCVBUF
);
4057 PyModule_AddIntConstant(m
, "SO_SNDLOWAT", SO_SNDLOWAT
);
4060 PyModule_AddIntConstant(m
, "SO_RCVLOWAT", SO_RCVLOWAT
);
4063 PyModule_AddIntConstant(m
, "SO_SNDTIMEO", SO_SNDTIMEO
);
4066 PyModule_AddIntConstant(m
, "SO_RCVTIMEO", SO_RCVTIMEO
);
4069 PyModule_AddIntConstant(m
, "SO_ERROR", SO_ERROR
);
4072 PyModule_AddIntConstant(m
, "SO_TYPE", SO_TYPE
);
4075 /* Maximum number of connections for "listen" */
4077 PyModule_AddIntConstant(m
, "SOMAXCONN", SOMAXCONN
);
4079 PyModule_AddIntConstant(m
, "SOMAXCONN", 5); /* Common value */
4082 /* Flags for send, recv */
4084 PyModule_AddIntConstant(m
, "MSG_OOB", MSG_OOB
);
4087 PyModule_AddIntConstant(m
, "MSG_PEEK", MSG_PEEK
);
4089 #ifdef MSG_DONTROUTE
4090 PyModule_AddIntConstant(m
, "MSG_DONTROUTE", MSG_DONTROUTE
);
4093 PyModule_AddIntConstant(m
, "MSG_DONTWAIT", MSG_DONTWAIT
);
4096 PyModule_AddIntConstant(m
, "MSG_EOR", MSG_EOR
);
4099 PyModule_AddIntConstant(m
, "MSG_TRUNC", MSG_TRUNC
);
4102 PyModule_AddIntConstant(m
, "MSG_CTRUNC", MSG_CTRUNC
);
4105 PyModule_AddIntConstant(m
, "MSG_WAITALL", MSG_WAITALL
);
4108 PyModule_AddIntConstant(m
, "MSG_BTAG", MSG_BTAG
);
4111 PyModule_AddIntConstant(m
, "MSG_ETAG", MSG_ETAG
);
4114 /* Protocol level and numbers, usable for [gs]etsockopt */
4116 PyModule_AddIntConstant(m
, "SOL_SOCKET", SOL_SOCKET
);
4119 PyModule_AddIntConstant(m
, "SOL_IP", SOL_IP
);
4121 PyModule_AddIntConstant(m
, "SOL_IP", 0);
4124 PyModule_AddIntConstant(m
, "SOL_IPX", SOL_IPX
);
4127 PyModule_AddIntConstant(m
, "SOL_AX25", SOL_AX25
);
4130 PyModule_AddIntConstant(m
, "SOL_ATALK", SOL_ATALK
);
4133 PyModule_AddIntConstant(m
, "SOL_NETROM", SOL_NETROM
);
4136 PyModule_AddIntConstant(m
, "SOL_ROSE", SOL_ROSE
);
4139 PyModule_AddIntConstant(m
, "SOL_TCP", SOL_TCP
);
4141 PyModule_AddIntConstant(m
, "SOL_TCP", 6);
4144 PyModule_AddIntConstant(m
, "SOL_UDP", SOL_UDP
);
4146 PyModule_AddIntConstant(m
, "SOL_UDP", 17);
4149 PyModule_AddIntConstant(m
, "IPPROTO_IP", IPPROTO_IP
);
4151 PyModule_AddIntConstant(m
, "IPPROTO_IP", 0);
4153 #ifdef IPPROTO_HOPOPTS
4154 PyModule_AddIntConstant(m
, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS
);
4157 PyModule_AddIntConstant(m
, "IPPROTO_ICMP", IPPROTO_ICMP
);
4159 PyModule_AddIntConstant(m
, "IPPROTO_ICMP", 1);
4162 PyModule_AddIntConstant(m
, "IPPROTO_IGMP", IPPROTO_IGMP
);
4165 PyModule_AddIntConstant(m
, "IPPROTO_GGP", IPPROTO_GGP
);
4168 PyModule_AddIntConstant(m
, "IPPROTO_IPV4", IPPROTO_IPV4
);
4171 PyModule_AddIntConstant(m
, "IPPROTO_IPV6", IPPROTO_IPV6
);
4174 PyModule_AddIntConstant(m
, "IPPROTO_IPIP", IPPROTO_IPIP
);
4177 PyModule_AddIntConstant(m
, "IPPROTO_TCP", IPPROTO_TCP
);
4179 PyModule_AddIntConstant(m
, "IPPROTO_TCP", 6);
4182 PyModule_AddIntConstant(m
, "IPPROTO_EGP", IPPROTO_EGP
);
4185 PyModule_AddIntConstant(m
, "IPPROTO_PUP", IPPROTO_PUP
);
4188 PyModule_AddIntConstant(m
, "IPPROTO_UDP", IPPROTO_UDP
);
4190 PyModule_AddIntConstant(m
, "IPPROTO_UDP", 17);
4193 PyModule_AddIntConstant(m
, "IPPROTO_IDP", IPPROTO_IDP
);
4195 #ifdef IPPROTO_HELLO
4196 PyModule_AddIntConstant(m
, "IPPROTO_HELLO", IPPROTO_HELLO
);
4199 PyModule_AddIntConstant(m
, "IPPROTO_ND", IPPROTO_ND
);
4202 PyModule_AddIntConstant(m
, "IPPROTO_TP", IPPROTO_TP
);
4205 PyModule_AddIntConstant(m
, "IPPROTO_IPV6", IPPROTO_IPV6
);
4207 #ifdef IPPROTO_ROUTING
4208 PyModule_AddIntConstant(m
, "IPPROTO_ROUTING", IPPROTO_ROUTING
);
4210 #ifdef IPPROTO_FRAGMENT
4211 PyModule_AddIntConstant(m
, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT
);
4214 PyModule_AddIntConstant(m
, "IPPROTO_RSVP", IPPROTO_RSVP
);
4217 PyModule_AddIntConstant(m
, "IPPROTO_GRE", IPPROTO_GRE
);
4220 PyModule_AddIntConstant(m
, "IPPROTO_ESP", IPPROTO_ESP
);
4223 PyModule_AddIntConstant(m
, "IPPROTO_AH", IPPROTO_AH
);
4225 #ifdef IPPROTO_MOBILE
4226 PyModule_AddIntConstant(m
, "IPPROTO_MOBILE", IPPROTO_MOBILE
);
4228 #ifdef IPPROTO_ICMPV6
4229 PyModule_AddIntConstant(m
, "IPPROTO_ICMPV6", IPPROTO_ICMPV6
);
4232 PyModule_AddIntConstant(m
, "IPPROTO_NONE", IPPROTO_NONE
);
4234 #ifdef IPPROTO_DSTOPTS
4235 PyModule_AddIntConstant(m
, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS
);
4238 PyModule_AddIntConstant(m
, "IPPROTO_XTP", IPPROTO_XTP
);
4241 PyModule_AddIntConstant(m
, "IPPROTO_EON", IPPROTO_EON
);
4244 PyModule_AddIntConstant(m
, "IPPROTO_PIM", IPPROTO_PIM
);
4246 #ifdef IPPROTO_IPCOMP
4247 PyModule_AddIntConstant(m
, "IPPROTO_IPCOMP", IPPROTO_IPCOMP
);
4250 PyModule_AddIntConstant(m
, "IPPROTO_VRRP", IPPROTO_VRRP
);
4253 PyModule_AddIntConstant(m
, "IPPROTO_BIP", IPPROTO_BIP
);
4257 PyModule_AddIntConstant(m
, "IPPROTO_RAW", IPPROTO_RAW
);
4259 PyModule_AddIntConstant(m
, "IPPROTO_RAW", 255);
4262 PyModule_AddIntConstant(m
, "IPPROTO_MAX", IPPROTO_MAX
);
4265 /* Some port configuration */
4266 #ifdef IPPORT_RESERVED
4267 PyModule_AddIntConstant(m
, "IPPORT_RESERVED", IPPORT_RESERVED
);
4269 PyModule_AddIntConstant(m
, "IPPORT_RESERVED", 1024);
4271 #ifdef IPPORT_USERRESERVED
4272 PyModule_AddIntConstant(m
, "IPPORT_USERRESERVED", IPPORT_USERRESERVED
);
4274 PyModule_AddIntConstant(m
, "IPPORT_USERRESERVED", 5000);
4277 /* Some reserved IP v.4 addresses */
4279 PyModule_AddIntConstant(m
, "INADDR_ANY", INADDR_ANY
);
4281 PyModule_AddIntConstant(m
, "INADDR_ANY", 0x00000000);
4283 #ifdef INADDR_BROADCAST
4284 PyModule_AddIntConstant(m
, "INADDR_BROADCAST", INADDR_BROADCAST
);
4286 PyModule_AddIntConstant(m
, "INADDR_BROADCAST", 0xffffffff);
4288 #ifdef INADDR_LOOPBACK
4289 PyModule_AddIntConstant(m
, "INADDR_LOOPBACK", INADDR_LOOPBACK
);
4291 PyModule_AddIntConstant(m
, "INADDR_LOOPBACK", 0x7F000001);
4293 #ifdef INADDR_UNSPEC_GROUP
4294 PyModule_AddIntConstant(m
, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP
);
4296 PyModule_AddIntConstant(m
, "INADDR_UNSPEC_GROUP", 0xe0000000);
4298 #ifdef INADDR_ALLHOSTS_GROUP
4299 PyModule_AddIntConstant(m
, "INADDR_ALLHOSTS_GROUP",
4300 INADDR_ALLHOSTS_GROUP
);
4302 PyModule_AddIntConstant(m
, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
4304 #ifdef INADDR_MAX_LOCAL_GROUP
4305 PyModule_AddIntConstant(m
, "INADDR_MAX_LOCAL_GROUP",
4306 INADDR_MAX_LOCAL_GROUP
);
4308 PyModule_AddIntConstant(m
, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
4311 PyModule_AddIntConstant(m
, "INADDR_NONE", INADDR_NONE
);
4313 PyModule_AddIntConstant(m
, "INADDR_NONE", 0xffffffff);
4316 /* IPv4 [gs]etsockopt options */
4318 PyModule_AddIntConstant(m
, "IP_OPTIONS", IP_OPTIONS
);
4321 PyModule_AddIntConstant(m
, "IP_HDRINCL", IP_HDRINCL
);
4324 PyModule_AddIntConstant(m
, "IP_TOS", IP_TOS
);
4327 PyModule_AddIntConstant(m
, "IP_TTL", IP_TTL
);
4330 PyModule_AddIntConstant(m
, "IP_RECVOPTS", IP_RECVOPTS
);
4332 #ifdef IP_RECVRETOPTS
4333 PyModule_AddIntConstant(m
, "IP_RECVRETOPTS", IP_RECVRETOPTS
);
4335 #ifdef IP_RECVDSTADDR
4336 PyModule_AddIntConstant(m
, "IP_RECVDSTADDR", IP_RECVDSTADDR
);
4339 PyModule_AddIntConstant(m
, "IP_RETOPTS", IP_RETOPTS
);
4341 #ifdef IP_MULTICAST_IF
4342 PyModule_AddIntConstant(m
, "IP_MULTICAST_IF", IP_MULTICAST_IF
);
4344 #ifdef IP_MULTICAST_TTL
4345 PyModule_AddIntConstant(m
, "IP_MULTICAST_TTL", IP_MULTICAST_TTL
);
4347 #ifdef IP_MULTICAST_LOOP
4348 PyModule_AddIntConstant(m
, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP
);
4350 #ifdef IP_ADD_MEMBERSHIP
4351 PyModule_AddIntConstant(m
, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP
);
4353 #ifdef IP_DROP_MEMBERSHIP
4354 PyModule_AddIntConstant(m
, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP
);
4356 #ifdef IP_DEFAULT_MULTICAST_TTL
4357 PyModule_AddIntConstant(m
, "IP_DEFAULT_MULTICAST_TTL",
4358 IP_DEFAULT_MULTICAST_TTL
);
4360 #ifdef IP_DEFAULT_MULTICAST_LOOP
4361 PyModule_AddIntConstant(m
, "IP_DEFAULT_MULTICAST_LOOP",
4362 IP_DEFAULT_MULTICAST_LOOP
);
4364 #ifdef IP_MAX_MEMBERSHIPS
4365 PyModule_AddIntConstant(m
, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS
);
4368 /* IPv6 [gs]etsockopt options, defined in RFC2553 */
4369 #ifdef IPV6_JOIN_GROUP
4370 PyModule_AddIntConstant(m
, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP
);
4372 #ifdef IPV6_LEAVE_GROUP
4373 PyModule_AddIntConstant(m
, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP
);
4375 #ifdef IPV6_MULTICAST_HOPS
4376 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS
);
4378 #ifdef IPV6_MULTICAST_IF
4379 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF
);
4381 #ifdef IPV6_MULTICAST_LOOP
4382 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP
);
4384 #ifdef IPV6_UNICAST_HOPS
4385 PyModule_AddIntConstant(m
, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS
);
4387 /* Additional IPV6 socket options, defined in RFC 3493 */
4389 PyModule_AddIntConstant(m
, "IPV6_V6ONLY", IPV6_V6ONLY
);
4391 /* Advanced IPV6 socket options, from RFC 3542 */
4392 #ifdef IPV6_CHECKSUM
4393 PyModule_AddIntConstant(m
, "IPV6_CHECKSUM", IPV6_CHECKSUM
);
4395 #ifdef IPV6_DONTFRAG
4396 PyModule_AddIntConstant(m
, "IPV6_DONTFRAG", IPV6_DONTFRAG
);
4399 PyModule_AddIntConstant(m
, "IPV6_DSTOPTS", IPV6_DSTOPTS
);
4401 #ifdef IPV6_HOPLIMIT
4402 PyModule_AddIntConstant(m
, "IPV6_HOPLIMIT", IPV6_HOPLIMIT
);
4405 PyModule_AddIntConstant(m
, "IPV6_HOPOPTS", IPV6_HOPOPTS
);
4408 PyModule_AddIntConstant(m
, "IPV6_NEXTHOP", IPV6_NEXTHOP
);
4411 PyModule_AddIntConstant(m
, "IPV6_PATHMTU", IPV6_PATHMTU
);
4414 PyModule_AddIntConstant(m
, "IPV6_PKTINFO", IPV6_PKTINFO
);
4416 #ifdef IPV6_RECVDSTOPTS
4417 PyModule_AddIntConstant(m
, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS
);
4419 #ifdef IPV6_RECVHOPLIMIT
4420 PyModule_AddIntConstant(m
, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT
);
4422 #ifdef IPV6_RECVHOPOPTS
4423 PyModule_AddIntConstant(m
, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS
);
4425 #ifdef IPV6_RECVPKTINFO
4426 PyModule_AddIntConstant(m
, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO
);
4428 #ifdef IPV6_RECVRTHDR
4429 PyModule_AddIntConstant(m
, "IPV6_RECVRTHDR", IPV6_RECVRTHDR
);
4431 #ifdef IPV6_RECVTCLASS
4432 PyModule_AddIntConstant(m
, "IPV6_RECVTCLASS", IPV6_RECVTCLASS
);
4435 PyModule_AddIntConstant(m
, "IPV6_RTHDR", IPV6_RTHDR
);
4437 #ifdef IPV6_RTHDRDSTOPTS
4438 PyModule_AddIntConstant(m
, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS
);
4440 #ifdef IPV6_RTHDR_TYPE_0
4441 PyModule_AddIntConstant(m
, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0
);
4443 #ifdef IPV6_RECVPATHMTU
4444 PyModule_AddIntConstant(m
, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU
);
4447 PyModule_AddIntConstant(m
, "IPV6_TCLASS", IPV6_TCLASS
);
4449 #ifdef IPV6_USE_MIN_MTU
4450 PyModule_AddIntConstant(m
, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU
);
4455 PyModule_AddIntConstant(m
, "TCP_NODELAY", TCP_NODELAY
);
4458 PyModule_AddIntConstant(m
, "TCP_MAXSEG", TCP_MAXSEG
);
4461 PyModule_AddIntConstant(m
, "TCP_CORK", TCP_CORK
);
4464 PyModule_AddIntConstant(m
, "TCP_KEEPIDLE", TCP_KEEPIDLE
);
4466 #ifdef TCP_KEEPINTVL
4467 PyModule_AddIntConstant(m
, "TCP_KEEPINTVL", TCP_KEEPINTVL
);
4470 PyModule_AddIntConstant(m
, "TCP_KEEPCNT", TCP_KEEPCNT
);
4473 PyModule_AddIntConstant(m
, "TCP_SYNCNT", TCP_SYNCNT
);
4476 PyModule_AddIntConstant(m
, "TCP_LINGER2", TCP_LINGER2
);
4478 #ifdef TCP_DEFER_ACCEPT
4479 PyModule_AddIntConstant(m
, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT
);
4481 #ifdef TCP_WINDOW_CLAMP
4482 PyModule_AddIntConstant(m
, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP
);
4485 PyModule_AddIntConstant(m
, "TCP_INFO", TCP_INFO
);
4488 PyModule_AddIntConstant(m
, "TCP_QUICKACK", TCP_QUICKACK
);
4494 PyModule_AddIntConstant(m
, "IPX_TYPE", IPX_TYPE
);
4497 /* get{addr,name}info parameters */
4498 #ifdef EAI_ADDRFAMILY
4499 PyModule_AddIntConstant(m
, "EAI_ADDRFAMILY", EAI_ADDRFAMILY
);
4502 PyModule_AddIntConstant(m
, "EAI_AGAIN", EAI_AGAIN
);
4505 PyModule_AddIntConstant(m
, "EAI_BADFLAGS", EAI_BADFLAGS
);
4508 PyModule_AddIntConstant(m
, "EAI_FAIL", EAI_FAIL
);
4511 PyModule_AddIntConstant(m
, "EAI_FAMILY", EAI_FAMILY
);
4514 PyModule_AddIntConstant(m
, "EAI_MEMORY", EAI_MEMORY
);
4517 PyModule_AddIntConstant(m
, "EAI_NODATA", EAI_NODATA
);
4520 PyModule_AddIntConstant(m
, "EAI_NONAME", EAI_NONAME
);
4523 PyModule_AddIntConstant(m
, "EAI_OVERFLOW", EAI_OVERFLOW
);
4526 PyModule_AddIntConstant(m
, "EAI_SERVICE", EAI_SERVICE
);
4529 PyModule_AddIntConstant(m
, "EAI_SOCKTYPE", EAI_SOCKTYPE
);
4532 PyModule_AddIntConstant(m
, "EAI_SYSTEM", EAI_SYSTEM
);
4535 PyModule_AddIntConstant(m
, "EAI_BADHINTS", EAI_BADHINTS
);
4538 PyModule_AddIntConstant(m
, "EAI_PROTOCOL", EAI_PROTOCOL
);
4541 PyModule_AddIntConstant(m
, "EAI_MAX", EAI_MAX
);
4544 PyModule_AddIntConstant(m
, "AI_PASSIVE", AI_PASSIVE
);
4547 PyModule_AddIntConstant(m
, "AI_CANONNAME", AI_CANONNAME
);
4549 #ifdef AI_NUMERICHOST
4550 PyModule_AddIntConstant(m
, "AI_NUMERICHOST", AI_NUMERICHOST
);
4552 #ifdef AI_NUMERICSERV
4553 PyModule_AddIntConstant(m
, "AI_NUMERICSERV", AI_NUMERICSERV
);
4556 PyModule_AddIntConstant(m
, "AI_MASK", AI_MASK
);
4559 PyModule_AddIntConstant(m
, "AI_ALL", AI_ALL
);
4561 #ifdef AI_V4MAPPED_CFG
4562 PyModule_AddIntConstant(m
, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG
);
4564 #ifdef AI_ADDRCONFIG
4565 PyModule_AddIntConstant(m
, "AI_ADDRCONFIG", AI_ADDRCONFIG
);
4568 PyModule_AddIntConstant(m
, "AI_V4MAPPED", AI_V4MAPPED
);
4571 PyModule_AddIntConstant(m
, "AI_DEFAULT", AI_DEFAULT
);
4574 PyModule_AddIntConstant(m
, "NI_MAXHOST", NI_MAXHOST
);
4577 PyModule_AddIntConstant(m
, "NI_MAXSERV", NI_MAXSERV
);
4580 PyModule_AddIntConstant(m
, "NI_NOFQDN", NI_NOFQDN
);
4582 #ifdef NI_NUMERICHOST
4583 PyModule_AddIntConstant(m
, "NI_NUMERICHOST", NI_NUMERICHOST
);
4586 PyModule_AddIntConstant(m
, "NI_NAMEREQD", NI_NAMEREQD
);
4588 #ifdef NI_NUMERICSERV
4589 PyModule_AddIntConstant(m
, "NI_NUMERICSERV", NI_NUMERICSERV
);
4592 PyModule_AddIntConstant(m
, "NI_DGRAM", NI_DGRAM
);
4595 /* shutdown() parameters */
4597 PyModule_AddIntConstant(m
, "SHUT_RD", SHUT_RD
);
4598 #elif defined(SD_RECEIVE)
4599 PyModule_AddIntConstant(m
, "SHUT_RD", SD_RECEIVE
);
4601 PyModule_AddIntConstant(m
, "SHUT_RD", 0);
4604 PyModule_AddIntConstant(m
, "SHUT_WR", SHUT_WR
);
4605 #elif defined(SD_SEND)
4606 PyModule_AddIntConstant(m
, "SHUT_WR", SD_SEND
);
4608 PyModule_AddIntConstant(m
, "SHUT_WR", 1);
4611 PyModule_AddIntConstant(m
, "SHUT_RDWR", SHUT_RDWR
);
4612 #elif defined(SD_BOTH)
4613 PyModule_AddIntConstant(m
, "SHUT_RDWR", SD_BOTH
);
4615 PyModule_AddIntConstant(m
, "SHUT_RDWR", 2);
4618 /* Initialize gethostbyname lock */
4619 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
4620 netdb_lock
= PyThread_allocate_lock();
4625 #ifndef HAVE_INET_PTON
4627 /* Simplistic emulation code for inet_pton that only works for IPv4 */
4628 /* These are not exposed because they do not set errno properly */
4631 inet_pton(int af
, const char *src
, void *dst
)
4633 if (af
== AF_INET
) {
4635 packed_addr
= inet_addr(src
);
4636 if (packed_addr
== INADDR_NONE
)
4638 memcpy(dst
, &packed_addr
, 4);
4641 /* Should set errno to EAFNOSUPPORT */
4646 inet_ntop(int af
, const void *src
, char *dst
, socklen_t size
)
4648 if (af
== AF_INET
) {
4649 struct in_addr packed_addr
;
4651 /* Should set errno to ENOSPC. */
4653 memcpy(&packed_addr
, src
, sizeof(packed_addr
));
4654 return strncpy(dst
, inet_ntoa(packed_addr
), size
);
4656 /* Should set errno to EAFNOSUPPORT */