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, AF_NETLINK and AF_TIPC are supported
12 - No read/write operations (use sendall/recv or makefile instead).
13 - Additional restrictions apply on some non-Unix platforms (compensated
18 - socket.error: exception raised for socket specific errors
19 - socket.gaierror: exception raised for getaddrinfo/getnameinfo errors,
20 a subclass of socket.error
21 - socket.herror: exception raised for gethostby* errors,
22 a subclass of socket.error
23 - socket.fromfd(fd, family, type[, proto]) --> new socket object (created
24 from an existing file descriptor)
25 - socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')
26 - socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])
27 - socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com')
28 - socket.getprotobyname(protocolname) --> protocol number
29 - socket.getservbyname(servicename[, protocolname]) --> port number
30 - socket.getservbyport(portnumber[, protocolname]) --> service name
31 - socket.socket([family[, type [, proto]]]) --> new socket object
32 - socket.socketpair([family[, type [, proto]]]) --> (socket, socket)
33 - socket.ntohs(16 bit value) --> new int object
34 - socket.ntohl(32 bit value) --> new int object
35 - socket.htons(16 bit value) --> new int object
36 - socket.htonl(32 bit value) --> new int object
37 - socket.getaddrinfo(host, port [, family, socktype, proto, flags])
38 --> List of (family, socktype, proto, canonname, sockaddr)
39 - socket.getnameinfo(sockaddr, flags) --> (host, port)
40 - socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
41 - socket.has_ipv6: boolean value indicating if IPv6 is supported
42 - socket.inet_aton(IP address) -> 32-bit packed IP representation
43 - socket.inet_ntoa(packed IP) -> IP address string
44 - socket.getdefaulttimeout() -> None | float
45 - socket.setdefaulttimeout(None | float)
46 - an Internet socket address is a pair (hostname, port)
47 where hostname can be anything recognized by gethostbyname()
48 (including the dd.dd.dd.dd notation) and port is in host byte order
49 - where a hostname is returned, the dd.dd.dd.dd notation is used
50 - a UNIX domain socket address is a string specifying the pathname
51 - an AF_PACKET socket address is a tuple containing a string
52 specifying the ethernet interface and an integer specifying
53 the Ethernet protocol number to be received. For example:
54 ("eth0",0x1234). Optional 3rd,4th,5th elements in the tuple
55 specify packet-type and ha-type/addr.
56 - an AF_TIPC socket address is expressed as
57 (addr_type, v1, v2, v3 [, scope]); where addr_type can be one of:
58 TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, and TIPC_ADDR_ID;
59 and scope can be one of:
60 TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and TIPC_NODE_SCOPE.
61 The meaning of v1, v2 and v3 depends on the value of addr_type:
62 if addr_type is TIPC_ADDR_NAME:
64 v2 is the port identifier
66 if addr_type is TIPC_ADDR_NAMESEQ:
68 v2 is the lower port number
69 v3 is the upper port number
70 if addr_type is TIPC_ADDR_ID:
76 Local naming conventions:
78 - names starting with sock_ are socket object methods
79 - names starting with socket_ are module-level functions
80 - names starting with PySocket are exported through socketmodule.h
86 * inet_aton is not available on OSX 10.3, yet we want to use a binary
87 * that was build on 10.4 or later to work on that release, weak linking
88 * comes to the rescue.
90 # pragma weak inet_aton
94 #include "structmember.h"
97 #define MAX(x, y) ((x) < (y) ? (y) : (x))
99 /* Socket object documentation */
100 PyDoc_STRVAR(sock_doc
,
101 "socket([family[, type[, proto]]]) -> socket object\n\
103 Open a socket of the given type. The family argument specifies the\n\
104 address family; it defaults to AF_INET. The type argument specifies\n\
105 whether this is a stream (SOCK_STREAM, this is the default)\n\
106 or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0,\n\
107 specifying the default protocol. Keyword arguments are accepted.\n\
109 A socket object represents one endpoint of a network connection.\n\
111 Methods of socket objects (keyword arguments not allowed):\n\
113 accept() -- accept a connection, returning new socket and client address\n\
114 bind(addr) -- bind the socket to a local address\n\
115 close() -- close the socket\n\
116 connect(addr) -- connect the socket to a remote address\n\
117 connect_ex(addr) -- connect, return an error code instead of an exception\n\
118 dup() -- return a new socket object identical to the current one [*]\n\
119 fileno() -- return underlying file descriptor\n\
120 getpeername() -- return remote address [*]\n\
121 getsockname() -- return local address\n\
122 getsockopt(level, optname[, buflen]) -- get socket options\n\
123 gettimeout() -- return timeout or None\n\
124 listen(n) -- start listening for incoming connections\n\
125 makefile([mode, [bufsize]]) -- return a file object for the socket [*]\n\
126 recv(buflen[, flags]) -- receive data\n\
127 recv_into(buffer[, nbytes[, flags]]) -- receive data (into a buffer)\n\
128 recvfrom(buflen[, flags]) -- receive data and sender\'s address\n\
129 recvfrom_into(buffer[, nbytes, [, flags])\n\
130 -- receive data and sender\'s address (into a buffer)\n\
131 sendall(data[, flags]) -- send all data\n\
132 send(data[, flags]) -- send data, may not send all of it\n\
133 sendto(data[, flags], addr) -- send data to a given address\n\
134 setblocking(0 | 1) -- set or clear the blocking I/O flag\n\
135 setsockopt(level, optname, value) -- set socket options\n\
136 settimeout(None | float) -- set or clear the timeout\n\
137 shutdown(how) -- shut down traffic in one or both directions\n\
139 [*] not available on all platforms!");
141 /* XXX This is a terrible mess of platform-dependent preprocessor hacks.
142 I hope some day someone can clean this up please... */
144 /* Hacks for gethostbyname_r(). On some non-Linux platforms, the configure
145 script doesn't get this right, so we hardcode some platform checks below.
146 On the other hand, not all Linux versions agree, so there the settings
147 computed by the configure script are needed! */
150 # undef HAVE_GETHOSTBYNAME_R_3_ARG
151 # undef HAVE_GETHOSTBYNAME_R_5_ARG
152 # undef HAVE_GETHOSTBYNAME_R_6_ARG
156 # undef HAVE_GETHOSTBYNAME_R
159 #ifdef HAVE_GETHOSTBYNAME_R
160 # if defined(_AIX) || defined(__osf__)
161 # define HAVE_GETHOSTBYNAME_R_3_ARG
162 # elif defined(__sun) || defined(__sgi)
163 # define HAVE_GETHOSTBYNAME_R_5_ARG
164 # elif defined(linux)
165 /* Rely on the configure script */
167 # undef HAVE_GETHOSTBYNAME_R
171 #if !defined(HAVE_GETHOSTBYNAME_R) && defined(WITH_THREAD) && \
173 # define USE_GETHOSTBYNAME_LOCK
176 /* To use __FreeBSD_version */
177 #ifdef HAVE_SYS_PARAM_H
178 #include <sys/param.h>
180 /* On systems on which getaddrinfo() is believed to not be thread-safe,
181 (this includes the getaddrinfo emulation) protect access with a lock. */
182 #if defined(WITH_THREAD) && (defined(__APPLE__) || \
183 (defined(__FreeBSD__) && __FreeBSD_version+0 < 503000) || \
184 defined(__OpenBSD__) || defined(__NetBSD__) || \
185 defined(__VMS) || !defined(HAVE_GETADDRINFO))
186 #define USE_GETADDRINFO_LOCK
189 #ifdef USE_GETADDRINFO_LOCK
190 #define ACQUIRE_GETADDRINFO_LOCK PyThread_acquire_lock(netdb_lock, 1);
191 #define RELEASE_GETADDRINFO_LOCK PyThread_release_lock(netdb_lock);
193 #define ACQUIRE_GETADDRINFO_LOCK
194 #define RELEASE_GETADDRINFO_LOCK
197 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
198 # include "pythread.h"
201 #if defined(PYCC_VACPP)
204 # include <sys/ioctl.h>
213 #if defined(PYOS_OS2)
215 # define INCL_DOSERRORS
216 # define INCL_NOPMAPI
220 #if defined(__sgi) && _COMPILER_VERSION>700 && !_SGIAPI
221 /* make sure that the reentrant (gethostbyaddr_r etc)
222 functions are declared correctly if compiling with
223 MIPSPro 7.x in ANSI C mode (default) */
225 /* XXX Using _SGIAPI is the wrong thing,
226 but I don't know what the right thing is. */
227 #undef _SGIAPI /* to avoid warning */
231 #include <sys/socket.h>
232 #include <sys/types.h>
233 #include <netinet/in.h>
235 #define HAVE_GETADDRINFO 1
236 #define HAVE_GETNAMEINFO 1
239 #define HAVE_INET_PTON
243 /* Irix 6.5 fails to define this variable at all. This is needed
244 for both GCC and SGI's compiler. I'd say that the SGI headers
245 are just busted. Same thing for Solaris. */
246 #if (defined(__sgi) || defined(sun)) && !defined(INET_ADDRSTRLEN)
247 #define INET_ADDRSTRLEN 16
250 /* Generic includes */
251 #ifdef HAVE_SYS_TYPES_H
252 #include <sys/types.h>
255 /* Generic socket object definitions and includes */
256 #define PySocket_BUILDING_SOCKET
257 #include "socketmodule.h"
259 /* Addressing includes */
263 /* Non-MS WINDOWS includes */
266 /* Headers needed for inet_ntoa() and inet_addr() */
268 # include <net/netdb.h>
269 # elif defined(PYOS_OS2) && defined(PYCC_VACPP)
271 typedef size_t socklen_t
;
273 # include <arpa/inet.h>
279 # include <sys/ioctl.h>
280 # include <socklib.h>
282 int h_errno
; /* not used */
283 # define INET_ADDRSTRLEN 16
288 /* MS_WINDOWS includes */
298 # define offsetof(type, member) ((size_t)(&((type *)0)->member))
302 # define O_NONBLOCK O_NDELAY
305 /* include Python's addrinfo.h unless it causes trouble */
306 #if defined(__sgi) && _COMPILER_VERSION>700 && defined(_SS_ALIGNSIZE)
307 /* Do not include addinfo.h on some newer IRIX versions.
308 * _SS_ALIGNSIZE is defined in sys/socket.h by 6.5.21,
309 * for example, but not by 6.5.10.
311 #elif defined(_MSC_VER) && _MSC_VER>1201
312 /* Do not include addrinfo.h for MSVC7 or greater. 'addrinfo' and
313 * EAI_* constants are defined in (the already included) ws2tcpip.h.
316 # include "addrinfo.h"
319 #ifndef HAVE_INET_PTON
320 #if !defined(NTDDI_VERSION) || (NTDDI_VERSION < NTDDI_LONGHORN)
321 int inet_pton(int af
, const char *src
, void *dst
);
322 const char *inet_ntop(int af
, const void *src
, char *dst
, socklen_t size
);
327 /* On OS X, getaddrinfo returns no error indication of lookup
328 failure, so we must use the emulation instead of the libinfo
329 implementation. Unfortunately, performing an autoconf test
330 for this bug would require DNS access for the machine performing
331 the configuration, which is not acceptable. Therefore, we
332 determine the bug just by checking for __APPLE__. If this bug
333 gets ever fixed, perhaps checking for sys/version.h would be
334 appropriate, which is 10/0 on the system with the bug. */
335 #ifndef HAVE_GETNAMEINFO
336 /* This bug seems to be fixed in Jaguar. Ths easiest way I could
337 Find to check for Jaguar is that it has getnameinfo(), which
338 older releases don't have */
339 #undef HAVE_GETADDRINFO
342 #ifdef HAVE_INET_ATON
343 #define USE_INET_ATON_WEAKLINK
348 /* I know this is a bad practice, but it is the easiest... */
349 #if !defined(HAVE_GETADDRINFO)
350 /* avoid clashes with the C library definition of the symbol. */
351 #define getaddrinfo fake_getaddrinfo
352 #define gai_strerror fake_gai_strerror
353 #define freeaddrinfo fake_freeaddrinfo
354 #include "getaddrinfo.c"
356 #if !defined(HAVE_GETNAMEINFO)
357 #define getnameinfo fake_getnameinfo
358 #include "getnameinfo.c"
361 #if defined(MS_WINDOWS) || defined(__BEOS__)
362 /* BeOS suffers from the same socket dichotomy as Win32... - [cjh] */
363 /* seem to be a few differences in the API */
364 #define SOCKETCLOSE closesocket
365 #define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */
369 #define EAFNOSUPPORT WSAEAFNOSUPPORT
370 #define snprintf _snprintf
373 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
374 #define SOCKETCLOSE soclose
375 #define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
379 #define SOCKETCLOSE close
382 #if (defined(HAVE_BLUETOOTH_H) || defined(HAVE_BLUETOOTH_BLUETOOTH_H)) && !defined(__NetBSD__) && !defined(__DragonFly__)
383 #define USE_BLUETOOTH 1
384 #if defined(__FreeBSD__)
385 #define BTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP
386 #define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM
387 #define BTPROTO_HCI BLUETOOTH_PROTO_HCI
388 #define SOL_HCI SOL_HCI_RAW
389 #define HCI_FILTER SO_HCI_RAW_FILTER
390 #define sockaddr_l2 sockaddr_l2cap
391 #define sockaddr_rc sockaddr_rfcomm
392 #define hci_dev hci_node
393 #define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb)
394 #define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)
395 #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
396 #elif defined(__NetBSD__) || defined(__DragonFly__)
397 #define sockaddr_l2 sockaddr_bt
398 #define sockaddr_rc sockaddr_bt
399 #define sockaddr_hci sockaddr_bt
400 #define sockaddr_sco sockaddr_bt
401 #define SOL_HCI BTPROTO_HCI
402 #define HCI_DATA_DIR SO_HCI_DIRECTION
403 #define _BT_L2_MEMB(sa, memb) ((sa)->bt_##memb)
404 #define _BT_RC_MEMB(sa, memb) ((sa)->bt_##memb)
405 #define _BT_HCI_MEMB(sa, memb) ((sa)->bt_##memb)
406 #define _BT_SCO_MEMB(sa, memb) ((sa)->bt_##memb)
408 #define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb)
409 #define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb)
410 #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
411 #define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)
416 /* TCP/IP Services for VMS uses a maximum send/recv buffer length */
417 #define SEGMENT_SIZE (32 * 1024 -1)
420 #define SAS2SA(x) ((struct sockaddr *)(x))
423 * Constants for getnameinfo()
425 #if !defined(NI_MAXHOST)
426 #define NI_MAXHOST 1025
428 #if !defined(NI_MAXSERV)
429 #define NI_MAXSERV 32
432 /* XXX There's a problem here: *static* functions are not supposed to have
433 a Py prefix (or use CapitalizedWords). Later... */
435 /* Global variable holding the exception type for errors detected
436 by this module (but not argument type or memory errors, etc.). */
437 static PyObject
*socket_error
;
438 static PyObject
*socket_herror
;
439 static PyObject
*socket_gaierror
;
440 static PyObject
*socket_timeout
;
443 /* Global variable which is !=0 if Python is running in a RISC OS taskwindow */
444 static int taskwindow
;
447 /* A forward reference to the socket type object.
448 The sock_type variable contains pointers to various functions,
449 some of which call new_sockobject(), which uses sock_type, so
450 there has to be a circular reference. */
451 static PyTypeObject sock_type
;
453 #if defined(HAVE_POLL_H)
455 #elif defined(HAVE_SYS_POLL_H)
456 #include <sys/poll.h>
459 #ifdef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
460 /* Platform can select file descriptors beyond FD_SETSIZE */
461 #define IS_SELECTABLE(s) 1
462 #elif defined(HAVE_POLL)
463 /* Instead of select(), we'll use poll() since poll() works on any fd. */
464 #define IS_SELECTABLE(s) 1
465 /* Can we call select() with this socket without a buffer overrun? */
467 /* POSIX says selecting file descriptors beyond FD_SETSIZE
468 has undefined behaviour. If there's no timeout left, we don't have to
469 call select, so it's a safe, little white lie. */
470 #define IS_SELECTABLE(s) ((s)->sock_fd < FD_SETSIZE || s->sock_timeout <= 0.0)
476 PyErr_SetString(socket_error
, "unable to select on socket");
480 /* Convenience function to raise an error according to errno
481 and return a NULL pointer from a function. */
487 int err_no
= WSAGetLastError();
488 /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which
489 recognizes the error codes used by both GetLastError() and
492 return PyErr_SetExcFromWindowsErr(socket_error
, err_no
);
495 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
496 if (sock_errno() != NO_ERROR
) {
500 int myerrorcode
= sock_errno();
502 /* Retrieve socket-related error message from MPTN.MSG file */
503 rc
= DosGetMessage(NULL
, 0, outbuf
, sizeof(outbuf
),
504 myerrorcode
- SOCBASEERR
+ 26,
507 if (rc
== NO_ERROR
) {
510 /* OS/2 doesn't guarantee a terminator */
511 outbuf
[msglen
] = '\0';
512 if (strlen(outbuf
) > 0) {
513 /* If non-empty msg, trim CRLF */
514 char *lastc
= &outbuf
[ strlen(outbuf
)-1 ];
515 while (lastc
> outbuf
&&
516 isspace(Py_CHARMASK(*lastc
))) {
517 /* Trim trailing whitespace (CRLF) */
521 v
= Py_BuildValue("(is)", myerrorcode
, outbuf
);
523 PyErr_SetObject(socket_error
, v
);
532 if (_inet_error
.errnum
!= NULL
) {
534 v
= Py_BuildValue("(is)", errno
, _inet_err());
536 PyErr_SetObject(socket_error
, v
);
543 return PyErr_SetFromErrno(socket_error
);
548 set_herror(int h_error
)
552 #ifdef HAVE_HSTRERROR
553 v
= Py_BuildValue("(is)", h_error
, (char *)hstrerror(h_error
));
555 v
= Py_BuildValue("(is)", h_error
, "host not found");
558 PyErr_SetObject(socket_herror
, v
);
567 set_gaierror(int error
)
572 /* EAI_SYSTEM is not available on Windows XP. */
573 if (error
== EAI_SYSTEM
)
577 #ifdef HAVE_GAI_STRERROR
578 v
= Py_BuildValue("(is)", error
, gai_strerror(error
));
580 v
= Py_BuildValue("(is)", error
, "getaddrinfo failed");
583 PyErr_SetObject(socket_gaierror
, v
);
591 /* Function to send in segments */
593 sendsegmented(int sock_fd
, char *buf
, int len
, int flags
)
598 while (remaining
> 0) {
599 unsigned int segment
;
601 segment
= (remaining
>= SEGMENT_SIZE
? SEGMENT_SIZE
: remaining
);
602 n
= send(sock_fd
, buf
, segment
, flags
);
606 remaining
-= segment
;
614 /* Function to perform the setting of socket blocking mode
615 internally. block = (1 | 0). */
617 internal_setblocking(PySocketSockObject
*s
, int block
)
625 Py_BEGIN_ALLOW_THREADS
628 setsockopt(s
->sock_fd
, SOL_SOCKET
, SO_NONBLOCK
,
629 (void *)(&block
), sizeof(int));
633 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
635 ioctl(s
->sock_fd
, FIONBIO
, (caddr_t
)&block
, sizeof(block
));
638 ioctl(s
->sock_fd
, FIONBIO
, (unsigned int *)&block
);
639 #else /* !PYOS_OS2 && !__VMS */
640 delay_flag
= fcntl(s
->sock_fd
, F_GETFL
, 0);
642 delay_flag
&= (~O_NONBLOCK
);
644 delay_flag
|= O_NONBLOCK
;
645 fcntl(s
->sock_fd
, F_SETFL
, delay_flag
);
646 #endif /* !PYOS_OS2 */
647 #else /* MS_WINDOWS */
649 ioctlsocket(s
->sock_fd
, FIONBIO
, (u_long
*)&block
);
650 #endif /* MS_WINDOWS */
653 socketioctl(s
->sock_fd
, FIONBIO
, (u_long
*)&block
);
655 #endif /* __BEOS__ */
658 /* Since these don't return anything */
662 /* Do a select()/poll() on the socket, if necessary (sock_timeout > 0).
663 The argument writing indicates the direction.
664 This does not raise an exception; we'll let our caller do that
665 after they've reacquired the interpreter lock.
666 Returns 1 on timeout, -1 on error, 0 otherwise. */
668 internal_select(PySocketSockObject
*s
, int writing
)
672 /* Nothing to do unless we're in timeout mode (not non-blocking) */
673 if (s
->sock_timeout
<= 0.0)
676 /* Guard against closed socket */
680 /* Prefer poll, if available, since you can poll() any fd
681 * which can't be done with select(). */
684 struct pollfd pollfd
;
687 pollfd
.fd
= s
->sock_fd
;
688 pollfd
.events
= writing
? POLLOUT
: POLLIN
;
690 /* s->sock_timeout is in seconds, timeout in ms */
691 timeout
= (int)(s
->sock_timeout
* 1000 + 0.5);
692 n
= poll(&pollfd
, 1, timeout
);
696 /* Construct the arguments to select */
699 tv
.tv_sec
= (int)s
->sock_timeout
;
700 tv
.tv_usec
= (int)((s
->sock_timeout
- tv
.tv_sec
) * 1e6
);
702 FD_SET(s
->sock_fd
, &fds
);
704 /* See if the socket is ready */
706 n
= select(s
->sock_fd
+1, NULL
, &fds
, NULL
, &tv
);
708 n
= select(s
->sock_fd
+1, &fds
, NULL
, NULL
, &tv
);
719 /* Initialize a new socket object. */
721 static double defaulttimeout
= -1.0; /* Default timeout for new sockets */
724 init_sockobject(PySocketSockObject
*s
,
725 SOCKET_T fd
, int family
, int type
, int proto
)
731 s
->sock_family
= family
;
733 s
->sock_proto
= proto
;
734 s
->sock_timeout
= defaulttimeout
;
736 s
->errorhandler
= &set_error
;
738 if (defaulttimeout
>= 0.0)
739 internal_setblocking(s
, 0);
743 socketioctl(s
->sock_fd
, 0x80046679, (u_long
*)&block
);
748 /* Create a new socket object.
749 This just creates the object and initializes it.
750 If the creation fails, return NULL and set an exception (implicit
753 static PySocketSockObject
*
754 new_sockobject(SOCKET_T fd
, int family
, int type
, int proto
)
756 PySocketSockObject
*s
;
757 s
= (PySocketSockObject
*)
758 PyType_GenericNew(&sock_type
, NULL
, NULL
);
760 init_sockobject(s
, fd
, family
, type
, proto
);
765 /* Lock to allow python interpreter to continue, but only allow one
766 thread to be in gethostbyname or getaddrinfo */
767 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
768 PyThread_type_lock netdb_lock
;
772 /* Convert a string specifying a host name or one of a few symbolic
773 names to a numeric IP address. This usually calls gethostbyname()
774 to do the work; the names "" and "<broadcast>" are special.
775 Return the length (IPv4 should be 4 bytes), or negative if
776 an error occurred; then an exception is raised. */
779 setipaddr(char *name
, struct sockaddr
*addr_ret
, size_t addr_ret_size
, int af
)
781 struct addrinfo hints
, *res
;
786 memset((void *) addr_ret
, '\0', sizeof(*addr_ret
));
787 if (name
[0] == '\0') {
789 memset(&hints
, 0, sizeof(hints
));
790 hints
.ai_family
= af
;
791 hints
.ai_socktype
= SOCK_DGRAM
; /*dummy*/
792 hints
.ai_flags
= AI_PASSIVE
;
793 Py_BEGIN_ALLOW_THREADS
794 ACQUIRE_GETADDRINFO_LOCK
795 error
= getaddrinfo(NULL
, "0", &hints
, &res
);
797 /* We assume that those thread-unsafe getaddrinfo() versions
798 *are* safe regarding their return value, ie. that a
799 subsequent call to getaddrinfo() does not destroy the
800 outcome of the first call. */
801 RELEASE_GETADDRINFO_LOCK
806 switch (res
->ai_family
) {
817 PyErr_SetString(socket_error
,
818 "unsupported address family");
823 PyErr_SetString(socket_error
,
824 "wildcard resolved to multiple address");
827 if (res
->ai_addrlen
< addr_ret_size
)
828 addr_ret_size
= res
->ai_addrlen
;
829 memcpy(addr_ret
, res
->ai_addr
, addr_ret_size
);
833 if (name
[0] == '<' && strcmp(name
, "<broadcast>") == 0) {
834 struct sockaddr_in
*sin
;
835 if (af
!= AF_INET
&& af
!= AF_UNSPEC
) {
836 PyErr_SetString(socket_error
,
837 "address family mismatched");
840 sin
= (struct sockaddr_in
*)addr_ret
;
841 memset((void *) sin
, '\0', sizeof(*sin
));
842 sin
->sin_family
= AF_INET
;
843 #ifdef HAVE_SOCKADDR_SA_LEN
844 sin
->sin_len
= sizeof(*sin
);
846 sin
->sin_addr
.s_addr
= INADDR_BROADCAST
;
847 return sizeof(sin
->sin_addr
);
849 if (sscanf(name
, "%d.%d.%d.%d%c", &d1
, &d2
, &d3
, &d4
, &ch
) == 4 &&
850 0 <= d1
&& d1
<= 255 && 0 <= d2
&& d2
<= 255 &&
851 0 <= d3
&& d3
<= 255 && 0 <= d4
&& d4
<= 255) {
852 struct sockaddr_in
*sin
;
853 sin
= (struct sockaddr_in
*)addr_ret
;
854 sin
->sin_addr
.s_addr
= htonl(
855 ((long) d1
<< 24) | ((long) d2
<< 16) |
856 ((long) d3
<< 8) | ((long) d4
<< 0));
857 sin
->sin_family
= AF_INET
;
858 #ifdef HAVE_SOCKADDR_SA_LEN
859 sin
->sin_len
= sizeof(*sin
);
863 memset(&hints
, 0, sizeof(hints
));
864 hints
.ai_family
= af
;
865 Py_BEGIN_ALLOW_THREADS
866 ACQUIRE_GETADDRINFO_LOCK
867 error
= getaddrinfo(name
, NULL
, &hints
, &res
);
868 #if defined(__digital__) && defined(__unix__)
869 if (error
== EAI_NONAME
&& af
== AF_UNSPEC
) {
870 /* On Tru64 V5.1, numeric-to-addr conversion fails
871 if no address family is given. Assume IPv4 for now.*/
872 hints
.ai_family
= AF_INET
;
873 error
= getaddrinfo(name
, NULL
, &hints
, &res
);
877 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
882 if (res
->ai_addrlen
< addr_ret_size
)
883 addr_ret_size
= res
->ai_addrlen
;
884 memcpy((char *) addr_ret
, res
->ai_addr
, addr_ret_size
);
886 switch (addr_ret
->sa_family
) {
894 PyErr_SetString(socket_error
, "unknown address family");
900 /* Create a string object representing an IP address.
901 This is always a string of the form 'dd.dd.dd.dd' (with variable
905 makeipaddr(struct sockaddr
*addr
, int addrlen
)
907 char buf
[NI_MAXHOST
];
910 error
= getnameinfo(addr
, addrlen
, buf
, sizeof(buf
), NULL
, 0,
916 return PyString_FromString(buf
);
921 /* Convert a string representation of a Bluetooth address into a numeric
922 address. Returns the length (6), or raises an exception and returns -1 if
923 an error occurred. */
926 setbdaddr(char *name
, bdaddr_t
*bdaddr
)
928 unsigned int b0
, b1
, b2
, b3
, b4
, b5
;
932 n
= sscanf(name
, "%X:%X:%X:%X:%X:%X%c",
933 &b5
, &b4
, &b3
, &b2
, &b1
, &b0
, &ch
);
934 if (n
== 6 && (b0
| b1
| b2
| b3
| b4
| b5
) < 256) {
943 PyErr_SetString(socket_error
, "bad bluetooth address");
948 /* Create a string representation of the Bluetooth address. This is always a
949 string of the form 'XX:XX:XX:XX:XX:XX' where XX is a two digit hexadecimal
950 value (zero padded if necessary). */
953 makebdaddr(bdaddr_t
*bdaddr
)
955 char buf
[(6 * 2) + 5 + 1];
957 sprintf(buf
, "%02X:%02X:%02X:%02X:%02X:%02X",
958 bdaddr
->b
[5], bdaddr
->b
[4], bdaddr
->b
[3],
959 bdaddr
->b
[2], bdaddr
->b
[1], bdaddr
->b
[0]);
960 return PyString_FromString(buf
);
965 /* Create an object representing the given socket address,
966 suitable for passing it back to bind(), connect() etc.
967 The family field of the sockaddr structure is inspected
968 to determine what kind of address it really is. */
972 makesockaddr(int sockfd
, struct sockaddr
*addr
, int addrlen
, int proto
)
975 /* No address -- may be recvfrom() from known socket */
981 /* XXX: BeOS version of accept() doesn't set family correctly */
982 addr
->sa_family
= AF_INET
;
985 switch (addr
->sa_family
) {
989 struct sockaddr_in
*a
;
990 PyObject
*addrobj
= makeipaddr(addr
, sizeof(*a
));
991 PyObject
*ret
= NULL
;
993 a
= (struct sockaddr_in
*)addr
;
994 ret
= Py_BuildValue("Oi", addrobj
, ntohs(a
->sin_port
));
1000 #if defined(AF_UNIX)
1003 struct sockaddr_un
*a
= (struct sockaddr_un
*) addr
;
1005 if (a
->sun_path
[0] == 0) { /* Linux abstract namespace */
1006 addrlen
-= offsetof(struct sockaddr_un
, sun_path
);
1007 return PyString_FromStringAndSize(a
->sun_path
,
1013 /* regular NULL-terminated string */
1014 return PyString_FromString(a
->sun_path
);
1017 #endif /* AF_UNIX */
1019 #if defined(AF_NETLINK)
1022 struct sockaddr_nl
*a
= (struct sockaddr_nl
*) addr
;
1023 return Py_BuildValue("II", a
->nl_pid
, a
->nl_groups
);
1025 #endif /* AF_NETLINK */
1030 struct sockaddr_in6
*a
;
1031 PyObject
*addrobj
= makeipaddr(addr
, sizeof(*a
));
1032 PyObject
*ret
= NULL
;
1034 a
= (struct sockaddr_in6
*)addr
;
1035 ret
= Py_BuildValue("Oiii",
1037 ntohs(a
->sin6_port
),
1046 #ifdef USE_BLUETOOTH
1052 struct sockaddr_l2
*a
= (struct sockaddr_l2
*) addr
;
1053 PyObject
*addrobj
= makebdaddr(&_BT_L2_MEMB(a
, bdaddr
));
1054 PyObject
*ret
= NULL
;
1056 ret
= Py_BuildValue("Oi",
1058 _BT_L2_MEMB(a
, psm
));
1064 case BTPROTO_RFCOMM
:
1066 struct sockaddr_rc
*a
= (struct sockaddr_rc
*) addr
;
1067 PyObject
*addrobj
= makebdaddr(&_BT_RC_MEMB(a
, bdaddr
));
1068 PyObject
*ret
= NULL
;
1070 ret
= Py_BuildValue("Oi",
1072 _BT_RC_MEMB(a
, channel
));
1080 struct sockaddr_hci
*a
= (struct sockaddr_hci
*) addr
;
1081 #if defined(__NetBSD__) || defined(__DragonFly__)
1082 return makebdaddr(&_BT_HCI_MEMB(a
, bdaddr
));
1084 PyObject
*ret
= NULL
;
1085 ret
= Py_BuildValue("i", _BT_HCI_MEMB(a
, dev
));
1090 #if !defined(__FreeBSD__)
1093 struct sockaddr_sco
*a
= (struct sockaddr_sco
*) addr
;
1094 return makebdaddr(&_BT_SCO_MEMB(a
, bdaddr
));
1099 PyErr_SetString(PyExc_ValueError
,
1100 "Unknown Bluetooth protocol");
1105 #if defined(HAVE_NETPACKET_PACKET_H) && defined(SIOCGIFNAME)
1108 struct sockaddr_ll
*a
= (struct sockaddr_ll
*)addr
;
1111 /* need to look up interface name give index */
1112 if (a
->sll_ifindex
) {
1113 ifr
.ifr_ifindex
= a
->sll_ifindex
;
1114 if (ioctl(sockfd
, SIOCGIFNAME
, &ifr
) == 0)
1115 ifname
= ifr
.ifr_name
;
1117 return Py_BuildValue("shbhs#",
1119 ntohs(a
->sll_protocol
),
1127 #ifdef HAVE_LINUX_TIPC_H
1130 struct sockaddr_tipc
*a
= (struct sockaddr_tipc
*) addr
;
1131 if (a
->addrtype
== TIPC_ADDR_NAMESEQ
) {
1132 return Py_BuildValue("IIIII",
1134 a
->addr
.nameseq
.type
,
1135 a
->addr
.nameseq
.lower
,
1136 a
->addr
.nameseq
.upper
,
1138 } else if (a
->addrtype
== TIPC_ADDR_NAME
) {
1139 return Py_BuildValue("IIIII",
1141 a
->addr
.name
.name
.type
,
1142 a
->addr
.name
.name
.instance
,
1143 a
->addr
.name
.name
.instance
,
1145 } else if (a
->addrtype
== TIPC_ADDR_ID
) {
1146 return Py_BuildValue("IIIII",
1153 PyErr_SetString(PyExc_ValueError
,
1154 "Invalid address type");
1160 /* More cases here... */
1163 /* If we don't know the address family, don't raise an
1164 exception -- return it as a tuple. */
1165 return Py_BuildValue("is#",
1168 sizeof(addr
->sa_data
));
1174 /* Parse a socket address argument according to the socket object's
1175 address family. Return 1 if the address was in the proper format,
1176 0 of not. The address is returned through addr_ret, its length
1180 getsockaddrarg(PySocketSockObject
*s
, PyObject
*args
,
1181 struct sockaddr
*addr_ret
, int *len_ret
)
1183 switch (s
->sock_family
) {
1185 #if defined(AF_UNIX)
1188 struct sockaddr_un
* addr
;
1191 if (!PyArg_Parse(args
, "t#", &path
, &len
))
1194 addr
= (struct sockaddr_un
*)addr_ret
;
1196 if (len
> 0 && path
[0] == 0) {
1197 /* Linux abstract namespace extension */
1198 if (len
> sizeof addr
->sun_path
) {
1199 PyErr_SetString(socket_error
,
1200 "AF_UNIX path too long");
1207 /* regular NULL-terminated string */
1208 if (len
>= sizeof addr
->sun_path
) {
1209 PyErr_SetString(socket_error
,
1210 "AF_UNIX path too long");
1213 addr
->sun_path
[len
] = 0;
1215 addr
->sun_family
= s
->sock_family
;
1216 memcpy(addr
->sun_path
, path
, len
);
1217 #if defined(PYOS_OS2)
1218 *len_ret
= sizeof(*addr
);
1220 *len_ret
= len
+ offsetof(struct sockaddr_un
, sun_path
);
1224 #endif /* AF_UNIX */
1226 #if defined(AF_NETLINK)
1229 struct sockaddr_nl
* addr
;
1231 addr
= (struct sockaddr_nl
*)addr_ret
;
1232 if (!PyTuple_Check(args
)) {
1236 "AF_NETLINK address must be tuple, not %.500s",
1237 Py_TYPE(args
)->tp_name
);
1240 if (!PyArg_ParseTuple(args
, "II:getsockaddrarg", &pid
, &groups
))
1242 addr
->nl_family
= AF_NETLINK
;
1244 addr
->nl_groups
= groups
;
1245 *len_ret
= sizeof(*addr
);
1252 struct sockaddr_in
* addr
;
1255 if (!PyTuple_Check(args
)) {
1259 "AF_INET address must be tuple, not %.500s",
1260 Py_TYPE(args
)->tp_name
);
1263 if (!PyArg_ParseTuple(args
, "eti:getsockaddrarg",
1264 "idna", &host
, &port
))
1266 addr
=(struct sockaddr_in
*)addr_ret
;
1267 result
= setipaddr(host
, (struct sockaddr
*)addr
,
1268 sizeof(*addr
), AF_INET
);
1272 if (port
< 0 || port
> 0xffff) {
1274 PyExc_OverflowError
,
1275 "getsockaddrarg: port must be 0-65535.");
1278 addr
->sin_family
= AF_INET
;
1279 addr
->sin_port
= htons((short)port
);
1280 *len_ret
= sizeof *addr
;
1287 struct sockaddr_in6
* addr
;
1289 int port
, flowinfo
, scope_id
, result
;
1290 flowinfo
= scope_id
= 0;
1291 if (!PyTuple_Check(args
)) {
1295 "AF_INET6 address must be tuple, not %.500s",
1296 Py_TYPE(args
)->tp_name
);
1299 if (!PyArg_ParseTuple(args
, "eti|ii",
1300 "idna", &host
, &port
, &flowinfo
,
1304 addr
= (struct sockaddr_in6
*)addr_ret
;
1305 result
= setipaddr(host
, (struct sockaddr
*)addr
,
1306 sizeof(*addr
), AF_INET6
);
1310 if (port
< 0 || port
> 0xffff) {
1312 PyExc_OverflowError
,
1313 "getsockaddrarg: port must be 0-65535.");
1316 addr
->sin6_family
= s
->sock_family
;
1317 addr
->sin6_port
= htons((short)port
);
1318 addr
->sin6_flowinfo
= flowinfo
;
1319 addr
->sin6_scope_id
= scope_id
;
1320 *len_ret
= sizeof *addr
;
1325 #ifdef USE_BLUETOOTH
1328 switch (s
->sock_proto
) {
1331 struct sockaddr_l2
*addr
;
1334 addr
= (struct sockaddr_l2
*)addr_ret
;
1335 memset(addr
, 0, sizeof(struct sockaddr_l2
));
1336 _BT_L2_MEMB(addr
, family
) = AF_BLUETOOTH
;
1337 if (!PyArg_ParseTuple(args
, "si", &straddr
,
1338 &_BT_L2_MEMB(addr
, psm
))) {
1339 PyErr_SetString(socket_error
, "getsockaddrarg: "
1343 if (setbdaddr(straddr
, &_BT_L2_MEMB(addr
, bdaddr
)) < 0)
1346 *len_ret
= sizeof *addr
;
1349 case BTPROTO_RFCOMM
:
1351 struct sockaddr_rc
*addr
;
1354 addr
= (struct sockaddr_rc
*)addr_ret
;
1355 _BT_RC_MEMB(addr
, family
) = AF_BLUETOOTH
;
1356 if (!PyArg_ParseTuple(args
, "si", &straddr
,
1357 &_BT_RC_MEMB(addr
, channel
))) {
1358 PyErr_SetString(socket_error
, "getsockaddrarg: "
1362 if (setbdaddr(straddr
, &_BT_RC_MEMB(addr
, bdaddr
)) < 0)
1365 *len_ret
= sizeof *addr
;
1370 struct sockaddr_hci
*addr
= (struct sockaddr_hci
*)addr_ret
;
1371 #if defined(__NetBSD__) || defined(__DragonFly__)
1372 char *straddr
= PyBytes_AS_STRING(args
);
1374 _BT_HCI_MEMB(addr
, family
) = AF_BLUETOOTH
;
1375 if (straddr
== NULL
) {
1376 PyErr_SetString(socket_error
, "getsockaddrarg: "
1380 if (setbdaddr(straddr
, &_BT_HCI_MEMB(addr
, bdaddr
)) < 0)
1383 _BT_HCI_MEMB(addr
, family
) = AF_BLUETOOTH
;
1384 if (!PyArg_ParseTuple(args
, "i", &_BT_HCI_MEMB(addr
, dev
))) {
1385 PyErr_SetString(socket_error
, "getsockaddrarg: "
1390 *len_ret
= sizeof *addr
;
1393 #if !defined(__FreeBSD__)
1396 struct sockaddr_sco
*addr
;
1399 addr
= (struct sockaddr_sco
*)addr_ret
;
1400 _BT_SCO_MEMB(addr
, family
) = AF_BLUETOOTH
;
1401 straddr
= PyString_AsString(args
);
1402 if (straddr
== NULL
) {
1403 PyErr_SetString(socket_error
, "getsockaddrarg: "
1407 if (setbdaddr(straddr
, &_BT_SCO_MEMB(addr
, bdaddr
)) < 0)
1410 *len_ret
= sizeof *addr
;
1415 PyErr_SetString(socket_error
, "getsockaddrarg: unknown Bluetooth protocol");
1421 #if defined(HAVE_NETPACKET_PACKET_H) && defined(SIOCGIFINDEX)
1424 struct sockaddr_ll
* addr
;
1426 char *interfaceName
;
1431 unsigned int halen
= 0;
1433 if (!PyTuple_Check(args
)) {
1437 "AF_PACKET address must be tuple, not %.500s",
1438 Py_TYPE(args
)->tp_name
);
1441 if (!PyArg_ParseTuple(args
, "si|iis#", &interfaceName
,
1442 &protoNumber
, &pkttype
, &hatype
,
1445 strncpy(ifr
.ifr_name
, interfaceName
, sizeof(ifr
.ifr_name
));
1446 ifr
.ifr_name
[(sizeof(ifr
.ifr_name
))-1] = '\0';
1447 if (ioctl(s
->sock_fd
, SIOCGIFINDEX
, &ifr
) < 0) {
1452 PyErr_SetString(PyExc_ValueError
,
1453 "Hardware address must be 8 bytes or less");
1456 if (protoNumber
< 0 || protoNumber
> 0xffff) {
1458 PyExc_OverflowError
,
1459 "getsockaddrarg: protoNumber must be 0-65535.");
1462 addr
= (struct sockaddr_ll
*)addr_ret
;
1463 addr
->sll_family
= AF_PACKET
;
1464 addr
->sll_protocol
= htons((short)protoNumber
);
1465 addr
->sll_ifindex
= ifr
.ifr_ifindex
;
1466 addr
->sll_pkttype
= pkttype
;
1467 addr
->sll_hatype
= hatype
;
1469 memcpy(&addr
->sll_addr
, haddr
, halen
);
1471 addr
->sll_halen
= halen
;
1472 *len_ret
= sizeof *addr
;
1477 #ifdef HAVE_LINUX_TIPC_H
1480 unsigned int atype
, v1
, v2
, v3
;
1481 unsigned int scope
= TIPC_CLUSTER_SCOPE
;
1482 struct sockaddr_tipc
*addr
;
1484 if (!PyTuple_Check(args
)) {
1488 "AF_TIPC address must be tuple, not %.500s",
1489 Py_TYPE(args
)->tp_name
);
1493 if (!PyArg_ParseTuple(args
,
1494 "IIII|I;Invalid TIPC address format",
1495 &atype
, &v1
, &v2
, &v3
, &scope
))
1498 addr
= (struct sockaddr_tipc
*) addr_ret
;
1499 memset(addr
, 0, sizeof(struct sockaddr_tipc
));
1501 addr
->family
= AF_TIPC
;
1502 addr
->scope
= scope
;
1503 addr
->addrtype
= atype
;
1505 if (atype
== TIPC_ADDR_NAMESEQ
) {
1506 addr
->addr
.nameseq
.type
= v1
;
1507 addr
->addr
.nameseq
.lower
= v2
;
1508 addr
->addr
.nameseq
.upper
= v3
;
1509 } else if (atype
== TIPC_ADDR_NAME
) {
1510 addr
->addr
.name
.name
.type
= v1
;
1511 addr
->addr
.name
.name
.instance
= v2
;
1512 } else if (atype
== TIPC_ADDR_ID
) {
1513 addr
->addr
.id
.node
= v1
;
1514 addr
->addr
.id
.ref
= v2
;
1516 /* Shouldn't happen */
1517 PyErr_SetString(PyExc_TypeError
, "Invalid address type");
1521 *len_ret
= sizeof(*addr
);
1527 /* More cases here... */
1530 PyErr_SetString(socket_error
, "getsockaddrarg: bad family");
1537 /* Get the address length according to the socket object's address family.
1538 Return 1 if the family is known, 0 otherwise. The length is returned
1542 getsockaddrlen(PySocketSockObject
*s
, socklen_t
*len_ret
)
1544 switch (s
->sock_family
) {
1546 #if defined(AF_UNIX)
1549 *len_ret
= sizeof (struct sockaddr_un
);
1552 #endif /* AF_UNIX */
1553 #if defined(AF_NETLINK)
1556 *len_ret
= sizeof (struct sockaddr_nl
);
1563 *len_ret
= sizeof (struct sockaddr_in
);
1570 *len_ret
= sizeof (struct sockaddr_in6
);
1575 #ifdef USE_BLUETOOTH
1578 switch(s
->sock_proto
)
1582 *len_ret
= sizeof (struct sockaddr_l2
);
1584 case BTPROTO_RFCOMM
:
1585 *len_ret
= sizeof (struct sockaddr_rc
);
1588 *len_ret
= sizeof (struct sockaddr_hci
);
1590 #if !defined(__FreeBSD__)
1592 *len_ret
= sizeof (struct sockaddr_sco
);
1596 PyErr_SetString(socket_error
, "getsockaddrlen: "
1597 "unknown BT protocol");
1604 #ifdef HAVE_NETPACKET_PACKET_H
1607 *len_ret
= sizeof (struct sockaddr_ll
);
1612 #ifdef HAVE_LINUX_TIPC_H
1615 *len_ret
= sizeof (struct sockaddr_tipc
);
1620 /* More cases here... */
1623 PyErr_SetString(socket_error
, "getsockaddrlen: bad family");
1630 /* s.accept() method */
1633 sock_accept(PySocketSockObject
*s
)
1635 sock_addr_t addrbuf
;
1638 PyObject
*sock
= NULL
;
1639 PyObject
*addr
= NULL
;
1640 PyObject
*res
= NULL
;
1643 if (!getsockaddrlen(s
, &addrlen
))
1645 memset(&addrbuf
, 0, addrlen
);
1648 newfd
= INVALID_SOCKET
;
1653 if (!IS_SELECTABLE(s
))
1654 return select_error();
1656 Py_BEGIN_ALLOW_THREADS
1657 timeout
= internal_select(s
, 0);
1659 newfd
= accept(s
->sock_fd
, SAS2SA(&addrbuf
), &addrlen
);
1660 Py_END_ALLOW_THREADS
1663 PyErr_SetString(socket_timeout
, "timed out");
1668 if (newfd
== INVALID_SOCKET
)
1672 return s
->errorhandler();
1674 /* Create the new object with unspecified family,
1675 to avoid calls to bind() etc. on it. */
1676 sock
= (PyObject
*) new_sockobject(newfd
,
1685 addr
= makesockaddr(s
->sock_fd
, SAS2SA(&addrbuf
),
1686 addrlen
, s
->sock_proto
);
1690 res
= PyTuple_Pack(2, sock
, addr
);
1698 PyDoc_STRVAR(accept_doc
,
1699 "accept() -> (socket object, address info)\n\
1701 Wait for an incoming connection. Return a new socket representing the\n\
1702 connection, and the address of the client. For IP sockets, the address\n\
1703 info is a pair (hostaddr, port).");
1705 /* s.setblocking(flag) method. Argument:
1706 False -- non-blocking mode; same as settimeout(0)
1707 True -- blocking mode; same as settimeout(None)
1711 sock_setblocking(PySocketSockObject
*s
, PyObject
*arg
)
1715 block
= PyInt_AsLong(arg
);
1716 if (block
== -1 && PyErr_Occurred())
1719 s
->sock_timeout
= block
? -1.0 : 0.0;
1720 internal_setblocking(s
, block
);
1726 PyDoc_STRVAR(setblocking_doc
,
1727 "setblocking(flag)\n\
1729 Set the socket to blocking (flag is true) or non-blocking (false).\n\
1730 setblocking(True) is equivalent to settimeout(None);\n\
1731 setblocking(False) is equivalent to settimeout(0.0).");
1733 /* s.settimeout(timeout) method. Argument:
1734 None -- no timeout, blocking mode; same as setblocking(True)
1735 0.0 -- non-blocking mode; same as setblocking(False)
1736 > 0 -- timeout mode; operations time out after timeout seconds
1737 < 0 -- illegal; raises an exception
1740 sock_settimeout(PySocketSockObject
*s
, PyObject
*arg
)
1747 timeout
= PyFloat_AsDouble(arg
);
1748 if (timeout
< 0.0) {
1749 if (!PyErr_Occurred())
1750 PyErr_SetString(PyExc_ValueError
,
1751 "Timeout value out of range");
1756 s
->sock_timeout
= timeout
;
1757 internal_setblocking(s
, timeout
< 0.0);
1763 PyDoc_STRVAR(settimeout_doc
,
1764 "settimeout(timeout)\n\
1766 Set a timeout on socket operations. 'timeout' can be a float,\n\
1767 giving in seconds, or None. Setting a timeout of None disables\n\
1768 the timeout feature and is equivalent to setblocking(1).\n\
1769 Setting a timeout of zero is the same as setblocking(0).");
1771 /* s.gettimeout() method.
1772 Returns the timeout associated with a socket. */
1774 sock_gettimeout(PySocketSockObject
*s
)
1776 if (s
->sock_timeout
< 0.0) {
1781 return PyFloat_FromDouble(s
->sock_timeout
);
1784 PyDoc_STRVAR(gettimeout_doc
,
1785 "gettimeout() -> timeout\n\
1787 Returns the timeout in floating seconds associated with socket \n\
1788 operations. A timeout of None indicates that timeouts on socket \n\
1789 operations are disabled.");
1792 /* s.sleeptaskw(1 | 0) method */
1795 sock_sleeptaskw(PySocketSockObject
*s
,PyObject
*arg
)
1798 block
= PyInt_AsLong(arg
);
1799 if (block
== -1 && PyErr_Occurred())
1801 Py_BEGIN_ALLOW_THREADS
1802 socketioctl(s
->sock_fd
, 0x80046679, (u_long
*)&block
);
1803 Py_END_ALLOW_THREADS
1808 PyDoc_STRVAR(sleeptaskw_doc
,
1809 "sleeptaskw(flag)\n\
1811 Allow sleeps in taskwindows.");
1815 /* s.setsockopt() method.
1816 With an integer third argument, sets an integer option.
1817 With a string third argument, sets an option from a buffer;
1818 use optional built-in module 'struct' to encode the string. */
1821 sock_setsockopt(PySocketSockObject
*s
, PyObject
*args
)
1830 if (PyArg_ParseTuple(args
, "iii:setsockopt",
1831 &level
, &optname
, &flag
)) {
1832 buf
= (char *) &flag
;
1833 buflen
= sizeof flag
;
1837 if (!PyArg_ParseTuple(args
, "iis#:setsockopt",
1838 &level
, &optname
, &buf
, &buflen
))
1841 res
= setsockopt(s
->sock_fd
, level
, optname
, (void *)buf
, buflen
);
1843 return s
->errorhandler();
1848 PyDoc_STRVAR(setsockopt_doc
,
1849 "setsockopt(level, option, value)\n\
1851 Set a socket option. See the Unix manual for level and option.\n\
1852 The value argument can either be an integer or a string.");
1855 /* s.getsockopt() method.
1856 With two arguments, retrieves an integer option.
1857 With a third integer argument, retrieves a string buffer of that size;
1858 use optional built-in module 'struct' to decode the string. */
1861 sock_getsockopt(PySocketSockObject
*s
, PyObject
*args
)
1867 socklen_t buflen
= 0;
1870 /* We have incomplete socket support. */
1871 PyErr_SetString(socket_error
, "getsockopt not supported");
1875 if (!PyArg_ParseTuple(args
, "ii|i:getsockopt",
1876 &level
, &optname
, &buflen
))
1881 socklen_t flagsize
= sizeof flag
;
1882 res
= getsockopt(s
->sock_fd
, level
, optname
,
1883 (void *)&flag
, &flagsize
);
1885 return s
->errorhandler();
1886 return PyInt_FromLong(flag
);
1889 /* socklen_t is unsigned so no negative test is needed,
1890 test buflen == 0 is previously done */
1891 if (buflen
> 1024) {
1893 if (buflen
<= 0 || buflen
> 1024) {
1895 PyErr_SetString(socket_error
,
1896 "getsockopt buflen out of range");
1899 buf
= PyString_FromStringAndSize((char *)NULL
, buflen
);
1902 res
= getsockopt(s
->sock_fd
, level
, optname
,
1903 (void *)PyString_AS_STRING(buf
), &buflen
);
1906 return s
->errorhandler();
1908 _PyString_Resize(&buf
, buflen
);
1910 #endif /* __BEOS__ */
1913 PyDoc_STRVAR(getsockopt_doc
,
1914 "getsockopt(level, option[, buffersize]) -> value\n\
1916 Get a socket option. See the Unix manual for level and option.\n\
1917 If a nonzero buffersize argument is given, the return value is a\n\
1918 string of that length; otherwise it is an integer.");
1921 /* s.bind(sockaddr) method */
1924 sock_bind(PySocketSockObject
*s
, PyObject
*addro
)
1926 sock_addr_t addrbuf
;
1930 if (!getsockaddrarg(s
, addro
, SAS2SA(&addrbuf
), &addrlen
))
1932 Py_BEGIN_ALLOW_THREADS
1933 res
= bind(s
->sock_fd
, SAS2SA(&addrbuf
), addrlen
);
1934 Py_END_ALLOW_THREADS
1936 return s
->errorhandler();
1941 PyDoc_STRVAR(bind_doc
,
1944 Bind the socket to a local address. For IP sockets, the address is a\n\
1945 pair (host, port); the host must refer to the local host. For raw packet\n\
1946 sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");
1949 /* s.close() method.
1950 Set the file descriptor to -1 so operations tried subsequently
1951 will surely fail. */
1954 sock_close(PySocketSockObject
*s
)
1958 if ((fd
= s
->sock_fd
) != -1) {
1960 Py_BEGIN_ALLOW_THREADS
1961 (void) SOCKETCLOSE(fd
);
1962 Py_END_ALLOW_THREADS
1968 PyDoc_STRVAR(close_doc
,
1971 Close the socket. It cannot be used after this call.");
1974 internal_connect(PySocketSockObject
*s
, struct sockaddr
*addr
, int addrlen
,
1980 res
= connect(s
->sock_fd
, addr
, addrlen
);
1984 if (s
->sock_timeout
> 0.0) {
1985 if (res
< 0 && WSAGetLastError() == WSAEWOULDBLOCK
&&
1987 /* This is a mess. Best solution: trust select */
1991 tv
.tv_sec
= (int)s
->sock_timeout
;
1992 tv
.tv_usec
= (int)((s
->sock_timeout
- tv
.tv_sec
) * 1e6
);
1994 FD_SET(s
->sock_fd
, &fds
);
1996 FD_SET(s
->sock_fd
, &fds_exc
);
1997 res
= select(s
->sock_fd
+1, NULL
, &fds
, &fds_exc
, &tv
);
1999 res
= WSAEWOULDBLOCK
;
2001 } else if (res
> 0) {
2002 if (FD_ISSET(s
->sock_fd
, &fds
))
2003 /* The socket is in the writeable set - this
2007 /* As per MS docs, we need to call getsockopt()
2008 to get the underlying error */
2009 int res_size
= sizeof res
;
2010 /* It must be in the exception set */
2011 assert(FD_ISSET(s
->sock_fd
, &fds_exc
));
2012 if (0 == getsockopt(s
->sock_fd
, SOL_SOCKET
, SO_ERROR
,
2013 (char *)&res
, &res_size
))
2014 /* getsockopt also clears WSAGetLastError,
2015 so reset it back. */
2016 WSASetLastError(res
);
2018 res
= WSAGetLastError();
2021 /* else if (res < 0) an error occurred */
2026 res
= WSAGetLastError();
2030 if (s
->sock_timeout
> 0.0) {
2031 if (res
< 0 && errno
== EINPROGRESS
&& IS_SELECTABLE(s
)) {
2032 timeout
= internal_select(s
, 1);
2034 /* Bug #1019808: in case of an EINPROGRESS,
2035 use getsockopt(SO_ERROR) to get the real
2037 socklen_t res_size
= sizeof res
;
2038 (void)getsockopt(s
->sock_fd
, SOL_SOCKET
,
2039 SO_ERROR
, &res
, &res_size
);
2044 else if (timeout
== -1) {
2045 res
= errno
; /* had error */
2048 res
= EWOULDBLOCK
; /* timed out */
2056 *timeoutp
= timeout
;
2061 /* s.connect(sockaddr) method */
2064 sock_connect(PySocketSockObject
*s
, PyObject
*addro
)
2066 sock_addr_t addrbuf
;
2071 if (!getsockaddrarg(s
, addro
, SAS2SA(&addrbuf
), &addrlen
))
2074 Py_BEGIN_ALLOW_THREADS
2075 res
= internal_connect(s
, SAS2SA(&addrbuf
), addrlen
, &timeout
);
2076 Py_END_ALLOW_THREADS
2079 PyErr_SetString(socket_timeout
, "timed out");
2083 return s
->errorhandler();
2088 PyDoc_STRVAR(connect_doc
,
2089 "connect(address)\n\
2091 Connect the socket to a remote address. For IP sockets, the address\n\
2092 is a pair (host, port).");
2095 /* s.connect_ex(sockaddr) method */
2098 sock_connect_ex(PySocketSockObject
*s
, PyObject
*addro
)
2100 sock_addr_t addrbuf
;
2105 if (!getsockaddrarg(s
, addro
, SAS2SA(&addrbuf
), &addrlen
))
2108 Py_BEGIN_ALLOW_THREADS
2109 res
= internal_connect(s
, SAS2SA(&addrbuf
), addrlen
, &timeout
);
2110 Py_END_ALLOW_THREADS
2112 /* Signals are not errors (though they may raise exceptions). Adapted
2113 from PyErr_SetFromErrnoWithFilenameObject(). */
2115 if (res
== EINTR
&& PyErr_CheckSignals())
2119 return PyInt_FromLong((long) res
);
2122 PyDoc_STRVAR(connect_ex_doc
,
2123 "connect_ex(address) -> errno\n\
2125 This is like connect(address), but returns an error code (the errno value)\n\
2126 instead of raising an exception when an error occurs.");
2129 /* s.fileno() method */
2132 sock_fileno(PySocketSockObject
*s
)
2134 #if SIZEOF_SOCKET_T <= SIZEOF_LONG
2135 return PyInt_FromLong((long) s
->sock_fd
);
2137 return PyLong_FromLongLong((PY_LONG_LONG
)s
->sock_fd
);
2141 PyDoc_STRVAR(fileno_doc
,
2142 "fileno() -> integer\n\
2144 Return the integer file descriptor of the socket.");
2148 /* s.dup() method */
2151 sock_dup(PySocketSockObject
*s
)
2156 newfd
= dup(s
->sock_fd
);
2158 return s
->errorhandler();
2159 sock
= (PyObject
*) new_sockobject(newfd
,
2168 PyDoc_STRVAR(dup_doc
,
2169 "dup() -> socket object\n\
2171 Return a new socket object connected to the same system resource.");
2176 /* s.getsockname() method */
2179 sock_getsockname(PySocketSockObject
*s
)
2181 sock_addr_t addrbuf
;
2185 if (!getsockaddrlen(s
, &addrlen
))
2187 memset(&addrbuf
, 0, addrlen
);
2188 Py_BEGIN_ALLOW_THREADS
2189 res
= getsockname(s
->sock_fd
, SAS2SA(&addrbuf
), &addrlen
);
2190 Py_END_ALLOW_THREADS
2192 return s
->errorhandler();
2193 return makesockaddr(s
->sock_fd
, SAS2SA(&addrbuf
), addrlen
,
2197 PyDoc_STRVAR(getsockname_doc
,
2198 "getsockname() -> address info\n\
2200 Return the address of the local endpoint. For IP sockets, the address\n\
2201 info is a pair (hostaddr, port).");
2204 #ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
2205 /* s.getpeername() method */
2208 sock_getpeername(PySocketSockObject
*s
)
2210 sock_addr_t addrbuf
;
2214 if (!getsockaddrlen(s
, &addrlen
))
2216 memset(&addrbuf
, 0, addrlen
);
2217 Py_BEGIN_ALLOW_THREADS
2218 res
= getpeername(s
->sock_fd
, SAS2SA(&addrbuf
), &addrlen
);
2219 Py_END_ALLOW_THREADS
2221 return s
->errorhandler();
2222 return makesockaddr(s
->sock_fd
, SAS2SA(&addrbuf
), addrlen
,
2226 PyDoc_STRVAR(getpeername_doc
,
2227 "getpeername() -> address info\n\
2229 Return the address of the remote endpoint. For IP sockets, the address\n\
2230 info is a pair (hostaddr, port).");
2232 #endif /* HAVE_GETPEERNAME */
2235 /* s.listen(n) method */
2238 sock_listen(PySocketSockObject
*s
, PyObject
*arg
)
2243 backlog
= PyInt_AsLong(arg
);
2244 if (backlog
== -1 && PyErr_Occurred())
2246 Py_BEGIN_ALLOW_THREADS
2247 /* To avoid problems on systems that don't allow a negative backlog
2248 * (which doesn't make sense anyway) we force a minimum value of 0. */
2251 res
= listen(s
->sock_fd
, backlog
);
2252 Py_END_ALLOW_THREADS
2254 return s
->errorhandler();
2259 PyDoc_STRVAR(listen_doc
,
2262 Enable a server to accept connections. The backlog argument must be at\n\
2263 least 0 (if it is lower, it is set to 0); it specifies the number of\n\
2264 unaccepted connections that the system will allow before refusing new\n\
2269 /* s.makefile(mode) method.
2270 Create a new open file object referring to a dupped version of
2271 the socket's file descriptor. (The dup() call is necessary so
2272 that the open file and socket objects may be closed independent
2274 The mode argument specifies 'r' or 'w' passed to fdopen(). */
2277 sock_makefile(PySocketSockObject
*s
, PyObject
*args
)
2279 extern int fclose(FILE *);
2294 if (!PyArg_ParseTuple(args
, "|si:makefile", &mode
, &bufsize
))
2297 if (strcmp(mode
,"rb") == 0) {
2301 if (strcmp(mode
,"wb") == 0) {
2307 if (((fd
= _open_osfhandle(s
->sock_fd
, _O_BINARY
)) < 0) ||
2308 ((fd
= dup(fd
)) < 0) || ((fp
= fdopen(fd
, mode
)) == NULL
))
2310 if ((fd
= dup(s
->sock_fd
)) < 0 || (fp
= fdopen(fd
, mode
)) == NULL
)
2315 return s
->errorhandler();
2317 f
= PyFile_FromFile(fp
, "<socket>", mode
, fclose
);
2319 PyFile_SetBufSize(f
, bufsize
);
2323 PyDoc_STRVAR(makefile_doc
,
2324 "makefile([mode[, buffersize]]) -> file object\n\
2326 Return a regular file object corresponding to the socket.\n\
2327 The mode and buffersize arguments are as for the built-in open() function.");
2332 * This is the guts of the recv() and recv_into() methods, which reads into a
2333 * char buffer. If you have any inc/dec ref to do to the objects that contain
2334 * the buffer, do it in the caller. This function returns the number of bytes
2335 * successfully read. If there was an error, it returns -1. Note that it is
2336 * also possible that we return a number of bytes smaller than the request
2340 sock_recv_guts(PySocketSockObject
*s
, char* cbuf
, int len
, int flags
)
2342 ssize_t outlen
= -1;
2349 if (!IS_SELECTABLE(s
)) {
2355 Py_BEGIN_ALLOW_THREADS
2356 timeout
= internal_select(s
, 0);
2358 outlen
= recv(s
->sock_fd
, cbuf
, len
, flags
);
2359 Py_END_ALLOW_THREADS
2362 PyErr_SetString(socket_timeout
, "timed out");
2366 /* Note: the call to errorhandler() ALWAYS indirectly returned
2367 NULL, so ignore its return value */
2374 while (remaining
!= 0) {
2375 unsigned int segment
;
2378 segment
= remaining
/SEGMENT_SIZE
;
2380 segment
= SEGMENT_SIZE
;
2383 segment
= remaining
;
2386 Py_BEGIN_ALLOW_THREADS
2387 timeout
= internal_select(s
, 0);
2389 nread
= recv(s
->sock_fd
, read_buf
, segment
, flags
);
2390 Py_END_ALLOW_THREADS
2393 PyErr_SetString(socket_timeout
, "timed out");
2400 if (nread
!= remaining
) {
2405 remaining
-= segment
;
2406 read_buf
+= segment
;
2408 outlen
= read_buf
- cbuf
;
2415 /* s.recv(nbytes [,flags]) method */
2418 sock_recv(PySocketSockObject
*s
, PyObject
*args
)
2420 int recvlen
, flags
= 0;
2424 if (!PyArg_ParseTuple(args
, "i|i:recv", &recvlen
, &flags
))
2428 PyErr_SetString(PyExc_ValueError
,
2429 "negative buffersize in recv");
2433 /* Allocate a new string. */
2434 buf
= PyString_FromStringAndSize((char *) 0, recvlen
);
2439 outlen
= sock_recv_guts(s
, PyString_AS_STRING(buf
), recvlen
, flags
);
2441 /* An error occurred, release the string and return an
2446 if (outlen
!= recvlen
) {
2447 /* We did not read as many bytes as we anticipated, resize the
2448 string if possible and be successful. */
2449 if (_PyString_Resize(&buf
, outlen
) < 0)
2450 /* Oopsy, not so successful after all. */
2457 PyDoc_STRVAR(recv_doc
,
2458 "recv(buffersize[, flags]) -> data\n\
2460 Receive up to buffersize bytes from the socket. For the optional flags\n\
2461 argument, see the Unix manual. When no data is available, block until\n\
2462 at least one byte is available or until the remote end is closed. When\n\
2463 the remote end is closed and all data is read, return the empty string.");
2466 /* s.recv_into(buffer, [nbytes [,flags]]) method */
2469 sock_recv_into(PySocketSockObject
*s
, PyObject
*args
, PyObject
*kwds
)
2471 static char *kwlist
[] = {"buffer", "nbytes", "flags", 0};
2473 int recvlen
= 0, flags
= 0;
2478 /* Get the buffer's memory */
2479 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "w*|ii:recv_into", kwlist
,
2480 &buf
, &recvlen
, &flags
))
2483 assert(buf
.buf
!= 0 && buflen
> 0);
2486 PyErr_SetString(PyExc_ValueError
,
2487 "negative buffersize in recv_into");
2491 /* If nbytes was not specified, use the buffer's length */
2495 /* Check if the buffer is large enough */
2496 if (buflen
< recvlen
) {
2497 PyErr_SetString(PyExc_ValueError
,
2498 "buffer too small for requested bytes");
2503 readlen
= sock_recv_guts(s
, buf
.buf
, recvlen
, flags
);
2505 /* Return an error. */
2509 PyBuffer_Release(&buf
);
2510 /* Return the number of bytes read. Note that we do not do anything
2511 special here in the case that readlen < recvlen. */
2512 return PyInt_FromSsize_t(readlen
);
2515 PyBuffer_Release(&buf
);
2519 PyDoc_STRVAR(recv_into_doc
,
2520 "recv_into(buffer, [nbytes[, flags]]) -> nbytes_read\n\
2522 A version of recv() that stores its data into a buffer rather than creating \n\
2523 a new string. Receive up to buffersize bytes from the socket. If buffersize \n\
2524 is not specified (or 0), receive up to the size available in the given buffer.\n\
2526 See recv() for documentation about the flags.");
2530 * This is the guts of the recvfrom() and recvfrom_into() methods, which reads
2531 * into a char buffer. If you have any inc/def ref to do to the objects that
2532 * contain the buffer, do it in the caller. This function returns the number
2533 * of bytes successfully read. If there was an error, it returns -1. Note
2534 * that it is also possible that we return a number of bytes smaller than the
2537 * 'addr' is a return value for the address object. Note that you must decref
2541 sock_recvfrom_guts(PySocketSockObject
*s
, char* cbuf
, int len
, int flags
,
2544 sock_addr_t addrbuf
;
2551 if (!getsockaddrlen(s
, &addrlen
))
2554 if (!IS_SELECTABLE(s
)) {
2559 Py_BEGIN_ALLOW_THREADS
2560 memset(&addrbuf
, 0, addrlen
);
2561 timeout
= internal_select(s
, 0);
2564 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
2565 n
= recvfrom(s
->sock_fd
, cbuf
, len
, flags
,
2566 SAS2SA(&addrbuf
), &addrlen
);
2568 n
= recvfrom(s
->sock_fd
, cbuf
, len
, flags
,
2569 (void *) &addrbuf
, &addrlen
);
2572 n
= recvfrom(s
->sock_fd
, cbuf
, len
, flags
,
2573 SAS2SA(&addrbuf
), &addrlen
);
2576 Py_END_ALLOW_THREADS
2579 PyErr_SetString(socket_timeout
, "timed out");
2587 if (!(*addr
= makesockaddr(s
->sock_fd
, SAS2SA(&addrbuf
),
2588 addrlen
, s
->sock_proto
)))
2594 /* s.recvfrom(nbytes [,flags]) method */
2597 sock_recvfrom(PySocketSockObject
*s
, PyObject
*args
)
2599 PyObject
*buf
= NULL
;
2600 PyObject
*addr
= NULL
;
2601 PyObject
*ret
= NULL
;
2602 int recvlen
, flags
= 0;
2605 if (!PyArg_ParseTuple(args
, "i|i:recvfrom", &recvlen
, &flags
))
2609 PyErr_SetString(PyExc_ValueError
,
2610 "negative buffersize in recvfrom");
2614 buf
= PyString_FromStringAndSize((char *) 0, recvlen
);
2618 outlen
= sock_recvfrom_guts(s
, PyString_AS_STRING(buf
),
2619 recvlen
, flags
, &addr
);
2624 if (outlen
!= recvlen
) {
2625 /* We did not read as many bytes as we anticipated, resize the
2626 string if possible and be successful. */
2627 if (_PyString_Resize(&buf
, outlen
) < 0)
2628 /* Oopsy, not so successful after all. */
2632 ret
= PyTuple_Pack(2, buf
, addr
);
2640 PyDoc_STRVAR(recvfrom_doc
,
2641 "recvfrom(buffersize[, flags]) -> (data, address info)\n\
2643 Like recv(buffersize, flags) but also return the sender's address info.");
2646 /* s.recvfrom_into(buffer[, nbytes [,flags]]) method */
2649 sock_recvfrom_into(PySocketSockObject
*s
, PyObject
*args
, PyObject
* kwds
)
2651 static char *kwlist
[] = {"buffer", "nbytes", "flags", 0};
2653 int recvlen
= 0, flags
= 0;
2658 PyObject
*addr
= NULL
;
2660 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "w*|ii:recvfrom_into",
2665 assert(buf
.buf
!= 0 && buflen
> 0);
2668 PyErr_SetString(PyExc_ValueError
,
2669 "negative buffersize in recvfrom_into");
2673 /* If nbytes was not specified, use the buffer's length */
2677 readlen
= sock_recvfrom_guts(s
, buf
.buf
, recvlen
, flags
, &addr
);
2679 /* Return an error */
2683 PyBuffer_Release(&buf
);
2684 /* Return the number of bytes read and the address. Note that we do
2685 not do anything special here in the case that readlen < recvlen. */
2686 return Py_BuildValue("lN", readlen
, addr
);
2690 PyBuffer_Release(&buf
);
2694 PyDoc_STRVAR(recvfrom_into_doc
,
2695 "recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)\n\
2697 Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.");
2700 /* s.send(data [,flags]) method */
2703 sock_send(PySocketSockObject
*s
, PyObject
*args
)
2706 int len
, n
= -1, flags
= 0, timeout
;
2709 if (!PyArg_ParseTuple(args
, "s*|i:send", &pbuf
, &flags
))
2712 if (!IS_SELECTABLE(s
)) {
2713 PyBuffer_Release(&pbuf
);
2714 return select_error();
2719 Py_BEGIN_ALLOW_THREADS
2720 timeout
= internal_select(s
, 1);
2723 n
= sendsegmented(s
->sock_fd
, buf
, len
, flags
);
2725 n
= send(s
->sock_fd
, buf
, len
, flags
);
2727 Py_END_ALLOW_THREADS
2729 PyBuffer_Release(&pbuf
);
2732 PyErr_SetString(socket_timeout
, "timed out");
2736 return s
->errorhandler();
2737 return PyInt_FromLong((long)n
);
2740 PyDoc_STRVAR(send_doc
,
2741 "send(data[, flags]) -> count\n\
2743 Send a data string to the socket. For the optional flags\n\
2744 argument, see the Unix manual. Return the number of bytes\n\
2745 sent; this may be less than len(data) if the network is busy.");
2748 /* s.sendall(data [,flags]) method */
2751 sock_sendall(PySocketSockObject
*s
, PyObject
*args
)
2754 int len
, n
= -1, flags
= 0, timeout
, saved_errno
;
2757 if (!PyArg_ParseTuple(args
, "s*|i:sendall", &pbuf
, &flags
))
2762 if (!IS_SELECTABLE(s
)) {
2763 PyBuffer_Release(&pbuf
);
2764 return select_error();
2768 Py_BEGIN_ALLOW_THREADS
2769 timeout
= internal_select(s
, 1);
2773 n
= sendsegmented(s
->sock_fd
, buf
, len
, flags
);
2775 n
= send(s
->sock_fd
, buf
, len
, flags
);
2778 Py_END_ALLOW_THREADS
2780 PyBuffer_Release(&pbuf
);
2781 PyErr_SetString(socket_timeout
, "timed out");
2784 /* PyErr_CheckSignals() might change errno */
2785 saved_errno
= errno
;
2786 /* We must run our signal handlers before looping again.
2787 send() can return a successful partial write when it is
2788 interrupted, so we can't restrict ourselves to EINTR. */
2789 if (PyErr_CheckSignals()) {
2790 PyBuffer_Release(&pbuf
);
2794 /* If interrupted, try again */
2795 if (saved_errno
== EINTR
)
2803 PyBuffer_Release(&pbuf
);
2806 return s
->errorhandler();
2812 PyDoc_STRVAR(sendall_doc
,
2813 "sendall(data[, flags])\n\
2815 Send a data string to the socket. For the optional flags\n\
2816 argument, see the Unix manual. This calls send() repeatedly\n\
2817 until all data is sent. If an error occurs, it's impossible\n\
2818 to tell how much data has been sent.");
2821 /* s.sendto(data, [flags,] sockaddr) method */
2824 sock_sendto(PySocketSockObject
*s
, PyObject
*args
)
2830 sock_addr_t addrbuf
;
2831 int addrlen
, n
= -1, flags
, timeout
;
2835 arglen
= PyTuple_Size(args
);
2838 PyArg_ParseTuple(args
, "s*O:sendto", &pbuf
, &addro
);
2841 PyArg_ParseTuple(args
, "s*iO:sendto", &pbuf
, &flags
, &addro
);
2844 PyErr_Format(PyExc_TypeError
, "sendto() takes 2 or 3"
2845 " arguments (%d given)", arglen
);
2847 if (PyErr_Occurred())
2853 if (!IS_SELECTABLE(s
)) {
2854 PyBuffer_Release(&pbuf
);
2855 return select_error();
2858 if (!getsockaddrarg(s
, addro
, SAS2SA(&addrbuf
), &addrlen
)) {
2859 PyBuffer_Release(&pbuf
);
2863 Py_BEGIN_ALLOW_THREADS
2864 timeout
= internal_select(s
, 1);
2866 n
= sendto(s
->sock_fd
, buf
, len
, flags
, SAS2SA(&addrbuf
), addrlen
);
2867 Py_END_ALLOW_THREADS
2869 PyBuffer_Release(&pbuf
);
2871 PyErr_SetString(socket_timeout
, "timed out");
2875 return s
->errorhandler();
2876 return PyInt_FromLong((long)n
);
2879 PyDoc_STRVAR(sendto_doc
,
2880 "sendto(data[, flags], address) -> count\n\
2882 Like send(data, flags) but allows specifying the destination address.\n\
2883 For IP sockets, the address is a pair (hostaddr, port).");
2886 /* s.shutdown(how) method */
2889 sock_shutdown(PySocketSockObject
*s
, PyObject
*arg
)
2894 how
= PyInt_AsLong(arg
);
2895 if (how
== -1 && PyErr_Occurred())
2897 Py_BEGIN_ALLOW_THREADS
2898 res
= shutdown(s
->sock_fd
, how
);
2899 Py_END_ALLOW_THREADS
2901 return s
->errorhandler();
2906 PyDoc_STRVAR(shutdown_doc
,
2909 Shut down the reading side of the socket (flag == SHUT_RD), the writing side\n\
2910 of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).");
2912 #if defined(MS_WINDOWS) && defined(SIO_RCVALL)
2914 sock_ioctl(PySocketSockObject
*s
, PyObject
*arg
)
2916 unsigned long cmd
= SIO_RCVALL
;
2920 if (!PyArg_ParseTuple(arg
, "kO:ioctl", &cmd
, &argO
))
2925 unsigned int option
= RCVALL_ON
;
2926 if (!PyArg_ParseTuple(arg
, "kI:ioctl", &cmd
, &option
))
2928 if (WSAIoctl(s
->sock_fd
, cmd
, &option
, sizeof(option
),
2929 NULL
, 0, &recv
, NULL
, NULL
) == SOCKET_ERROR
) {
2932 return PyLong_FromUnsignedLong(recv
); }
2933 case SIO_KEEPALIVE_VALS
: {
2934 struct tcp_keepalive ka
;
2935 if (!PyArg_ParseTuple(arg
, "k(kkk):ioctl", &cmd
,
2936 &ka
.onoff
, &ka
.keepalivetime
, &ka
.keepaliveinterval
))
2938 if (WSAIoctl(s
->sock_fd
, cmd
, &ka
, sizeof(ka
),
2939 NULL
, 0, &recv
, NULL
, NULL
) == SOCKET_ERROR
) {
2942 return PyLong_FromUnsignedLong(recv
); }
2944 PyErr_Format(PyExc_ValueError
, "invalid ioctl command %d", cmd
);
2948 PyDoc_STRVAR(sock_ioctl_doc
,
2949 "ioctl(cmd, option) -> long\n\
2951 Control the socket with WSAIoctl syscall. Currently supported 'cmd' values are\n\
2952 SIO_RCVALL: 'option' must be one of the socket.RCVALL_* constants.\n\
2953 SIO_KEEPALIVE_VALS: 'option' is a tuple of (onoff, timeout, interval).");
2957 /* List of methods for socket objects */
2959 static PyMethodDef sock_methods
[] = {
2960 {"accept", (PyCFunction
)sock_accept
, METH_NOARGS
,
2962 {"bind", (PyCFunction
)sock_bind
, METH_O
,
2964 {"close", (PyCFunction
)sock_close
, METH_NOARGS
,
2966 {"connect", (PyCFunction
)sock_connect
, METH_O
,
2968 {"connect_ex", (PyCFunction
)sock_connect_ex
, METH_O
,
2971 {"dup", (PyCFunction
)sock_dup
, METH_NOARGS
,
2974 {"fileno", (PyCFunction
)sock_fileno
, METH_NOARGS
,
2976 #ifdef HAVE_GETPEERNAME
2977 {"getpeername", (PyCFunction
)sock_getpeername
,
2978 METH_NOARGS
, getpeername_doc
},
2980 {"getsockname", (PyCFunction
)sock_getsockname
,
2981 METH_NOARGS
, getsockname_doc
},
2982 {"getsockopt", (PyCFunction
)sock_getsockopt
, METH_VARARGS
,
2984 #if defined(MS_WINDOWS) && defined(SIO_RCVALL)
2985 {"ioctl", (PyCFunction
)sock_ioctl
, METH_VARARGS
,
2988 {"listen", (PyCFunction
)sock_listen
, METH_O
,
2991 {"makefile", (PyCFunction
)sock_makefile
, METH_VARARGS
,
2994 {"recv", (PyCFunction
)sock_recv
, METH_VARARGS
,
2996 {"recv_into", (PyCFunction
)sock_recv_into
, METH_VARARGS
| METH_KEYWORDS
,
2998 {"recvfrom", (PyCFunction
)sock_recvfrom
, METH_VARARGS
,
3000 {"recvfrom_into", (PyCFunction
)sock_recvfrom_into
, METH_VARARGS
| METH_KEYWORDS
,
3002 {"send", (PyCFunction
)sock_send
, METH_VARARGS
,
3004 {"sendall", (PyCFunction
)sock_sendall
, METH_VARARGS
,
3006 {"sendto", (PyCFunction
)sock_sendto
, METH_VARARGS
,
3008 {"setblocking", (PyCFunction
)sock_setblocking
, METH_O
,
3010 {"settimeout", (PyCFunction
)sock_settimeout
, METH_O
,
3012 {"gettimeout", (PyCFunction
)sock_gettimeout
, METH_NOARGS
,
3014 {"setsockopt", (PyCFunction
)sock_setsockopt
, METH_VARARGS
,
3016 {"shutdown", (PyCFunction
)sock_shutdown
, METH_O
,
3019 {"sleeptaskw", (PyCFunction
)sock_sleeptaskw
, METH_O
,
3022 {NULL
, NULL
} /* sentinel */
3025 /* SockObject members */
3026 static PyMemberDef sock_memberlist
[] = {
3027 {"family", T_INT
, offsetof(PySocketSockObject
, sock_family
), READONLY
, "the socket family"},
3028 {"type", T_INT
, offsetof(PySocketSockObject
, sock_type
), READONLY
, "the socket type"},
3029 {"proto", T_INT
, offsetof(PySocketSockObject
, sock_proto
), READONLY
, "the socket protocol"},
3030 {"timeout", T_DOUBLE
, offsetof(PySocketSockObject
, sock_timeout
), READONLY
, "the socket timeout"},
3034 /* Deallocate a socket object in response to the last Py_DECREF().
3035 First close the file description. */
3038 sock_dealloc(PySocketSockObject
*s
)
3040 if (s
->sock_fd
!= -1)
3041 (void) SOCKETCLOSE(s
->sock_fd
);
3042 Py_TYPE(s
)->tp_free((PyObject
*)s
);
3047 sock_repr(PySocketSockObject
*s
)
3050 #if SIZEOF_SOCKET_T > SIZEOF_LONG
3051 if (s
->sock_fd
> LONG_MAX
) {
3052 /* this can occur on Win64, and actually there is a special
3053 ugly printf formatter for decimal pointer length integer
3054 printing, only bother if necessary*/
3055 PyErr_SetString(PyExc_OverflowError
,
3056 "no printf formatter to display "
3057 "the socket descriptor in decimal");
3063 "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
3064 (long)s
->sock_fd
, s
->sock_family
,
3067 return PyString_FromString(buf
);
3071 /* Create a new, uninitialized socket object. */
3074 sock_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
3078 new = type
->tp_alloc(type
, 0);
3080 ((PySocketSockObject
*)new)->sock_fd
= -1;
3081 ((PySocketSockObject
*)new)->sock_timeout
= -1.0;
3082 ((PySocketSockObject
*)new)->errorhandler
= &set_error
;
3088 /* Initialize a new socket object. */
3092 sock_initobj(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
3094 PySocketSockObject
*s
= (PySocketSockObject
*)self
;
3096 int family
= AF_INET
, type
= SOCK_STREAM
, proto
= 0;
3097 static char *keywords
[] = {"family", "type", "proto", 0};
3099 if (!PyArg_ParseTupleAndKeywords(args
, kwds
,
3100 "|iii:socket", keywords
,
3101 &family
, &type
, &proto
))
3104 Py_BEGIN_ALLOW_THREADS
3105 fd
= socket(family
, type
, proto
);
3106 Py_END_ALLOW_THREADS
3109 if (fd
== INVALID_SOCKET
)
3117 init_sockobject(s
, fd
, family
, type
, proto
);
3124 /* Type object for socket objects. */
3126 static PyTypeObject sock_type
= {
3127 PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */
3128 "_socket.socket", /* tp_name */
3129 sizeof(PySocketSockObject
), /* tp_basicsize */
3130 0, /* tp_itemsize */
3131 (destructor
)sock_dealloc
, /* tp_dealloc */
3136 (reprfunc
)sock_repr
, /* tp_repr */
3137 0, /* tp_as_number */
3138 0, /* tp_as_sequence */
3139 0, /* tp_as_mapping */
3143 PyObject_GenericGetAttr
, /* tp_getattro */
3144 0, /* tp_setattro */
3145 0, /* tp_as_buffer */
3146 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
3147 sock_doc
, /* tp_doc */
3148 0, /* tp_traverse */
3150 0, /* tp_richcompare */
3151 0, /* tp_weaklistoffset */
3153 0, /* tp_iternext */
3154 sock_methods
, /* tp_methods */
3155 sock_memberlist
, /* tp_members */
3159 0, /* tp_descr_get */
3160 0, /* tp_descr_set */
3161 0, /* tp_dictoffset */
3162 sock_initobj
, /* tp_init */
3163 PyType_GenericAlloc
, /* tp_alloc */
3164 sock_new
, /* tp_new */
3165 PyObject_Del
, /* tp_free */
3169 /* Python interface to gethostname(). */
3173 socket_gethostname(PyObject
*self
, PyObject
*unused
)
3177 Py_BEGIN_ALLOW_THREADS
3178 res
= gethostname(buf
, (int) sizeof buf
- 1);
3179 Py_END_ALLOW_THREADS
3182 buf
[sizeof buf
- 1] = '\0';
3183 return PyString_FromString(buf
);
3186 PyDoc_STRVAR(gethostname_doc
,
3187 "gethostname() -> string\n\
3189 Return the current host name.");
3192 /* Python interface to gethostbyname(name). */
3196 socket_gethostbyname(PyObject
*self
, PyObject
*args
)
3199 sock_addr_t addrbuf
;
3201 if (!PyArg_ParseTuple(args
, "s:gethostbyname", &name
))
3203 if (setipaddr(name
, SAS2SA(&addrbuf
), sizeof(addrbuf
), AF_INET
) < 0)
3205 return makeipaddr(SAS2SA(&addrbuf
), sizeof(struct sockaddr_in
));
3208 PyDoc_STRVAR(gethostbyname_doc
,
3209 "gethostbyname(host) -> address\n\
3211 Return the IP address (a string of the form '255.255.255.255') for a host.");
3214 /* Convenience function common to gethostbyname_ex and gethostbyaddr */
3217 gethost_common(struct hostent
*h
, struct sockaddr
*addr
, int alen
, int af
)
3220 PyObject
*rtn_tuple
= (PyObject
*)NULL
;
3221 PyObject
*name_list
= (PyObject
*)NULL
;
3222 PyObject
*addr_list
= (PyObject
*)NULL
;
3226 /* Let's get real error message to return */
3228 set_herror(h_errno
);
3230 PyErr_SetString(socket_error
, "host not found");
3235 if (h
->h_addrtype
!= af
) {
3236 /* Let's get real error message to return */
3237 PyErr_SetString(socket_error
,
3238 (char *)strerror(EAFNOSUPPORT
));
3246 if (alen
< sizeof(struct sockaddr_in
))
3252 if (alen
< sizeof(struct sockaddr_in6
))
3259 if ((name_list
= PyList_New(0)) == NULL
)
3262 if ((addr_list
= PyList_New(0)) == NULL
)
3265 /* SF #1511317: h_aliases can be NULL */
3267 for (pch
= h
->h_aliases
; *pch
!= NULL
; pch
++) {
3269 tmp
= PyString_FromString(*pch
);
3273 status
= PyList_Append(name_list
, tmp
);
3281 for (pch
= h
->h_addr_list
; *pch
!= NULL
; pch
++) {
3288 struct sockaddr_in sin
;
3289 memset(&sin
, 0, sizeof(sin
));
3290 sin
.sin_family
= af
;
3291 #ifdef HAVE_SOCKADDR_SA_LEN
3292 sin
.sin_len
= sizeof(sin
);
3294 memcpy(&sin
.sin_addr
, *pch
, sizeof(sin
.sin_addr
));
3295 tmp
= makeipaddr((struct sockaddr
*)&sin
, sizeof(sin
));
3297 if (pch
== h
->h_addr_list
&& alen
>= sizeof(sin
))
3298 memcpy((char *) addr
, &sin
, sizeof(sin
));
3305 struct sockaddr_in6 sin6
;
3306 memset(&sin6
, 0, sizeof(sin6
));
3307 sin6
.sin6_family
= af
;
3308 #ifdef HAVE_SOCKADDR_SA_LEN
3309 sin6
.sin6_len
= sizeof(sin6
);
3311 memcpy(&sin6
.sin6_addr
, *pch
, sizeof(sin6
.sin6_addr
));
3312 tmp
= makeipaddr((struct sockaddr
*)&sin6
,
3315 if (pch
== h
->h_addr_list
&& alen
>= sizeof(sin6
))
3316 memcpy((char *) addr
, &sin6
, sizeof(sin6
));
3321 default: /* can't happen */
3322 PyErr_SetString(socket_error
,
3323 "unsupported address family");
3330 status
= PyList_Append(addr_list
, tmp
);
3337 rtn_tuple
= Py_BuildValue("sOO", h
->h_name
, name_list
, addr_list
);
3340 Py_XDECREF(name_list
);
3341 Py_XDECREF(addr_list
);
3346 /* Python interface to gethostbyname_ex(name). */
3350 socket_gethostbyname_ex(PyObject
*self
, PyObject
*args
)
3355 struct sockaddr_storage addr
;
3357 struct sockaddr_in addr
;
3359 struct sockaddr
*sa
;
3361 #ifdef HAVE_GETHOSTBYNAME_R
3362 struct hostent hp_allocated
;
3363 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
3364 struct hostent_data data
;
3367 int buf_len
= (sizeof buf
) - 1;
3370 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3373 #endif /* HAVE_GETHOSTBYNAME_R */
3375 if (!PyArg_ParseTuple(args
, "s:gethostbyname_ex", &name
))
3377 if (setipaddr(name
, (struct sockaddr
*)&addr
, sizeof(addr
), AF_INET
) < 0)
3379 Py_BEGIN_ALLOW_THREADS
3380 #ifdef HAVE_GETHOSTBYNAME_R
3381 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3382 result
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
,
3384 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
3385 h
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
, &errnop
);
3386 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
3387 memset((void *) &data
, '\0', sizeof(data
));
3388 result
= gethostbyname_r(name
, &hp_allocated
, &data
);
3389 h
= (result
!= 0) ? NULL
: &hp_allocated
;
3391 #else /* not HAVE_GETHOSTBYNAME_R */
3392 #ifdef USE_GETHOSTBYNAME_LOCK
3393 PyThread_acquire_lock(netdb_lock
, 1);
3395 h
= gethostbyname(name
);
3396 #endif /* HAVE_GETHOSTBYNAME_R */
3397 Py_END_ALLOW_THREADS
3398 /* Some C libraries would require addr.__ss_family instead of
3400 Therefore, we cast the sockaddr_storage into sockaddr to
3401 access sa_family. */
3402 sa
= (struct sockaddr
*)&addr
;
3403 ret
= gethost_common(h
, (struct sockaddr
*)&addr
, sizeof(addr
),
3405 #ifdef USE_GETHOSTBYNAME_LOCK
3406 PyThread_release_lock(netdb_lock
);
3411 PyDoc_STRVAR(ghbn_ex_doc
,
3412 "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
3414 Return the true host name, a list of aliases, and a list of IP addresses,\n\
3415 for a host. The host argument is a string giving a host name or IP number.");
3418 /* Python interface to gethostbyaddr(IP). */
3422 socket_gethostbyaddr(PyObject
*self
, PyObject
*args
)
3425 struct sockaddr_storage addr
;
3427 struct sockaddr_in addr
;
3429 struct sockaddr
*sa
= (struct sockaddr
*)&addr
;
3433 #ifdef HAVE_GETHOSTBYNAME_R
3434 struct hostent hp_allocated
;
3435 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
3436 struct hostent_data data
;
3438 /* glibcs up to 2.10 assume that the buf argument to
3439 gethostbyaddr_r is 8-byte aligned, which at least llvm-gcc
3440 does not ensure. The attribute below instructs the compiler
3441 to maintain this alignment. */
3442 char buf
[16384] Py_ALIGNED(8);
3443 int buf_len
= (sizeof buf
) - 1;
3446 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3449 #endif /* HAVE_GETHOSTBYNAME_R */
3454 if (!PyArg_ParseTuple(args
, "s:gethostbyaddr", &ip_num
))
3457 if (setipaddr(ip_num
, sa
, sizeof(addr
), af
) < 0)
3463 ap
= (char *)&((struct sockaddr_in
*)sa
)->sin_addr
;
3464 al
= sizeof(((struct sockaddr_in
*)sa
)->sin_addr
);
3468 ap
= (char *)&((struct sockaddr_in6
*)sa
)->sin6_addr
;
3469 al
= sizeof(((struct sockaddr_in6
*)sa
)->sin6_addr
);
3473 PyErr_SetString(socket_error
, "unsupported address family");
3476 Py_BEGIN_ALLOW_THREADS
3477 #ifdef HAVE_GETHOSTBYNAME_R
3478 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3479 result
= gethostbyaddr_r(ap
, al
, af
,
3480 &hp_allocated
, buf
, buf_len
,
3482 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
3483 h
= gethostbyaddr_r(ap
, al
, af
,
3484 &hp_allocated
, buf
, buf_len
, &errnop
);
3485 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
3486 memset((void *) &data
, '\0', sizeof(data
));
3487 result
= gethostbyaddr_r(ap
, al
, af
, &hp_allocated
, &data
);
3488 h
= (result
!= 0) ? NULL
: &hp_allocated
;
3490 #else /* not HAVE_GETHOSTBYNAME_R */
3491 #ifdef USE_GETHOSTBYNAME_LOCK
3492 PyThread_acquire_lock(netdb_lock
, 1);
3494 h
= gethostbyaddr(ap
, al
, af
);
3495 #endif /* HAVE_GETHOSTBYNAME_R */
3496 Py_END_ALLOW_THREADS
3497 ret
= gethost_common(h
, (struct sockaddr
*)&addr
, sizeof(addr
), af
);
3498 #ifdef USE_GETHOSTBYNAME_LOCK
3499 PyThread_release_lock(netdb_lock
);
3504 PyDoc_STRVAR(gethostbyaddr_doc
,
3505 "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
3507 Return the true host name, a list of aliases, and a list of IP addresses,\n\
3508 for a host. The host argument is a string giving a host name or IP number.");
3511 /* Python interface to getservbyname(name).
3512 This only returns the port number, since the other info is already
3513 known or not useful (like the list of aliases). */
3517 socket_getservbyname(PyObject
*self
, PyObject
*args
)
3519 char *name
, *proto
=NULL
;
3521 if (!PyArg_ParseTuple(args
, "s|s:getservbyname", &name
, &proto
))
3523 Py_BEGIN_ALLOW_THREADS
3524 sp
= getservbyname(name
, proto
);
3525 Py_END_ALLOW_THREADS
3527 PyErr_SetString(socket_error
, "service/proto not found");
3530 return PyInt_FromLong((long) ntohs(sp
->s_port
));
3533 PyDoc_STRVAR(getservbyname_doc
,
3534 "getservbyname(servicename[, protocolname]) -> integer\n\
3536 Return a port number from a service name and protocol name.\n\
3537 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3538 otherwise any protocol will match.");
3541 /* Python interface to getservbyport(port).
3542 This only returns the service name, since the other info is already
3543 known or not useful (like the list of aliases). */
3547 socket_getservbyport(PyObject
*self
, PyObject
*args
)
3552 if (!PyArg_ParseTuple(args
, "i|s:getservbyport", &port
, &proto
))
3554 if (port
< 0 || port
> 0xffff) {
3556 PyExc_OverflowError
,
3557 "getservbyport: port must be 0-65535.");
3560 Py_BEGIN_ALLOW_THREADS
3561 sp
= getservbyport(htons((short)port
), proto
);
3562 Py_END_ALLOW_THREADS
3564 PyErr_SetString(socket_error
, "port/proto not found");
3567 return PyString_FromString(sp
->s_name
);
3570 PyDoc_STRVAR(getservbyport_doc
,
3571 "getservbyport(port[, protocolname]) -> string\n\
3573 Return the service name from a port number and protocol name.\n\
3574 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3575 otherwise any protocol will match.");
3577 /* Python interface to getprotobyname(name).
3578 This only returns the protocol number, since the other info is
3579 already known or not useful (like the list of aliases). */
3583 socket_getprotobyname(PyObject
*self
, PyObject
*args
)
3586 struct protoent
*sp
;
3588 /* Not available in BeOS yet. - [cjh] */
3589 PyErr_SetString(socket_error
, "getprotobyname not supported");
3592 if (!PyArg_ParseTuple(args
, "s:getprotobyname", &name
))
3594 Py_BEGIN_ALLOW_THREADS
3595 sp
= getprotobyname(name
);
3596 Py_END_ALLOW_THREADS
3598 PyErr_SetString(socket_error
, "protocol not found");
3601 return PyInt_FromLong((long) sp
->p_proto
);
3605 PyDoc_STRVAR(getprotobyname_doc
,
3606 "getprotobyname(name) -> integer\n\
3608 Return the protocol number for the named protocol. (Rarely used.)");
3611 #ifdef HAVE_SOCKETPAIR
3612 /* Create a pair of sockets using the socketpair() function.
3613 Arguments as for socket() except the default family is AF_UNIX if
3614 defined on the platform; otherwise, the default is AF_INET. */
3618 socket_socketpair(PyObject
*self
, PyObject
*args
)
3620 PySocketSockObject
*s0
= NULL
, *s1
= NULL
;
3622 int family
, type
= SOCK_STREAM
, proto
= 0;
3623 PyObject
*res
= NULL
;
3625 #if defined(AF_UNIX)
3630 if (!PyArg_ParseTuple(args
, "|iii:socketpair",
3631 &family
, &type
, &proto
))
3633 /* Create a pair of socket fds */
3634 if (socketpair(family
, type
, proto
, sv
) < 0)
3636 s0
= new_sockobject(sv
[0], family
, type
, proto
);
3639 s1
= new_sockobject(sv
[1], family
, type
, proto
);
3642 res
= PyTuple_Pack(2, s0
, s1
);
3656 PyDoc_STRVAR(socketpair_doc
,
3657 "socketpair([family[, type[, proto]]]) -> (socket object, socket object)\n\
3659 Create a pair of socket objects from the sockets returned by the platform\n\
3660 socketpair() function.\n\
3661 The arguments are the same as for socket() except the default family is\n\
3662 AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");
3664 #endif /* HAVE_SOCKETPAIR */
3668 /* Create a socket object from a numeric file description.
3669 Useful e.g. if stdin is a socket.
3670 Additional arguments as for socket(). */
3674 socket_fromfd(PyObject
*self
, PyObject
*args
)
3676 PySocketSockObject
*s
;
3678 int family
, type
, proto
= 0;
3679 if (!PyArg_ParseTuple(args
, "iii|i:fromfd",
3680 &fd
, &family
, &type
, &proto
))
3682 /* Dup the fd so it and the socket can be closed independently */
3686 s
= new_sockobject(fd
, family
, type
, proto
);
3687 return (PyObject
*) s
;
3690 PyDoc_STRVAR(fromfd_doc
,
3691 "fromfd(fd, family, type[, proto]) -> socket object\n\
3693 Create a socket object from a duplicate of the given\n\
3695 The remaining arguments are the same as for socket().");
3701 socket_ntohs(PyObject
*self
, PyObject
*args
)
3705 if (!PyArg_ParseTuple(args
, "i:ntohs", &x1
)) {
3709 PyErr_SetString(PyExc_OverflowError
,
3710 "can't convert negative number to unsigned long");
3713 x2
= (unsigned int)ntohs((unsigned short)x1
);
3714 return PyInt_FromLong(x2
);
3717 PyDoc_STRVAR(ntohs_doc
,
3718 "ntohs(integer) -> integer\n\
3720 Convert a 16-bit integer from network to host byte order.");
3724 socket_ntohl(PyObject
*self
, PyObject
*arg
)
3728 if (PyInt_Check(arg
)) {
3729 x
= PyInt_AS_LONG(arg
);
3730 if (x
== (unsigned long) -1 && PyErr_Occurred())
3733 PyErr_SetString(PyExc_OverflowError
,
3734 "can't convert negative number to unsigned long");
3738 else if (PyLong_Check(arg
)) {
3739 x
= PyLong_AsUnsignedLong(arg
);
3740 if (x
== (unsigned long) -1 && PyErr_Occurred())
3745 /* only want the trailing 32 bits */
3746 y
= x
& 0xFFFFFFFFUL
;
3748 return PyErr_Format(PyExc_OverflowError
,
3749 "long int larger than 32 bits");
3755 return PyErr_Format(PyExc_TypeError
,
3756 "expected int/long, %s found",
3757 Py_TYPE(arg
)->tp_name
);
3758 if (x
== (unsigned long) -1 && PyErr_Occurred())
3760 return PyLong_FromUnsignedLong(ntohl(x
));
3763 PyDoc_STRVAR(ntohl_doc
,
3764 "ntohl(integer) -> integer\n\
3766 Convert a 32-bit integer from network to host byte order.");
3770 socket_htons(PyObject
*self
, PyObject
*args
)
3774 if (!PyArg_ParseTuple(args
, "i:htons", &x1
)) {
3778 PyErr_SetString(PyExc_OverflowError
,
3779 "can't convert negative number to unsigned long");
3782 x2
= (unsigned int)htons((unsigned short)x1
);
3783 return PyInt_FromLong(x2
);
3786 PyDoc_STRVAR(htons_doc
,
3787 "htons(integer) -> integer\n\
3789 Convert a 16-bit integer from host to network byte order.");
3793 socket_htonl(PyObject
*self
, PyObject
*arg
)
3797 if (PyInt_Check(arg
)) {
3798 x
= PyInt_AS_LONG(arg
);
3799 if (x
== (unsigned long) -1 && PyErr_Occurred())
3802 PyErr_SetString(PyExc_OverflowError
,
3803 "can't convert negative number to unsigned long");
3807 else if (PyLong_Check(arg
)) {
3808 x
= PyLong_AsUnsignedLong(arg
);
3809 if (x
== (unsigned long) -1 && PyErr_Occurred())
3814 /* only want the trailing 32 bits */
3815 y
= x
& 0xFFFFFFFFUL
;
3817 return PyErr_Format(PyExc_OverflowError
,
3818 "long int larger than 32 bits");
3824 return PyErr_Format(PyExc_TypeError
,
3825 "expected int/long, %s found",
3826 Py_TYPE(arg
)->tp_name
);
3827 return PyLong_FromUnsignedLong(htonl((unsigned long)x
));
3830 PyDoc_STRVAR(htonl_doc
,
3831 "htonl(integer) -> integer\n\
3833 Convert a 32-bit integer from host to network byte order.");
3835 /* socket.inet_aton() and socket.inet_ntoa() functions. */
3837 PyDoc_STRVAR(inet_aton_doc
,
3838 "inet_aton(string) -> packed 32-bit IP representation\n\
3840 Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
3841 binary format used in low-level network functions.");
3844 socket_inet_aton(PyObject
*self
, PyObject
*args
)
3847 #define INADDR_NONE (-1)
3849 #ifdef HAVE_INET_ATON
3853 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
3854 #if (SIZEOF_INT != 4)
3855 #error "Not sure if in_addr_t exists and int is not 32-bits."
3857 /* Have to use inet_addr() instead */
3858 unsigned int packed_addr
;
3862 if (!PyArg_ParseTuple(args
, "s:inet_aton", &ip_addr
))
3866 #ifdef HAVE_INET_ATON
3868 #ifdef USE_INET_ATON_WEAKLINK
3869 if (inet_aton
!= NULL
) {
3871 if (inet_aton(ip_addr
, &buf
))
3872 return PyString_FromStringAndSize((char *)(&buf
),
3875 PyErr_SetString(socket_error
,
3876 "illegal IP address string passed to inet_aton");
3879 #ifdef USE_INET_ATON_WEAKLINK
3885 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
3887 /* special-case this address as inet_addr might return INADDR_NONE
3889 if (strcmp(ip_addr
, "255.255.255.255") == 0) {
3890 packed_addr
= 0xFFFFFFFF;
3893 packed_addr
= inet_addr(ip_addr
);
3895 if (packed_addr
== INADDR_NONE
) { /* invalid address */
3896 PyErr_SetString(socket_error
,
3897 "illegal IP address string passed to inet_aton");
3901 return PyString_FromStringAndSize((char *) &packed_addr
,
3902 sizeof(packed_addr
));
3904 #ifdef USE_INET_ATON_WEAKLINK
3911 PyDoc_STRVAR(inet_ntoa_doc
,
3912 "inet_ntoa(packed_ip) -> ip_address_string\n\
3914 Convert an IP address from 32-bit packed binary format to string format");
3917 socket_inet_ntoa(PyObject
*self
, PyObject
*args
)
3921 struct in_addr packed_addr
;
3923 if (!PyArg_ParseTuple(args
, "s#:inet_ntoa", &packed_str
, &addr_len
)) {
3927 if (addr_len
!= sizeof(packed_addr
)) {
3928 PyErr_SetString(socket_error
,
3929 "packed IP wrong length for inet_ntoa");
3933 memcpy(&packed_addr
, packed_str
, addr_len
);
3935 return PyString_FromString(inet_ntoa(packed_addr
));
3938 #ifdef HAVE_INET_PTON
3940 PyDoc_STRVAR(inet_pton_doc
,
3941 "inet_pton(af, ip) -> packed IP address string\n\
3943 Convert an IP address from string format to a packed string suitable\n\
3944 for use with low-level network functions.");
3947 socket_inet_pton(PyObject
*self
, PyObject
*args
)
3953 char packed
[MAX(sizeof(struct in_addr
), sizeof(struct in6_addr
))];
3955 char packed
[sizeof(struct in_addr
)];
3957 if (!PyArg_ParseTuple(args
, "is:inet_pton", &af
, &ip
)) {
3961 #if !defined(ENABLE_IPV6) && defined(AF_INET6)
3962 if(af
== AF_INET6
) {
3963 PyErr_SetString(socket_error
,
3964 "can't use AF_INET6, IPv6 is disabled");
3969 retval
= inet_pton(af
, ip
, packed
);
3971 PyErr_SetFromErrno(socket_error
);
3973 } else if (retval
== 0) {
3974 PyErr_SetString(socket_error
,
3975 "illegal IP address string passed to inet_pton");
3977 } else if (af
== AF_INET
) {
3978 return PyString_FromStringAndSize(packed
,
3979 sizeof(struct in_addr
));
3981 } else if (af
== AF_INET6
) {
3982 return PyString_FromStringAndSize(packed
,
3983 sizeof(struct in6_addr
));
3986 PyErr_SetString(socket_error
, "unknown address family");
3991 PyDoc_STRVAR(inet_ntop_doc
,
3992 "inet_ntop(af, packed_ip) -> string formatted IP address\n\
3994 Convert a packed IP address of the given family to string format.");
3997 socket_inet_ntop(PyObject
*self
, PyObject
*args
)
4004 char ip
[MAX(INET_ADDRSTRLEN
, INET6_ADDRSTRLEN
) + 1];
4006 char ip
[INET_ADDRSTRLEN
+ 1];
4009 /* Guarantee NUL-termination for PyString_FromString() below */
4010 memset((void *) &ip
[0], '\0', sizeof(ip
));
4012 if (!PyArg_ParseTuple(args
, "is#:inet_ntop", &af
, &packed
, &len
)) {
4016 if (af
== AF_INET
) {
4017 if (len
!= sizeof(struct in_addr
)) {
4018 PyErr_SetString(PyExc_ValueError
,
4019 "invalid length of packed IP address string");
4023 } else if (af
== AF_INET6
) {
4024 if (len
!= sizeof(struct in6_addr
)) {
4025 PyErr_SetString(PyExc_ValueError
,
4026 "invalid length of packed IP address string");
4031 PyErr_Format(PyExc_ValueError
,
4032 "unknown address family %d", af
);
4036 retval
= inet_ntop(af
, packed
, ip
, sizeof(ip
));
4038 PyErr_SetFromErrno(socket_error
);
4041 return PyString_FromString(retval
);
4045 PyErr_SetString(PyExc_RuntimeError
, "invalid handling of inet_ntop");
4049 #endif /* HAVE_INET_PTON */
4051 /* Python interface to getaddrinfo(host, port). */
4055 socket_getaddrinfo(PyObject
*self
, PyObject
*args
)
4057 struct addrinfo hints
, *res
;
4058 struct addrinfo
*res0
= NULL
;
4059 PyObject
*hobj
= NULL
;
4060 PyObject
*pobj
= (PyObject
*)NULL
;
4063 int family
, socktype
, protocol
, flags
;
4065 PyObject
*all
= (PyObject
*)NULL
;
4066 PyObject
*single
= (PyObject
*)NULL
;
4067 PyObject
*idna
= NULL
;
4069 family
= socktype
= protocol
= flags
= 0;
4071 if (!PyArg_ParseTuple(args
, "OO|iiii:getaddrinfo",
4072 &hobj
, &pobj
, &family
, &socktype
,
4073 &protocol
, &flags
)) {
4076 if (hobj
== Py_None
) {
4078 } else if (PyUnicode_Check(hobj
)) {
4079 idna
= PyObject_CallMethod(hobj
, "encode", "s", "idna");
4082 hptr
= PyString_AsString(idna
);
4083 } else if (PyString_Check(hobj
)) {
4084 hptr
= PyString_AsString(hobj
);
4086 PyErr_SetString(PyExc_TypeError
,
4087 "getaddrinfo() argument 1 must be string or None");
4090 if (PyInt_Check(pobj
)) {
4091 PyOS_snprintf(pbuf
, sizeof(pbuf
), "%ld", PyInt_AsLong(pobj
));
4093 } else if (PyString_Check(pobj
)) {
4094 pptr
= PyString_AsString(pobj
);
4095 } else if (pobj
== Py_None
) {
4096 pptr
= (char *)NULL
;
4098 PyErr_SetString(socket_error
, "Int or String expected");
4101 memset(&hints
, 0, sizeof(hints
));
4102 hints
.ai_family
= family
;
4103 hints
.ai_socktype
= socktype
;
4104 hints
.ai_protocol
= protocol
;
4105 hints
.ai_flags
= flags
;
4106 Py_BEGIN_ALLOW_THREADS
4107 ACQUIRE_GETADDRINFO_LOCK
4108 error
= getaddrinfo(hptr
, pptr
, &hints
, &res0
);
4109 Py_END_ALLOW_THREADS
4110 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
4112 set_gaierror(error
);
4116 if ((all
= PyList_New(0)) == NULL
)
4118 for (res
= res0
; res
; res
= res
->ai_next
) {
4120 makesockaddr(-1, res
->ai_addr
, res
->ai_addrlen
, protocol
);
4123 single
= Py_BuildValue("iiisO", res
->ai_family
,
4124 res
->ai_socktype
, res
->ai_protocol
,
4125 res
->ai_canonname
? res
->ai_canonname
: "",
4131 if (PyList_Append(all
, single
))
4145 return (PyObject
*)NULL
;
4148 PyDoc_STRVAR(getaddrinfo_doc
,
4149 "getaddrinfo(host, port [, family, socktype, proto, flags])\n\
4150 -> list of (family, socktype, proto, canonname, sockaddr)\n\
4152 Resolve host and port into addrinfo struct.");
4154 /* Python interface to getnameinfo(sa, flags). */
4158 socket_getnameinfo(PyObject
*self
, PyObject
*args
)
4160 PyObject
*sa
= (PyObject
*)NULL
;
4163 int port
, flowinfo
, scope_id
;
4164 char hbuf
[NI_MAXHOST
], pbuf
[NI_MAXSERV
];
4165 struct addrinfo hints
, *res
= NULL
;
4167 PyObject
*ret
= (PyObject
*)NULL
;
4169 flags
= flowinfo
= scope_id
= 0;
4170 if (!PyArg_ParseTuple(args
, "Oi:getnameinfo", &sa
, &flags
))
4172 if (!PyTuple_Check(sa
)) {
4173 PyErr_SetString(PyExc_TypeError
,
4174 "getnameinfo() argument 1 must be a tuple");
4177 if (!PyArg_ParseTuple(sa
, "si|ii",
4178 &hostp
, &port
, &flowinfo
, &scope_id
))
4180 PyOS_snprintf(pbuf
, sizeof(pbuf
), "%d", port
);
4181 memset(&hints
, 0, sizeof(hints
));
4182 hints
.ai_family
= AF_UNSPEC
;
4183 hints
.ai_socktype
= SOCK_DGRAM
; /* make numeric port happy */
4184 Py_BEGIN_ALLOW_THREADS
4185 ACQUIRE_GETADDRINFO_LOCK
4186 error
= getaddrinfo(hostp
, pbuf
, &hints
, &res
);
4187 Py_END_ALLOW_THREADS
4188 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
4190 set_gaierror(error
);
4194 PyErr_SetString(socket_error
,
4195 "sockaddr resolved to multiple addresses");
4198 switch (res
->ai_family
) {
4201 if (PyTuple_GET_SIZE(sa
) != 2) {
4202 PyErr_SetString(socket_error
,
4203 "IPv4 sockaddr must be 2 tuple");
4211 struct sockaddr_in6
*sin6
;
4212 sin6
= (struct sockaddr_in6
*)res
->ai_addr
;
4213 sin6
->sin6_flowinfo
= flowinfo
;
4214 sin6
->sin6_scope_id
= scope_id
;
4219 error
= getnameinfo(res
->ai_addr
, res
->ai_addrlen
,
4220 hbuf
, sizeof(hbuf
), pbuf
, sizeof(pbuf
), flags
);
4222 set_gaierror(error
);
4225 ret
= Py_BuildValue("ss", hbuf
, pbuf
);
4233 PyDoc_STRVAR(getnameinfo_doc
,
4234 "getnameinfo(sockaddr, flags) --> (host, port)\n\
4236 Get host and port for a sockaddr.");
4239 /* Python API to getting and setting the default timeout value. */
4242 socket_getdefaulttimeout(PyObject
*self
)
4244 if (defaulttimeout
< 0.0) {
4249 return PyFloat_FromDouble(defaulttimeout
);
4252 PyDoc_STRVAR(getdefaulttimeout_doc
,
4253 "getdefaulttimeout() -> timeout\n\
4255 Returns the default timeout in floating seconds for new socket objects.\n\
4256 A value of None indicates that new socket objects have no timeout.\n\
4257 When the socket module is first imported, the default is None.");
4260 socket_setdefaulttimeout(PyObject
*self
, PyObject
*arg
)
4267 timeout
= PyFloat_AsDouble(arg
);
4268 if (timeout
< 0.0) {
4269 if (!PyErr_Occurred())
4270 PyErr_SetString(PyExc_ValueError
,
4271 "Timeout value out of range");
4276 defaulttimeout
= timeout
;
4282 PyDoc_STRVAR(setdefaulttimeout_doc
,
4283 "setdefaulttimeout(timeout)\n\
4285 Set the default timeout in floating seconds for new socket objects.\n\
4286 A value of None indicates that new socket objects have no timeout.\n\
4287 When the socket module is first imported, the default is None.");
4290 /* List of functions exported by this module. */
4292 static PyMethodDef socket_methods
[] = {
4293 {"gethostbyname", socket_gethostbyname
,
4294 METH_VARARGS
, gethostbyname_doc
},
4295 {"gethostbyname_ex", socket_gethostbyname_ex
,
4296 METH_VARARGS
, ghbn_ex_doc
},
4297 {"gethostbyaddr", socket_gethostbyaddr
,
4298 METH_VARARGS
, gethostbyaddr_doc
},
4299 {"gethostname", socket_gethostname
,
4300 METH_NOARGS
, gethostname_doc
},
4301 {"getservbyname", socket_getservbyname
,
4302 METH_VARARGS
, getservbyname_doc
},
4303 {"getservbyport", socket_getservbyport
,
4304 METH_VARARGS
, getservbyport_doc
},
4305 {"getprotobyname", socket_getprotobyname
,
4306 METH_VARARGS
, getprotobyname_doc
},
4308 {"fromfd", socket_fromfd
,
4309 METH_VARARGS
, fromfd_doc
},
4311 #ifdef HAVE_SOCKETPAIR
4312 {"socketpair", socket_socketpair
,
4313 METH_VARARGS
, socketpair_doc
},
4315 {"ntohs", socket_ntohs
,
4316 METH_VARARGS
, ntohs_doc
},
4317 {"ntohl", socket_ntohl
,
4319 {"htons", socket_htons
,
4320 METH_VARARGS
, htons_doc
},
4321 {"htonl", socket_htonl
,
4323 {"inet_aton", socket_inet_aton
,
4324 METH_VARARGS
, inet_aton_doc
},
4325 {"inet_ntoa", socket_inet_ntoa
,
4326 METH_VARARGS
, inet_ntoa_doc
},
4327 #ifdef HAVE_INET_PTON
4328 {"inet_pton", socket_inet_pton
,
4329 METH_VARARGS
, inet_pton_doc
},
4330 {"inet_ntop", socket_inet_ntop
,
4331 METH_VARARGS
, inet_ntop_doc
},
4333 {"getaddrinfo", socket_getaddrinfo
,
4334 METH_VARARGS
, getaddrinfo_doc
},
4335 {"getnameinfo", socket_getnameinfo
,
4336 METH_VARARGS
, getnameinfo_doc
},
4337 {"getdefaulttimeout", (PyCFunction
)socket_getdefaulttimeout
,
4338 METH_NOARGS
, getdefaulttimeout_doc
},
4339 {"setdefaulttimeout", socket_setdefaulttimeout
,
4340 METH_O
, setdefaulttimeout_doc
},
4341 {NULL
, NULL
} /* Sentinel */
4346 #define OS_INIT_DEFINED
4354 _kernel_swi(0x43380, &r
, &r
);
4355 taskwindow
= r
.r
[0];
4364 #define OS_INIT_DEFINED
4366 /* Additional initialization and cleanup for Windows */
4380 ret
= WSAStartup(0x0101, &WSAData
);
4382 case 0: /* No error */
4383 Py_AtExit(os_cleanup
);
4384 return 1; /* Success */
4385 case WSASYSNOTREADY
:
4386 PyErr_SetString(PyExc_ImportError
,
4387 "WSAStartup failed: network not ready");
4389 case WSAVERNOTSUPPORTED
:
4393 "WSAStartup failed: requested version not supported");
4396 PyOS_snprintf(buf
, sizeof(buf
),
4397 "WSAStartup failed: error code %d", ret
);
4398 PyErr_SetString(PyExc_ImportError
, buf
);
4401 return 0; /* Failure */
4404 #endif /* MS_WINDOWS */
4408 #define OS_INIT_DEFINED
4410 /* Additional initialization for OS/2 */
4417 int rc
= sock_init();
4420 return 1; /* Success */
4423 PyOS_snprintf(reason
, sizeof(reason
),
4424 "OS/2 TCP/IP Error# %d", sock_errno());
4425 PyErr_SetString(PyExc_ImportError
, reason
);
4427 return 0; /* Failure */
4429 /* No need to initialize sockets with GCC/EMX */
4430 return 1; /* Success */
4434 #endif /* PYOS_OS2 */
4437 #ifndef OS_INIT_DEFINED
4441 return 1; /* Success */
4446 /* C API table - always add new things to the end for binary
4449 PySocketModule_APIObject PySocketModuleAPI
=
4456 /* Initialize the _socket module.
4458 This module is actually called "_socket", and there's a wrapper
4459 "socket.py" which implements some additional functionality. On some
4460 platforms (e.g. Windows and OS/2), socket.py also implements a
4461 wrapper for the socket type that provides missing functionality such
4462 as makefile(), dup() and fromfd(). The import of "_socket" may fail
4463 with an ImportError exception if os-specific initialization fails.
4464 On Windows, this does WINSOCK initialization. When WINSOCK is
4465 initialized successfully, a call to WSACleanup() is scheduled to be
4469 PyDoc_STRVAR(socket_doc
,
4470 "Implementation module for socket operations.\n\
4472 See the socket module for documentation.");
4477 PyObject
*m
, *has_ipv6
;
4482 Py_TYPE(&sock_type
) = &PyType_Type
;
4483 m
= Py_InitModule3(PySocket_MODULE_NAME
,
4489 socket_error
= PyErr_NewException("socket.error",
4490 PyExc_IOError
, NULL
);
4491 if (socket_error
== NULL
)
4493 PySocketModuleAPI
.error
= socket_error
;
4494 Py_INCREF(socket_error
);
4495 PyModule_AddObject(m
, "error", socket_error
);
4496 socket_herror
= PyErr_NewException("socket.herror",
4497 socket_error
, NULL
);
4498 if (socket_herror
== NULL
)
4500 Py_INCREF(socket_herror
);
4501 PyModule_AddObject(m
, "herror", socket_herror
);
4502 socket_gaierror
= PyErr_NewException("socket.gaierror", socket_error
,
4504 if (socket_gaierror
== NULL
)
4506 Py_INCREF(socket_gaierror
);
4507 PyModule_AddObject(m
, "gaierror", socket_gaierror
);
4508 socket_timeout
= PyErr_NewException("socket.timeout",
4509 socket_error
, NULL
);
4510 if (socket_timeout
== NULL
)
4512 Py_INCREF(socket_timeout
);
4513 PyModule_AddObject(m
, "timeout", socket_timeout
);
4514 Py_INCREF((PyObject
*)&sock_type
);
4515 if (PyModule_AddObject(m
, "SocketType",
4516 (PyObject
*)&sock_type
) != 0)
4518 Py_INCREF((PyObject
*)&sock_type
);
4519 if (PyModule_AddObject(m
, "socket",
4520 (PyObject
*)&sock_type
) != 0)
4526 has_ipv6
= Py_False
;
4528 Py_INCREF(has_ipv6
);
4529 PyModule_AddObject(m
, "has_ipv6", has_ipv6
);
4532 if (PyModule_AddObject(m
, PySocket_CAPI_NAME
,
4533 PyCapsule_New(&PySocketModuleAPI
, PySocket_CAPSULE_NAME
, NULL
)
4537 /* Address families (we only support AF_INET and AF_UNIX) */
4539 PyModule_AddIntConstant(m
, "AF_UNSPEC", AF_UNSPEC
);
4541 PyModule_AddIntConstant(m
, "AF_INET", AF_INET
);
4543 PyModule_AddIntConstant(m
, "AF_INET6", AF_INET6
);
4544 #endif /* AF_INET6 */
4545 #if defined(AF_UNIX)
4546 PyModule_AddIntConstant(m
, "AF_UNIX", AF_UNIX
);
4547 #endif /* AF_UNIX */
4549 /* Amateur Radio AX.25 */
4550 PyModule_AddIntConstant(m
, "AF_AX25", AF_AX25
);
4553 PyModule_AddIntConstant(m
, "AF_IPX", AF_IPX
); /* Novell IPX */
4557 PyModule_AddIntConstant(m
, "AF_APPLETALK", AF_APPLETALK
);
4560 /* Amateur radio NetROM */
4561 PyModule_AddIntConstant(m
, "AF_NETROM", AF_NETROM
);
4564 /* Multiprotocol bridge */
4565 PyModule_AddIntConstant(m
, "AF_BRIDGE", AF_BRIDGE
);
4569 PyModule_AddIntConstant(m
, "AF_ATMPVC", AF_ATMPVC
);
4572 /* Reserved for Werner's ATM */
4573 PyModule_AddIntConstant(m
, "AF_AAL5", AF_AAL5
);
4576 /* Reserved for X.25 project */
4577 PyModule_AddIntConstant(m
, "AF_X25", AF_X25
);
4580 PyModule_AddIntConstant(m
, "AF_INET6", AF_INET6
); /* IP version 6 */
4583 /* Amateur Radio X.25 PLP */
4584 PyModule_AddIntConstant(m
, "AF_ROSE", AF_ROSE
);
4587 /* Reserved for DECnet project */
4588 PyModule_AddIntConstant(m
, "AF_DECnet", AF_DECnet
);
4591 /* Reserved for 802.2LLC project */
4592 PyModule_AddIntConstant(m
, "AF_NETBEUI", AF_NETBEUI
);
4595 /* Security callback pseudo AF */
4596 PyModule_AddIntConstant(m
, "AF_SECURITY", AF_SECURITY
);
4599 /* PF_KEY key management API */
4600 PyModule_AddIntConstant(m
, "AF_KEY", AF_KEY
);
4604 PyModule_AddIntConstant(m
, "AF_NETLINK", AF_NETLINK
);
4605 PyModule_AddIntConstant(m
, "NETLINK_ROUTE", NETLINK_ROUTE
);
4607 PyModule_AddIntConstant(m
, "NETLINK_SKIP", NETLINK_SKIP
);
4610 PyModule_AddIntConstant(m
, "NETLINK_W1", NETLINK_W1
);
4612 PyModule_AddIntConstant(m
, "NETLINK_USERSOCK", NETLINK_USERSOCK
);
4613 PyModule_AddIntConstant(m
, "NETLINK_FIREWALL", NETLINK_FIREWALL
);
4614 #ifdef NETLINK_TCPDIAG
4615 PyModule_AddIntConstant(m
, "NETLINK_TCPDIAG", NETLINK_TCPDIAG
);
4617 #ifdef NETLINK_NFLOG
4618 PyModule_AddIntConstant(m
, "NETLINK_NFLOG", NETLINK_NFLOG
);
4621 PyModule_AddIntConstant(m
, "NETLINK_XFRM", NETLINK_XFRM
);
4624 PyModule_AddIntConstant(m
, "NETLINK_ARPD", NETLINK_ARPD
);
4626 #ifdef NETLINK_ROUTE6
4627 PyModule_AddIntConstant(m
, "NETLINK_ROUTE6", NETLINK_ROUTE6
);
4629 PyModule_AddIntConstant(m
, "NETLINK_IP6_FW", NETLINK_IP6_FW
);
4630 #ifdef NETLINK_DNRTMSG
4631 PyModule_AddIntConstant(m
, "NETLINK_DNRTMSG", NETLINK_DNRTMSG
);
4633 #ifdef NETLINK_TAPBASE
4634 PyModule_AddIntConstant(m
, "NETLINK_TAPBASE", NETLINK_TAPBASE
);
4636 #endif /* AF_NETLINK */
4638 /* Alias to emulate 4.4BSD */
4639 PyModule_AddIntConstant(m
, "AF_ROUTE", AF_ROUTE
);
4643 PyModule_AddIntConstant(m
, "AF_ASH", AF_ASH
);
4647 PyModule_AddIntConstant(m
, "AF_ECONET", AF_ECONET
);
4651 PyModule_AddIntConstant(m
, "AF_ATMSVC", AF_ATMSVC
);
4654 /* Linux SNA Project (nutters!) */
4655 PyModule_AddIntConstant(m
, "AF_SNA", AF_SNA
);
4659 PyModule_AddIntConstant(m
, "AF_IRDA", AF_IRDA
);
4663 PyModule_AddIntConstant(m
, "AF_PPPOX", AF_PPPOX
);
4666 /* Wanpipe API Sockets */
4667 PyModule_AddIntConstant(m
, "AF_WANPIPE", AF_WANPIPE
);
4671 PyModule_AddIntConstant(m
, "AF_LLC", AF_LLC
);
4674 #ifdef USE_BLUETOOTH
4675 PyModule_AddIntConstant(m
, "AF_BLUETOOTH", AF_BLUETOOTH
);
4676 PyModule_AddIntConstant(m
, "BTPROTO_L2CAP", BTPROTO_L2CAP
);
4677 PyModule_AddIntConstant(m
, "BTPROTO_HCI", BTPROTO_HCI
);
4678 PyModule_AddIntConstant(m
, "SOL_HCI", SOL_HCI
);
4679 #if !defined(__NetBSD__) && !defined(__DragonFly__)
4680 PyModule_AddIntConstant(m
, "HCI_FILTER", HCI_FILTER
);
4682 #if !defined(__FreeBSD__)
4683 #if !defined(__NetBSD__) && !defined(__DragonFly__)
4684 PyModule_AddIntConstant(m
, "HCI_TIME_STAMP", HCI_TIME_STAMP
);
4686 PyModule_AddIntConstant(m
, "HCI_DATA_DIR", HCI_DATA_DIR
);
4687 PyModule_AddIntConstant(m
, "BTPROTO_SCO", BTPROTO_SCO
);
4689 PyModule_AddIntConstant(m
, "BTPROTO_RFCOMM", BTPROTO_RFCOMM
);
4690 PyModule_AddStringConstant(m
, "BDADDR_ANY", "00:00:00:00:00:00");
4691 PyModule_AddStringConstant(m
, "BDADDR_LOCAL", "00:00:00:FF:FF:FF");
4695 PyModule_AddIntMacro(m
, AF_PACKET
);
4698 PyModule_AddIntMacro(m
, PF_PACKET
);
4701 PyModule_AddIntMacro(m
, PACKET_HOST
);
4703 #ifdef PACKET_BROADCAST
4704 PyModule_AddIntMacro(m
, PACKET_BROADCAST
);
4706 #ifdef PACKET_MULTICAST
4707 PyModule_AddIntMacro(m
, PACKET_MULTICAST
);
4709 #ifdef PACKET_OTHERHOST
4710 PyModule_AddIntMacro(m
, PACKET_OTHERHOST
);
4712 #ifdef PACKET_OUTGOING
4713 PyModule_AddIntMacro(m
, PACKET_OUTGOING
);
4715 #ifdef PACKET_LOOPBACK
4716 PyModule_AddIntMacro(m
, PACKET_LOOPBACK
);
4718 #ifdef PACKET_FASTROUTE
4719 PyModule_AddIntMacro(m
, PACKET_FASTROUTE
);
4722 #ifdef HAVE_LINUX_TIPC_H
4723 PyModule_AddIntConstant(m
, "AF_TIPC", AF_TIPC
);
4726 PyModule_AddIntConstant(m
, "TIPC_ADDR_NAMESEQ", TIPC_ADDR_NAMESEQ
);
4727 PyModule_AddIntConstant(m
, "TIPC_ADDR_NAME", TIPC_ADDR_NAME
);
4728 PyModule_AddIntConstant(m
, "TIPC_ADDR_ID", TIPC_ADDR_ID
);
4730 PyModule_AddIntConstant(m
, "TIPC_ZONE_SCOPE", TIPC_ZONE_SCOPE
);
4731 PyModule_AddIntConstant(m
, "TIPC_CLUSTER_SCOPE", TIPC_CLUSTER_SCOPE
);
4732 PyModule_AddIntConstant(m
, "TIPC_NODE_SCOPE", TIPC_NODE_SCOPE
);
4734 /* for setsockopt() */
4735 PyModule_AddIntConstant(m
, "SOL_TIPC", SOL_TIPC
);
4736 PyModule_AddIntConstant(m
, "TIPC_IMPORTANCE", TIPC_IMPORTANCE
);
4737 PyModule_AddIntConstant(m
, "TIPC_SRC_DROPPABLE", TIPC_SRC_DROPPABLE
);
4738 PyModule_AddIntConstant(m
, "TIPC_DEST_DROPPABLE",
4739 TIPC_DEST_DROPPABLE
);
4740 PyModule_AddIntConstant(m
, "TIPC_CONN_TIMEOUT", TIPC_CONN_TIMEOUT
);
4742 PyModule_AddIntConstant(m
, "TIPC_LOW_IMPORTANCE",
4743 TIPC_LOW_IMPORTANCE
);
4744 PyModule_AddIntConstant(m
, "TIPC_MEDIUM_IMPORTANCE",
4745 TIPC_MEDIUM_IMPORTANCE
);
4746 PyModule_AddIntConstant(m
, "TIPC_HIGH_IMPORTANCE",
4747 TIPC_HIGH_IMPORTANCE
);
4748 PyModule_AddIntConstant(m
, "TIPC_CRITICAL_IMPORTANCE",
4749 TIPC_CRITICAL_IMPORTANCE
);
4751 /* for subscriptions */
4752 PyModule_AddIntConstant(m
, "TIPC_SUB_PORTS", TIPC_SUB_PORTS
);
4753 PyModule_AddIntConstant(m
, "TIPC_SUB_SERVICE", TIPC_SUB_SERVICE
);
4754 #ifdef TIPC_SUB_CANCEL
4755 /* doesn't seem to be available everywhere */
4756 PyModule_AddIntConstant(m
, "TIPC_SUB_CANCEL", TIPC_SUB_CANCEL
);
4758 PyModule_AddIntConstant(m
, "TIPC_WAIT_FOREVER", TIPC_WAIT_FOREVER
);
4759 PyModule_AddIntConstant(m
, "TIPC_PUBLISHED", TIPC_PUBLISHED
);
4760 PyModule_AddIntConstant(m
, "TIPC_WITHDRAWN", TIPC_WITHDRAWN
);
4761 PyModule_AddIntConstant(m
, "TIPC_SUBSCR_TIMEOUT", TIPC_SUBSCR_TIMEOUT
);
4762 PyModule_AddIntConstant(m
, "TIPC_CFG_SRV", TIPC_CFG_SRV
);
4763 PyModule_AddIntConstant(m
, "TIPC_TOP_SRV", TIPC_TOP_SRV
);
4767 PyModule_AddIntConstant(m
, "SOCK_STREAM", SOCK_STREAM
);
4768 PyModule_AddIntConstant(m
, "SOCK_DGRAM", SOCK_DGRAM
);
4770 /* We have incomplete socket support. */
4771 PyModule_AddIntConstant(m
, "SOCK_RAW", SOCK_RAW
);
4772 PyModule_AddIntConstant(m
, "SOCK_SEQPACKET", SOCK_SEQPACKET
);
4773 #if defined(SOCK_RDM)
4774 PyModule_AddIntConstant(m
, "SOCK_RDM", SOCK_RDM
);
4779 PyModule_AddIntConstant(m
, "SO_DEBUG", SO_DEBUG
);
4781 #ifdef SO_ACCEPTCONN
4782 PyModule_AddIntConstant(m
, "SO_ACCEPTCONN", SO_ACCEPTCONN
);
4785 PyModule_AddIntConstant(m
, "SO_REUSEADDR", SO_REUSEADDR
);
4787 #ifdef SO_EXCLUSIVEADDRUSE
4788 PyModule_AddIntConstant(m
, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE
);
4792 PyModule_AddIntConstant(m
, "SO_KEEPALIVE", SO_KEEPALIVE
);
4795 PyModule_AddIntConstant(m
, "SO_DONTROUTE", SO_DONTROUTE
);
4798 PyModule_AddIntConstant(m
, "SO_BROADCAST", SO_BROADCAST
);
4800 #ifdef SO_USELOOPBACK
4801 PyModule_AddIntConstant(m
, "SO_USELOOPBACK", SO_USELOOPBACK
);
4804 PyModule_AddIntConstant(m
, "SO_LINGER", SO_LINGER
);
4807 PyModule_AddIntConstant(m
, "SO_OOBINLINE", SO_OOBINLINE
);
4810 PyModule_AddIntConstant(m
, "SO_REUSEPORT", SO_REUSEPORT
);
4813 PyModule_AddIntConstant(m
, "SO_SNDBUF", SO_SNDBUF
);
4816 PyModule_AddIntConstant(m
, "SO_RCVBUF", SO_RCVBUF
);
4819 PyModule_AddIntConstant(m
, "SO_SNDLOWAT", SO_SNDLOWAT
);
4822 PyModule_AddIntConstant(m
, "SO_RCVLOWAT", SO_RCVLOWAT
);
4825 PyModule_AddIntConstant(m
, "SO_SNDTIMEO", SO_SNDTIMEO
);
4828 PyModule_AddIntConstant(m
, "SO_RCVTIMEO", SO_RCVTIMEO
);
4831 PyModule_AddIntConstant(m
, "SO_ERROR", SO_ERROR
);
4834 PyModule_AddIntConstant(m
, "SO_TYPE", SO_TYPE
);
4837 PyModule_AddIntConstant(m
, "SO_SETFIB", SO_SETFIB
);
4840 /* Maximum number of connections for "listen" */
4842 PyModule_AddIntConstant(m
, "SOMAXCONN", SOMAXCONN
);
4844 PyModule_AddIntConstant(m
, "SOMAXCONN", 5); /* Common value */
4847 /* Flags for send, recv */
4849 PyModule_AddIntConstant(m
, "MSG_OOB", MSG_OOB
);
4852 PyModule_AddIntConstant(m
, "MSG_PEEK", MSG_PEEK
);
4854 #ifdef MSG_DONTROUTE
4855 PyModule_AddIntConstant(m
, "MSG_DONTROUTE", MSG_DONTROUTE
);
4858 PyModule_AddIntConstant(m
, "MSG_DONTWAIT", MSG_DONTWAIT
);
4861 PyModule_AddIntConstant(m
, "MSG_EOR", MSG_EOR
);
4864 PyModule_AddIntConstant(m
, "MSG_TRUNC", MSG_TRUNC
);
4867 PyModule_AddIntConstant(m
, "MSG_CTRUNC", MSG_CTRUNC
);
4870 PyModule_AddIntConstant(m
, "MSG_WAITALL", MSG_WAITALL
);
4873 PyModule_AddIntConstant(m
, "MSG_BTAG", MSG_BTAG
);
4876 PyModule_AddIntConstant(m
, "MSG_ETAG", MSG_ETAG
);
4879 /* Protocol level and numbers, usable for [gs]etsockopt */
4881 PyModule_AddIntConstant(m
, "SOL_SOCKET", SOL_SOCKET
);
4884 PyModule_AddIntConstant(m
, "SOL_IP", SOL_IP
);
4886 PyModule_AddIntConstant(m
, "SOL_IP", 0);
4889 PyModule_AddIntConstant(m
, "SOL_IPX", SOL_IPX
);
4892 PyModule_AddIntConstant(m
, "SOL_AX25", SOL_AX25
);
4895 PyModule_AddIntConstant(m
, "SOL_ATALK", SOL_ATALK
);
4898 PyModule_AddIntConstant(m
, "SOL_NETROM", SOL_NETROM
);
4901 PyModule_AddIntConstant(m
, "SOL_ROSE", SOL_ROSE
);
4904 PyModule_AddIntConstant(m
, "SOL_TCP", SOL_TCP
);
4906 PyModule_AddIntConstant(m
, "SOL_TCP", 6);
4909 PyModule_AddIntConstant(m
, "SOL_UDP", SOL_UDP
);
4911 PyModule_AddIntConstant(m
, "SOL_UDP", 17);
4914 PyModule_AddIntConstant(m
, "IPPROTO_IP", IPPROTO_IP
);
4916 PyModule_AddIntConstant(m
, "IPPROTO_IP", 0);
4918 #ifdef IPPROTO_HOPOPTS
4919 PyModule_AddIntConstant(m
, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS
);
4922 PyModule_AddIntConstant(m
, "IPPROTO_ICMP", IPPROTO_ICMP
);
4924 PyModule_AddIntConstant(m
, "IPPROTO_ICMP", 1);
4927 PyModule_AddIntConstant(m
, "IPPROTO_IGMP", IPPROTO_IGMP
);
4930 PyModule_AddIntConstant(m
, "IPPROTO_GGP", IPPROTO_GGP
);
4933 PyModule_AddIntConstant(m
, "IPPROTO_IPV4", IPPROTO_IPV4
);
4936 PyModule_AddIntConstant(m
, "IPPROTO_IPV6", IPPROTO_IPV6
);
4939 PyModule_AddIntConstant(m
, "IPPROTO_IPIP", IPPROTO_IPIP
);
4942 PyModule_AddIntConstant(m
, "IPPROTO_TCP", IPPROTO_TCP
);
4944 PyModule_AddIntConstant(m
, "IPPROTO_TCP", 6);
4947 PyModule_AddIntConstant(m
, "IPPROTO_EGP", IPPROTO_EGP
);
4950 PyModule_AddIntConstant(m
, "IPPROTO_PUP", IPPROTO_PUP
);
4953 PyModule_AddIntConstant(m
, "IPPROTO_UDP", IPPROTO_UDP
);
4955 PyModule_AddIntConstant(m
, "IPPROTO_UDP", 17);
4958 PyModule_AddIntConstant(m
, "IPPROTO_IDP", IPPROTO_IDP
);
4960 #ifdef IPPROTO_HELLO
4961 PyModule_AddIntConstant(m
, "IPPROTO_HELLO", IPPROTO_HELLO
);
4964 PyModule_AddIntConstant(m
, "IPPROTO_ND", IPPROTO_ND
);
4967 PyModule_AddIntConstant(m
, "IPPROTO_TP", IPPROTO_TP
);
4970 PyModule_AddIntConstant(m
, "IPPROTO_IPV6", IPPROTO_IPV6
);
4972 #ifdef IPPROTO_ROUTING
4973 PyModule_AddIntConstant(m
, "IPPROTO_ROUTING", IPPROTO_ROUTING
);
4975 #ifdef IPPROTO_FRAGMENT
4976 PyModule_AddIntConstant(m
, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT
);
4979 PyModule_AddIntConstant(m
, "IPPROTO_RSVP", IPPROTO_RSVP
);
4982 PyModule_AddIntConstant(m
, "IPPROTO_GRE", IPPROTO_GRE
);
4985 PyModule_AddIntConstant(m
, "IPPROTO_ESP", IPPROTO_ESP
);
4988 PyModule_AddIntConstant(m
, "IPPROTO_AH", IPPROTO_AH
);
4990 #ifdef IPPROTO_MOBILE
4991 PyModule_AddIntConstant(m
, "IPPROTO_MOBILE", IPPROTO_MOBILE
);
4993 #ifdef IPPROTO_ICMPV6
4994 PyModule_AddIntConstant(m
, "IPPROTO_ICMPV6", IPPROTO_ICMPV6
);
4997 PyModule_AddIntConstant(m
, "IPPROTO_NONE", IPPROTO_NONE
);
4999 #ifdef IPPROTO_DSTOPTS
5000 PyModule_AddIntConstant(m
, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS
);
5003 PyModule_AddIntConstant(m
, "IPPROTO_XTP", IPPROTO_XTP
);
5006 PyModule_AddIntConstant(m
, "IPPROTO_EON", IPPROTO_EON
);
5009 PyModule_AddIntConstant(m
, "IPPROTO_PIM", IPPROTO_PIM
);
5011 #ifdef IPPROTO_IPCOMP
5012 PyModule_AddIntConstant(m
, "IPPROTO_IPCOMP", IPPROTO_IPCOMP
);
5015 PyModule_AddIntConstant(m
, "IPPROTO_VRRP", IPPROTO_VRRP
);
5018 PyModule_AddIntConstant(m
, "IPPROTO_BIP", IPPROTO_BIP
);
5022 PyModule_AddIntConstant(m
, "IPPROTO_RAW", IPPROTO_RAW
);
5024 PyModule_AddIntConstant(m
, "IPPROTO_RAW", 255);
5027 PyModule_AddIntConstant(m
, "IPPROTO_MAX", IPPROTO_MAX
);
5030 /* Some port configuration */
5031 #ifdef IPPORT_RESERVED
5032 PyModule_AddIntConstant(m
, "IPPORT_RESERVED", IPPORT_RESERVED
);
5034 PyModule_AddIntConstant(m
, "IPPORT_RESERVED", 1024);
5036 #ifdef IPPORT_USERRESERVED
5037 PyModule_AddIntConstant(m
, "IPPORT_USERRESERVED", IPPORT_USERRESERVED
);
5039 PyModule_AddIntConstant(m
, "IPPORT_USERRESERVED", 5000);
5042 /* Some reserved IP v.4 addresses */
5044 PyModule_AddIntConstant(m
, "INADDR_ANY", INADDR_ANY
);
5046 PyModule_AddIntConstant(m
, "INADDR_ANY", 0x00000000);
5048 #ifdef INADDR_BROADCAST
5049 PyModule_AddIntConstant(m
, "INADDR_BROADCAST", INADDR_BROADCAST
);
5051 PyModule_AddIntConstant(m
, "INADDR_BROADCAST", 0xffffffff);
5053 #ifdef INADDR_LOOPBACK
5054 PyModule_AddIntConstant(m
, "INADDR_LOOPBACK", INADDR_LOOPBACK
);
5056 PyModule_AddIntConstant(m
, "INADDR_LOOPBACK", 0x7F000001);
5058 #ifdef INADDR_UNSPEC_GROUP
5059 PyModule_AddIntConstant(m
, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP
);
5061 PyModule_AddIntConstant(m
, "INADDR_UNSPEC_GROUP", 0xe0000000);
5063 #ifdef INADDR_ALLHOSTS_GROUP
5064 PyModule_AddIntConstant(m
, "INADDR_ALLHOSTS_GROUP",
5065 INADDR_ALLHOSTS_GROUP
);
5067 PyModule_AddIntConstant(m
, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
5069 #ifdef INADDR_MAX_LOCAL_GROUP
5070 PyModule_AddIntConstant(m
, "INADDR_MAX_LOCAL_GROUP",
5071 INADDR_MAX_LOCAL_GROUP
);
5073 PyModule_AddIntConstant(m
, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
5076 PyModule_AddIntConstant(m
, "INADDR_NONE", INADDR_NONE
);
5078 PyModule_AddIntConstant(m
, "INADDR_NONE", 0xffffffff);
5081 /* IPv4 [gs]etsockopt options */
5083 PyModule_AddIntConstant(m
, "IP_OPTIONS", IP_OPTIONS
);
5086 PyModule_AddIntConstant(m
, "IP_HDRINCL", IP_HDRINCL
);
5089 PyModule_AddIntConstant(m
, "IP_TOS", IP_TOS
);
5092 PyModule_AddIntConstant(m
, "IP_TTL", IP_TTL
);
5095 PyModule_AddIntConstant(m
, "IP_RECVOPTS", IP_RECVOPTS
);
5097 #ifdef IP_RECVRETOPTS
5098 PyModule_AddIntConstant(m
, "IP_RECVRETOPTS", IP_RECVRETOPTS
);
5100 #ifdef IP_RECVDSTADDR
5101 PyModule_AddIntConstant(m
, "IP_RECVDSTADDR", IP_RECVDSTADDR
);
5104 PyModule_AddIntConstant(m
, "IP_RETOPTS", IP_RETOPTS
);
5106 #ifdef IP_MULTICAST_IF
5107 PyModule_AddIntConstant(m
, "IP_MULTICAST_IF", IP_MULTICAST_IF
);
5109 #ifdef IP_MULTICAST_TTL
5110 PyModule_AddIntConstant(m
, "IP_MULTICAST_TTL", IP_MULTICAST_TTL
);
5112 #ifdef IP_MULTICAST_LOOP
5113 PyModule_AddIntConstant(m
, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP
);
5115 #ifdef IP_ADD_MEMBERSHIP
5116 PyModule_AddIntConstant(m
, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP
);
5118 #ifdef IP_DROP_MEMBERSHIP
5119 PyModule_AddIntConstant(m
, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP
);
5121 #ifdef IP_DEFAULT_MULTICAST_TTL
5122 PyModule_AddIntConstant(m
, "IP_DEFAULT_MULTICAST_TTL",
5123 IP_DEFAULT_MULTICAST_TTL
);
5125 #ifdef IP_DEFAULT_MULTICAST_LOOP
5126 PyModule_AddIntConstant(m
, "IP_DEFAULT_MULTICAST_LOOP",
5127 IP_DEFAULT_MULTICAST_LOOP
);
5129 #ifdef IP_MAX_MEMBERSHIPS
5130 PyModule_AddIntConstant(m
, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS
);
5133 /* IPv6 [gs]etsockopt options, defined in RFC2553 */
5134 #ifdef IPV6_JOIN_GROUP
5135 PyModule_AddIntConstant(m
, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP
);
5137 #ifdef IPV6_LEAVE_GROUP
5138 PyModule_AddIntConstant(m
, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP
);
5140 #ifdef IPV6_MULTICAST_HOPS
5141 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS
);
5143 #ifdef IPV6_MULTICAST_IF
5144 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF
);
5146 #ifdef IPV6_MULTICAST_LOOP
5147 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP
);
5149 #ifdef IPV6_UNICAST_HOPS
5150 PyModule_AddIntConstant(m
, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS
);
5152 /* Additional IPV6 socket options, defined in RFC 3493 */
5154 PyModule_AddIntConstant(m
, "IPV6_V6ONLY", IPV6_V6ONLY
);
5156 /* Advanced IPV6 socket options, from RFC 3542 */
5157 #ifdef IPV6_CHECKSUM
5158 PyModule_AddIntConstant(m
, "IPV6_CHECKSUM", IPV6_CHECKSUM
);
5160 #ifdef IPV6_DONTFRAG
5161 PyModule_AddIntConstant(m
, "IPV6_DONTFRAG", IPV6_DONTFRAG
);
5164 PyModule_AddIntConstant(m
, "IPV6_DSTOPTS", IPV6_DSTOPTS
);
5166 #ifdef IPV6_HOPLIMIT
5167 PyModule_AddIntConstant(m
, "IPV6_HOPLIMIT", IPV6_HOPLIMIT
);
5170 PyModule_AddIntConstant(m
, "IPV6_HOPOPTS", IPV6_HOPOPTS
);
5173 PyModule_AddIntConstant(m
, "IPV6_NEXTHOP", IPV6_NEXTHOP
);
5176 PyModule_AddIntConstant(m
, "IPV6_PATHMTU", IPV6_PATHMTU
);
5179 PyModule_AddIntConstant(m
, "IPV6_PKTINFO", IPV6_PKTINFO
);
5181 #ifdef IPV6_RECVDSTOPTS
5182 PyModule_AddIntConstant(m
, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS
);
5184 #ifdef IPV6_RECVHOPLIMIT
5185 PyModule_AddIntConstant(m
, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT
);
5187 #ifdef IPV6_RECVHOPOPTS
5188 PyModule_AddIntConstant(m
, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS
);
5190 #ifdef IPV6_RECVPKTINFO
5191 PyModule_AddIntConstant(m
, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO
);
5193 #ifdef IPV6_RECVRTHDR
5194 PyModule_AddIntConstant(m
, "IPV6_RECVRTHDR", IPV6_RECVRTHDR
);
5196 #ifdef IPV6_RECVTCLASS
5197 PyModule_AddIntConstant(m
, "IPV6_RECVTCLASS", IPV6_RECVTCLASS
);
5200 PyModule_AddIntConstant(m
, "IPV6_RTHDR", IPV6_RTHDR
);
5202 #ifdef IPV6_RTHDRDSTOPTS
5203 PyModule_AddIntConstant(m
, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS
);
5205 #ifdef IPV6_RTHDR_TYPE_0
5206 PyModule_AddIntConstant(m
, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0
);
5208 #ifdef IPV6_RECVPATHMTU
5209 PyModule_AddIntConstant(m
, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU
);
5212 PyModule_AddIntConstant(m
, "IPV6_TCLASS", IPV6_TCLASS
);
5214 #ifdef IPV6_USE_MIN_MTU
5215 PyModule_AddIntConstant(m
, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU
);
5220 PyModule_AddIntConstant(m
, "TCP_NODELAY", TCP_NODELAY
);
5223 PyModule_AddIntConstant(m
, "TCP_MAXSEG", TCP_MAXSEG
);
5226 PyModule_AddIntConstant(m
, "TCP_CORK", TCP_CORK
);
5229 PyModule_AddIntConstant(m
, "TCP_KEEPIDLE", TCP_KEEPIDLE
);
5231 #ifdef TCP_KEEPINTVL
5232 PyModule_AddIntConstant(m
, "TCP_KEEPINTVL", TCP_KEEPINTVL
);
5235 PyModule_AddIntConstant(m
, "TCP_KEEPCNT", TCP_KEEPCNT
);
5238 PyModule_AddIntConstant(m
, "TCP_SYNCNT", TCP_SYNCNT
);
5241 PyModule_AddIntConstant(m
, "TCP_LINGER2", TCP_LINGER2
);
5243 #ifdef TCP_DEFER_ACCEPT
5244 PyModule_AddIntConstant(m
, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT
);
5246 #ifdef TCP_WINDOW_CLAMP
5247 PyModule_AddIntConstant(m
, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP
);
5250 PyModule_AddIntConstant(m
, "TCP_INFO", TCP_INFO
);
5253 PyModule_AddIntConstant(m
, "TCP_QUICKACK", TCP_QUICKACK
);
5259 PyModule_AddIntConstant(m
, "IPX_TYPE", IPX_TYPE
);
5262 /* get{addr,name}info parameters */
5263 #ifdef EAI_ADDRFAMILY
5264 PyModule_AddIntConstant(m
, "EAI_ADDRFAMILY", EAI_ADDRFAMILY
);
5267 PyModule_AddIntConstant(m
, "EAI_AGAIN", EAI_AGAIN
);
5270 PyModule_AddIntConstant(m
, "EAI_BADFLAGS", EAI_BADFLAGS
);
5273 PyModule_AddIntConstant(m
, "EAI_FAIL", EAI_FAIL
);
5276 PyModule_AddIntConstant(m
, "EAI_FAMILY", EAI_FAMILY
);
5279 PyModule_AddIntConstant(m
, "EAI_MEMORY", EAI_MEMORY
);
5282 PyModule_AddIntConstant(m
, "EAI_NODATA", EAI_NODATA
);
5285 PyModule_AddIntConstant(m
, "EAI_NONAME", EAI_NONAME
);
5288 PyModule_AddIntConstant(m
, "EAI_OVERFLOW", EAI_OVERFLOW
);
5291 PyModule_AddIntConstant(m
, "EAI_SERVICE", EAI_SERVICE
);
5294 PyModule_AddIntConstant(m
, "EAI_SOCKTYPE", EAI_SOCKTYPE
);
5297 PyModule_AddIntConstant(m
, "EAI_SYSTEM", EAI_SYSTEM
);
5300 PyModule_AddIntConstant(m
, "EAI_BADHINTS", EAI_BADHINTS
);
5303 PyModule_AddIntConstant(m
, "EAI_PROTOCOL", EAI_PROTOCOL
);
5306 PyModule_AddIntConstant(m
, "EAI_MAX", EAI_MAX
);
5309 PyModule_AddIntConstant(m
, "AI_PASSIVE", AI_PASSIVE
);
5312 PyModule_AddIntConstant(m
, "AI_CANONNAME", AI_CANONNAME
);
5314 #ifdef AI_NUMERICHOST
5315 PyModule_AddIntConstant(m
, "AI_NUMERICHOST", AI_NUMERICHOST
);
5317 #ifdef AI_NUMERICSERV
5318 PyModule_AddIntConstant(m
, "AI_NUMERICSERV", AI_NUMERICSERV
);
5321 PyModule_AddIntConstant(m
, "AI_MASK", AI_MASK
);
5324 PyModule_AddIntConstant(m
, "AI_ALL", AI_ALL
);
5326 #ifdef AI_V4MAPPED_CFG
5327 PyModule_AddIntConstant(m
, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG
);
5329 #ifdef AI_ADDRCONFIG
5330 PyModule_AddIntConstant(m
, "AI_ADDRCONFIG", AI_ADDRCONFIG
);
5333 PyModule_AddIntConstant(m
, "AI_V4MAPPED", AI_V4MAPPED
);
5336 PyModule_AddIntConstant(m
, "AI_DEFAULT", AI_DEFAULT
);
5339 PyModule_AddIntConstant(m
, "NI_MAXHOST", NI_MAXHOST
);
5342 PyModule_AddIntConstant(m
, "NI_MAXSERV", NI_MAXSERV
);
5345 PyModule_AddIntConstant(m
, "NI_NOFQDN", NI_NOFQDN
);
5347 #ifdef NI_NUMERICHOST
5348 PyModule_AddIntConstant(m
, "NI_NUMERICHOST", NI_NUMERICHOST
);
5351 PyModule_AddIntConstant(m
, "NI_NAMEREQD", NI_NAMEREQD
);
5353 #ifdef NI_NUMERICSERV
5354 PyModule_AddIntConstant(m
, "NI_NUMERICSERV", NI_NUMERICSERV
);
5357 PyModule_AddIntConstant(m
, "NI_DGRAM", NI_DGRAM
);
5360 /* shutdown() parameters */
5362 PyModule_AddIntConstant(m
, "SHUT_RD", SHUT_RD
);
5363 #elif defined(SD_RECEIVE)
5364 PyModule_AddIntConstant(m
, "SHUT_RD", SD_RECEIVE
);
5366 PyModule_AddIntConstant(m
, "SHUT_RD", 0);
5369 PyModule_AddIntConstant(m
, "SHUT_WR", SHUT_WR
);
5370 #elif defined(SD_SEND)
5371 PyModule_AddIntConstant(m
, "SHUT_WR", SD_SEND
);
5373 PyModule_AddIntConstant(m
, "SHUT_WR", 1);
5376 PyModule_AddIntConstant(m
, "SHUT_RDWR", SHUT_RDWR
);
5377 #elif defined(SD_BOTH)
5378 PyModule_AddIntConstant(m
, "SHUT_RDWR", SD_BOTH
);
5380 PyModule_AddIntConstant(m
, "SHUT_RDWR", 2);
5385 DWORD codes
[] = {SIO_RCVALL
, SIO_KEEPALIVE_VALS
};
5386 const char *names
[] = {"SIO_RCVALL", "SIO_KEEPALIVE_VALS"};
5388 for(i
= 0; i
<sizeof(codes
)/sizeof(*codes
); ++i
) {
5390 tmp
= PyLong_FromUnsignedLong(codes
[i
]);
5393 PyModule_AddObject(m
, names
[i
], tmp
);
5396 PyModule_AddIntConstant(m
, "RCVALL_OFF", RCVALL_OFF
);
5397 PyModule_AddIntConstant(m
, "RCVALL_ON", RCVALL_ON
);
5398 PyModule_AddIntConstant(m
, "RCVALL_SOCKETLEVELONLY", RCVALL_SOCKETLEVELONLY
);
5399 #ifdef RCVALL_IPLEVEL
5400 PyModule_AddIntConstant(m
, "RCVALL_IPLEVEL", RCVALL_IPLEVEL
);
5403 PyModule_AddIntConstant(m
, "RCVALL_MAX", RCVALL_MAX
);
5405 #endif /* _MSTCPIP_ */
5407 /* Initialize gethostbyname lock */
5408 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
5409 netdb_lock
= PyThread_allocate_lock();
5414 #ifndef HAVE_INET_PTON
5415 #if !defined(NTDDI_VERSION) || (NTDDI_VERSION < NTDDI_LONGHORN)
5417 /* Simplistic emulation code for inet_pton that only works for IPv4 */
5418 /* These are not exposed because they do not set errno properly */
5421 inet_pton(int af
, const char *src
, void *dst
)
5423 if (af
== AF_INET
) {
5424 #if (SIZEOF_INT != 4)
5425 #error "Not sure if in_addr_t exists and int is not 32-bits."
5427 unsigned int packed_addr
;
5428 packed_addr
= inet_addr(src
);
5429 if (packed_addr
== INADDR_NONE
)
5431 memcpy(dst
, &packed_addr
, 4);
5434 /* Should set errno to EAFNOSUPPORT */
5439 inet_ntop(int af
, const void *src
, char *dst
, socklen_t size
)
5441 if (af
== AF_INET
) {
5442 struct in_addr packed_addr
;
5444 /* Should set errno to ENOSPC. */
5446 memcpy(&packed_addr
, src
, sizeof(packed_addr
));
5447 return strncpy(dst
, inet_ntoa(packed_addr
), size
);
5449 /* Should set errno to EAFNOSUPPORT */