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__)
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__)
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 _BT_L2_MEMB(sa, memb) ((sa)->bt_##memb)
402 #define _BT_RC_MEMB(sa, memb) ((sa)->bt_##memb)
403 #define _BT_HCI_MEMB(sa, memb) ((sa)->bt_##memb)
404 #define _BT_SCO_MEMB(sa, memb) ((sa)->bt_##memb)
406 #define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb)
407 #define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb)
408 #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
409 #define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)
414 /* TCP/IP Services for VMS uses a maximum send/recv buffer length */
415 #define SEGMENT_SIZE (32 * 1024 -1)
418 #define SAS2SA(x) ((struct sockaddr *)(x))
421 * Constants for getnameinfo()
423 #if !defined(NI_MAXHOST)
424 #define NI_MAXHOST 1025
426 #if !defined(NI_MAXSERV)
427 #define NI_MAXSERV 32
430 /* XXX There's a problem here: *static* functions are not supposed to have
431 a Py prefix (or use CapitalizedWords). Later... */
433 /* Global variable holding the exception type for errors detected
434 by this module (but not argument type or memory errors, etc.). */
435 static PyObject
*socket_error
;
436 static PyObject
*socket_herror
;
437 static PyObject
*socket_gaierror
;
438 static PyObject
*socket_timeout
;
441 /* Global variable which is !=0 if Python is running in a RISC OS taskwindow */
442 static int taskwindow
;
445 /* A forward reference to the socket type object.
446 The sock_type variable contains pointers to various functions,
447 some of which call new_sockobject(), which uses sock_type, so
448 there has to be a circular reference. */
449 static PyTypeObject sock_type
;
451 #if defined(HAVE_POLL_H)
453 #elif defined(HAVE_SYS_POLL_H)
454 #include <sys/poll.h>
457 #ifdef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
458 /* Platform can select file descriptors beyond FD_SETSIZE */
459 #define IS_SELECTABLE(s) 1
460 #elif defined(HAVE_POLL)
461 /* Instead of select(), we'll use poll() since poll() works on any fd. */
462 #define IS_SELECTABLE(s) 1
463 /* Can we call select() with this socket without a buffer overrun? */
465 /* POSIX says selecting file descriptors beyond FD_SETSIZE
466 has undefined behaviour. If there's no timeout left, we don't have to
467 call select, so it's a safe, little white lie. */
468 #define IS_SELECTABLE(s) ((s)->sock_fd < FD_SETSIZE || s->sock_timeout <= 0.0)
474 PyErr_SetString(socket_error
, "unable to select on socket");
478 /* Convenience function to raise an error according to errno
479 and return a NULL pointer from a function. */
485 int err_no
= WSAGetLastError();
486 /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which
487 recognizes the error codes used by both GetLastError() and
490 return PyErr_SetExcFromWindowsErr(socket_error
, err_no
);
493 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
494 if (sock_errno() != NO_ERROR
) {
498 int myerrorcode
= sock_errno();
500 /* Retrieve socket-related error message from MPTN.MSG file */
501 rc
= DosGetMessage(NULL
, 0, outbuf
, sizeof(outbuf
),
502 myerrorcode
- SOCBASEERR
+ 26,
505 if (rc
== NO_ERROR
) {
508 /* OS/2 doesn't guarantee a terminator */
509 outbuf
[msglen
] = '\0';
510 if (strlen(outbuf
) > 0) {
511 /* If non-empty msg, trim CRLF */
512 char *lastc
= &outbuf
[ strlen(outbuf
)-1 ];
513 while (lastc
> outbuf
&&
514 isspace(Py_CHARMASK(*lastc
))) {
515 /* Trim trailing whitespace (CRLF) */
519 v
= Py_BuildValue("(is)", myerrorcode
, outbuf
);
521 PyErr_SetObject(socket_error
, v
);
530 if (_inet_error
.errnum
!= NULL
) {
532 v
= Py_BuildValue("(is)", errno
, _inet_err());
534 PyErr_SetObject(socket_error
, v
);
541 return PyErr_SetFromErrno(socket_error
);
546 set_herror(int h_error
)
550 #ifdef HAVE_HSTRERROR
551 v
= Py_BuildValue("(is)", h_error
, (char *)hstrerror(h_error
));
553 v
= Py_BuildValue("(is)", h_error
, "host not found");
556 PyErr_SetObject(socket_herror
, v
);
565 set_gaierror(int error
)
570 /* EAI_SYSTEM is not available on Windows XP. */
571 if (error
== EAI_SYSTEM
)
575 #ifdef HAVE_GAI_STRERROR
576 v
= Py_BuildValue("(is)", error
, gai_strerror(error
));
578 v
= Py_BuildValue("(is)", error
, "getaddrinfo failed");
581 PyErr_SetObject(socket_gaierror
, v
);
589 /* Function to send in segments */
591 sendsegmented(int sock_fd
, char *buf
, int len
, int flags
)
596 while (remaining
> 0) {
597 unsigned int segment
;
599 segment
= (remaining
>= SEGMENT_SIZE
? SEGMENT_SIZE
: remaining
);
600 n
= send(sock_fd
, buf
, segment
, flags
);
604 remaining
-= segment
;
612 /* Function to perform the setting of socket blocking mode
613 internally. block = (1 | 0). */
615 internal_setblocking(PySocketSockObject
*s
, int block
)
623 Py_BEGIN_ALLOW_THREADS
626 setsockopt(s
->sock_fd
, SOL_SOCKET
, SO_NONBLOCK
,
627 (void *)(&block
), sizeof(int));
631 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
633 ioctl(s
->sock_fd
, FIONBIO
, (caddr_t
)&block
, sizeof(block
));
636 ioctl(s
->sock_fd
, FIONBIO
, (unsigned int *)&block
);
637 #else /* !PYOS_OS2 && !__VMS */
638 delay_flag
= fcntl(s
->sock_fd
, F_GETFL
, 0);
640 delay_flag
&= (~O_NONBLOCK
);
642 delay_flag
|= O_NONBLOCK
;
643 fcntl(s
->sock_fd
, F_SETFL
, delay_flag
);
644 #endif /* !PYOS_OS2 */
645 #else /* MS_WINDOWS */
647 ioctlsocket(s
->sock_fd
, FIONBIO
, (u_long
*)&block
);
648 #endif /* MS_WINDOWS */
651 socketioctl(s
->sock_fd
, FIONBIO
, (u_long
*)&block
);
653 #endif /* __BEOS__ */
656 /* Since these don't return anything */
660 /* Do a select()/poll() on the socket, if necessary (sock_timeout > 0).
661 The argument writing indicates the direction.
662 This does not raise an exception; we'll let our caller do that
663 after they've reacquired the interpreter lock.
664 Returns 1 on timeout, -1 on error, 0 otherwise. */
666 internal_select(PySocketSockObject
*s
, int writing
)
670 /* Nothing to do unless we're in timeout mode (not non-blocking) */
671 if (s
->sock_timeout
<= 0.0)
674 /* Guard against closed socket */
678 /* Prefer poll, if available, since you can poll() any fd
679 * which can't be done with select(). */
682 struct pollfd pollfd
;
685 pollfd
.fd
= s
->sock_fd
;
686 pollfd
.events
= writing
? POLLOUT
: POLLIN
;
688 /* s->sock_timeout is in seconds, timeout in ms */
689 timeout
= (int)(s
->sock_timeout
* 1000 + 0.5);
690 n
= poll(&pollfd
, 1, timeout
);
694 /* Construct the arguments to select */
697 tv
.tv_sec
= (int)s
->sock_timeout
;
698 tv
.tv_usec
= (int)((s
->sock_timeout
- tv
.tv_sec
) * 1e6
);
700 FD_SET(s
->sock_fd
, &fds
);
702 /* See if the socket is ready */
704 n
= select(s
->sock_fd
+1, NULL
, &fds
, NULL
, &tv
);
706 n
= select(s
->sock_fd
+1, &fds
, NULL
, NULL
, &tv
);
717 /* Initialize a new socket object. */
719 static double defaulttimeout
= -1.0; /* Default timeout for new sockets */
722 init_sockobject(PySocketSockObject
*s
,
723 SOCKET_T fd
, int family
, int type
, int proto
)
729 s
->sock_family
= family
;
731 s
->sock_proto
= proto
;
732 s
->sock_timeout
= defaulttimeout
;
734 s
->errorhandler
= &set_error
;
736 if (defaulttimeout
>= 0.0)
737 internal_setblocking(s
, 0);
741 socketioctl(s
->sock_fd
, 0x80046679, (u_long
*)&block
);
746 /* Create a new socket object.
747 This just creates the object and initializes it.
748 If the creation fails, return NULL and set an exception (implicit
751 static PySocketSockObject
*
752 new_sockobject(SOCKET_T fd
, int family
, int type
, int proto
)
754 PySocketSockObject
*s
;
755 s
= (PySocketSockObject
*)
756 PyType_GenericNew(&sock_type
, NULL
, NULL
);
758 init_sockobject(s
, fd
, family
, type
, proto
);
763 /* Lock to allow python interpreter to continue, but only allow one
764 thread to be in gethostbyname or getaddrinfo */
765 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
766 PyThread_type_lock netdb_lock
;
770 /* Convert a string specifying a host name or one of a few symbolic
771 names to a numeric IP address. This usually calls gethostbyname()
772 to do the work; the names "" and "<broadcast>" are special.
773 Return the length (IPv4 should be 4 bytes), or negative if
774 an error occurred; then an exception is raised. */
777 setipaddr(char *name
, struct sockaddr
*addr_ret
, size_t addr_ret_size
, int af
)
779 struct addrinfo hints
, *res
;
784 memset((void *) addr_ret
, '\0', sizeof(*addr_ret
));
785 if (name
[0] == '\0') {
787 memset(&hints
, 0, sizeof(hints
));
788 hints
.ai_family
= af
;
789 hints
.ai_socktype
= SOCK_DGRAM
; /*dummy*/
790 hints
.ai_flags
= AI_PASSIVE
;
791 Py_BEGIN_ALLOW_THREADS
792 ACQUIRE_GETADDRINFO_LOCK
793 error
= getaddrinfo(NULL
, "0", &hints
, &res
);
795 /* We assume that those thread-unsafe getaddrinfo() versions
796 *are* safe regarding their return value, ie. that a
797 subsequent call to getaddrinfo() does not destroy the
798 outcome of the first call. */
799 RELEASE_GETADDRINFO_LOCK
804 switch (res
->ai_family
) {
815 PyErr_SetString(socket_error
,
816 "unsupported address family");
821 PyErr_SetString(socket_error
,
822 "wildcard resolved to multiple address");
825 if (res
->ai_addrlen
< addr_ret_size
)
826 addr_ret_size
= res
->ai_addrlen
;
827 memcpy(addr_ret
, res
->ai_addr
, addr_ret_size
);
831 if (name
[0] == '<' && strcmp(name
, "<broadcast>") == 0) {
832 struct sockaddr_in
*sin
;
833 if (af
!= AF_INET
&& af
!= AF_UNSPEC
) {
834 PyErr_SetString(socket_error
,
835 "address family mismatched");
838 sin
= (struct sockaddr_in
*)addr_ret
;
839 memset((void *) sin
, '\0', sizeof(*sin
));
840 sin
->sin_family
= AF_INET
;
841 #ifdef HAVE_SOCKADDR_SA_LEN
842 sin
->sin_len
= sizeof(*sin
);
844 sin
->sin_addr
.s_addr
= INADDR_BROADCAST
;
845 return sizeof(sin
->sin_addr
);
847 if (sscanf(name
, "%d.%d.%d.%d%c", &d1
, &d2
, &d3
, &d4
, &ch
) == 4 &&
848 0 <= d1
&& d1
<= 255 && 0 <= d2
&& d2
<= 255 &&
849 0 <= d3
&& d3
<= 255 && 0 <= d4
&& d4
<= 255) {
850 struct sockaddr_in
*sin
;
851 sin
= (struct sockaddr_in
*)addr_ret
;
852 sin
->sin_addr
.s_addr
= htonl(
853 ((long) d1
<< 24) | ((long) d2
<< 16) |
854 ((long) d3
<< 8) | ((long) d4
<< 0));
855 sin
->sin_family
= AF_INET
;
856 #ifdef HAVE_SOCKADDR_SA_LEN
857 sin
->sin_len
= sizeof(*sin
);
861 memset(&hints
, 0, sizeof(hints
));
862 hints
.ai_family
= af
;
863 Py_BEGIN_ALLOW_THREADS
864 ACQUIRE_GETADDRINFO_LOCK
865 error
= getaddrinfo(name
, NULL
, &hints
, &res
);
866 #if defined(__digital__) && defined(__unix__)
867 if (error
== EAI_NONAME
&& af
== AF_UNSPEC
) {
868 /* On Tru64 V5.1, numeric-to-addr conversion fails
869 if no address family is given. Assume IPv4 for now.*/
870 hints
.ai_family
= AF_INET
;
871 error
= getaddrinfo(name
, NULL
, &hints
, &res
);
875 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
880 if (res
->ai_addrlen
< addr_ret_size
)
881 addr_ret_size
= res
->ai_addrlen
;
882 memcpy((char *) addr_ret
, res
->ai_addr
, addr_ret_size
);
884 switch (addr_ret
->sa_family
) {
892 PyErr_SetString(socket_error
, "unknown address family");
898 /* Create a string object representing an IP address.
899 This is always a string of the form 'dd.dd.dd.dd' (with variable
903 makeipaddr(struct sockaddr
*addr
, int addrlen
)
905 char buf
[NI_MAXHOST
];
908 error
= getnameinfo(addr
, addrlen
, buf
, sizeof(buf
), NULL
, 0,
914 return PyString_FromString(buf
);
919 /* Convert a string representation of a Bluetooth address into a numeric
920 address. Returns the length (6), or raises an exception and returns -1 if
921 an error occurred. */
924 setbdaddr(char *name
, bdaddr_t
*bdaddr
)
926 unsigned int b0
, b1
, b2
, b3
, b4
, b5
;
930 n
= sscanf(name
, "%X:%X:%X:%X:%X:%X%c",
931 &b5
, &b4
, &b3
, &b2
, &b1
, &b0
, &ch
);
932 if (n
== 6 && (b0
| b1
| b2
| b3
| b4
| b5
) < 256) {
941 PyErr_SetString(socket_error
, "bad bluetooth address");
946 /* Create a string representation of the Bluetooth address. This is always a
947 string of the form 'XX:XX:XX:XX:XX:XX' where XX is a two digit hexadecimal
948 value (zero padded if necessary). */
951 makebdaddr(bdaddr_t
*bdaddr
)
953 char buf
[(6 * 2) + 5 + 1];
955 sprintf(buf
, "%02X:%02X:%02X:%02X:%02X:%02X",
956 bdaddr
->b
[5], bdaddr
->b
[4], bdaddr
->b
[3],
957 bdaddr
->b
[2], bdaddr
->b
[1], bdaddr
->b
[0]);
958 return PyString_FromString(buf
);
963 /* Create an object representing the given socket address,
964 suitable for passing it back to bind(), connect() etc.
965 The family field of the sockaddr structure is inspected
966 to determine what kind of address it really is. */
970 makesockaddr(int sockfd
, struct sockaddr
*addr
, int addrlen
, int proto
)
973 /* No address -- may be recvfrom() from known socket */
979 /* XXX: BeOS version of accept() doesn't set family correctly */
980 addr
->sa_family
= AF_INET
;
983 switch (addr
->sa_family
) {
987 struct sockaddr_in
*a
;
988 PyObject
*addrobj
= makeipaddr(addr
, sizeof(*a
));
989 PyObject
*ret
= NULL
;
991 a
= (struct sockaddr_in
*)addr
;
992 ret
= Py_BuildValue("Oi", addrobj
, ntohs(a
->sin_port
));
1001 struct sockaddr_un
*a
= (struct sockaddr_un
*) addr
;
1003 if (a
->sun_path
[0] == 0) { /* Linux abstract namespace */
1004 addrlen
-= offsetof(struct sockaddr_un
, sun_path
);
1005 return PyString_FromStringAndSize(a
->sun_path
,
1011 /* regular NULL-terminated string */
1012 return PyString_FromString(a
->sun_path
);
1015 #endif /* AF_UNIX */
1017 #if defined(AF_NETLINK)
1020 struct sockaddr_nl
*a
= (struct sockaddr_nl
*) addr
;
1021 return Py_BuildValue("II", a
->nl_pid
, a
->nl_groups
);
1023 #endif /* AF_NETLINK */
1028 struct sockaddr_in6
*a
;
1029 PyObject
*addrobj
= makeipaddr(addr
, sizeof(*a
));
1030 PyObject
*ret
= NULL
;
1032 a
= (struct sockaddr_in6
*)addr
;
1033 ret
= Py_BuildValue("Oiii",
1035 ntohs(a
->sin6_port
),
1044 #ifdef USE_BLUETOOTH
1050 struct sockaddr_l2
*a
= (struct sockaddr_l2
*) addr
;
1051 PyObject
*addrobj
= makebdaddr(&_BT_L2_MEMB(a
, bdaddr
));
1052 PyObject
*ret
= NULL
;
1054 ret
= Py_BuildValue("Oi",
1056 _BT_L2_MEMB(a
, psm
));
1062 case BTPROTO_RFCOMM
:
1064 struct sockaddr_rc
*a
= (struct sockaddr_rc
*) addr
;
1065 PyObject
*addrobj
= makebdaddr(&_BT_RC_MEMB(a
, bdaddr
));
1066 PyObject
*ret
= NULL
;
1068 ret
= Py_BuildValue("Oi",
1070 _BT_RC_MEMB(a
, channel
));
1078 struct sockaddr_hci
*a
= (struct sockaddr_hci
*) addr
;
1079 PyObject
*ret
= NULL
;
1080 ret
= Py_BuildValue("i", _BT_HCI_MEMB(a
, dev
));
1084 #if !defined(__FreeBSD__)
1087 struct sockaddr_sco
*a
= (struct sockaddr_sco
*) addr
;
1088 return makebdaddr(&_BT_SCO_MEMB(a
, bdaddr
));
1093 PyErr_SetString(PyExc_ValueError
,
1094 "Unknown Bluetooth protocol");
1099 #ifdef HAVE_NETPACKET_PACKET_H
1102 struct sockaddr_ll
*a
= (struct sockaddr_ll
*)addr
;
1105 /* need to look up interface name give index */
1106 if (a
->sll_ifindex
) {
1107 ifr
.ifr_ifindex
= a
->sll_ifindex
;
1108 if (ioctl(sockfd
, SIOCGIFNAME
, &ifr
) == 0)
1109 ifname
= ifr
.ifr_name
;
1111 return Py_BuildValue("shbhs#",
1113 ntohs(a
->sll_protocol
),
1121 #ifdef HAVE_LINUX_TIPC_H
1124 struct sockaddr_tipc
*a
= (struct sockaddr_tipc
*) addr
;
1125 if (a
->addrtype
== TIPC_ADDR_NAMESEQ
) {
1126 return Py_BuildValue("IIIII",
1128 a
->addr
.nameseq
.type
,
1129 a
->addr
.nameseq
.lower
,
1130 a
->addr
.nameseq
.upper
,
1132 } else if (a
->addrtype
== TIPC_ADDR_NAME
) {
1133 return Py_BuildValue("IIIII",
1135 a
->addr
.name
.name
.type
,
1136 a
->addr
.name
.name
.instance
,
1137 a
->addr
.name
.name
.instance
,
1139 } else if (a
->addrtype
== TIPC_ADDR_ID
) {
1140 return Py_BuildValue("IIIII",
1147 PyErr_SetString(PyExc_ValueError
,
1148 "Invalid address type");
1154 /* More cases here... */
1157 /* If we don't know the address family, don't raise an
1158 exception -- return it as a tuple. */
1159 return Py_BuildValue("is#",
1162 sizeof(addr
->sa_data
));
1168 /* Parse a socket address argument according to the socket object's
1169 address family. Return 1 if the address was in the proper format,
1170 0 of not. The address is returned through addr_ret, its length
1174 getsockaddrarg(PySocketSockObject
*s
, PyObject
*args
,
1175 struct sockaddr
*addr_ret
, int *len_ret
)
1177 switch (s
->sock_family
) {
1179 #if defined(AF_UNIX)
1182 struct sockaddr_un
* addr
;
1185 if (!PyArg_Parse(args
, "t#", &path
, &len
))
1188 addr
= (struct sockaddr_un
*)addr_ret
;
1190 if (len
> 0 && path
[0] == 0) {
1191 /* Linux abstract namespace extension */
1192 if (len
> sizeof addr
->sun_path
) {
1193 PyErr_SetString(socket_error
,
1194 "AF_UNIX path too long");
1201 /* regular NULL-terminated string */
1202 if (len
>= sizeof addr
->sun_path
) {
1203 PyErr_SetString(socket_error
,
1204 "AF_UNIX path too long");
1207 addr
->sun_path
[len
] = 0;
1209 addr
->sun_family
= s
->sock_family
;
1210 memcpy(addr
->sun_path
, path
, len
);
1211 #if defined(PYOS_OS2)
1212 *len_ret
= sizeof(*addr
);
1214 *len_ret
= len
+ offsetof(struct sockaddr_un
, sun_path
);
1218 #endif /* AF_UNIX */
1220 #if defined(AF_NETLINK)
1223 struct sockaddr_nl
* addr
;
1225 addr
= (struct sockaddr_nl
*)addr_ret
;
1226 if (!PyTuple_Check(args
)) {
1230 "AF_NETLINK address must be tuple, not %.500s",
1231 Py_TYPE(args
)->tp_name
);
1234 if (!PyArg_ParseTuple(args
, "II:getsockaddrarg", &pid
, &groups
))
1236 addr
->nl_family
= AF_NETLINK
;
1238 addr
->nl_groups
= groups
;
1239 *len_ret
= sizeof(*addr
);
1246 struct sockaddr_in
* addr
;
1249 if (!PyTuple_Check(args
)) {
1253 "AF_INET address must be tuple, not %.500s",
1254 Py_TYPE(args
)->tp_name
);
1257 if (!PyArg_ParseTuple(args
, "eti:getsockaddrarg",
1258 "idna", &host
, &port
))
1260 addr
=(struct sockaddr_in
*)addr_ret
;
1261 result
= setipaddr(host
, (struct sockaddr
*)addr
,
1262 sizeof(*addr
), AF_INET
);
1266 if (port
< 0 || port
> 0xffff) {
1268 PyExc_OverflowError
,
1269 "getsockaddrarg: port must be 0-65535.");
1272 addr
->sin_family
= AF_INET
;
1273 addr
->sin_port
= htons((short)port
);
1274 *len_ret
= sizeof *addr
;
1281 struct sockaddr_in6
* addr
;
1283 int port
, flowinfo
, scope_id
, result
;
1284 flowinfo
= scope_id
= 0;
1285 if (!PyTuple_Check(args
)) {
1289 "AF_INET6 address must be tuple, not %.500s",
1290 Py_TYPE(args
)->tp_name
);
1293 if (!PyArg_ParseTuple(args
, "eti|ii",
1294 "idna", &host
, &port
, &flowinfo
,
1298 addr
= (struct sockaddr_in6
*)addr_ret
;
1299 result
= setipaddr(host
, (struct sockaddr
*)addr
,
1300 sizeof(*addr
), AF_INET6
);
1304 if (port
< 0 || port
> 0xffff) {
1306 PyExc_OverflowError
,
1307 "getsockaddrarg: port must be 0-65535.");
1310 addr
->sin6_family
= s
->sock_family
;
1311 addr
->sin6_port
= htons((short)port
);
1312 addr
->sin6_flowinfo
= flowinfo
;
1313 addr
->sin6_scope_id
= scope_id
;
1314 *len_ret
= sizeof *addr
;
1319 #ifdef USE_BLUETOOTH
1322 switch (s
->sock_proto
) {
1325 struct sockaddr_l2
*addr
;
1328 addr
= (struct sockaddr_l2
*)addr_ret
;
1329 memset(addr
, 0, sizeof(struct sockaddr_l2
));
1330 _BT_L2_MEMB(addr
, family
) = AF_BLUETOOTH
;
1331 if (!PyArg_ParseTuple(args
, "si", &straddr
,
1332 &_BT_L2_MEMB(addr
, psm
))) {
1333 PyErr_SetString(socket_error
, "getsockaddrarg: "
1337 if (setbdaddr(straddr
, &_BT_L2_MEMB(addr
, bdaddr
)) < 0)
1340 *len_ret
= sizeof *addr
;
1343 case BTPROTO_RFCOMM
:
1345 struct sockaddr_rc
*addr
;
1348 addr
= (struct sockaddr_rc
*)addr_ret
;
1349 _BT_RC_MEMB(addr
, family
) = AF_BLUETOOTH
;
1350 if (!PyArg_ParseTuple(args
, "si", &straddr
,
1351 &_BT_RC_MEMB(addr
, channel
))) {
1352 PyErr_SetString(socket_error
, "getsockaddrarg: "
1356 if (setbdaddr(straddr
, &_BT_RC_MEMB(addr
, bdaddr
)) < 0)
1359 *len_ret
= sizeof *addr
;
1364 struct sockaddr_hci
*addr
= (struct sockaddr_hci
*)addr_ret
;
1365 _BT_HCI_MEMB(addr
, family
) = AF_BLUETOOTH
;
1366 if (!PyArg_ParseTuple(args
, "i", &_BT_HCI_MEMB(addr
, dev
))) {
1367 PyErr_SetString(socket_error
, "getsockaddrarg: "
1371 *len_ret
= sizeof *addr
;
1374 #if !defined(__FreeBSD__)
1377 struct sockaddr_sco
*addr
;
1380 addr
= (struct sockaddr_sco
*)addr_ret
;
1381 _BT_SCO_MEMB(addr
, family
) = AF_BLUETOOTH
;
1382 straddr
= PyString_AsString(args
);
1383 if (straddr
== NULL
) {
1384 PyErr_SetString(socket_error
, "getsockaddrarg: "
1388 if (setbdaddr(straddr
, &_BT_SCO_MEMB(addr
, bdaddr
)) < 0)
1391 *len_ret
= sizeof *addr
;
1396 PyErr_SetString(socket_error
, "getsockaddrarg: unknown Bluetooth protocol");
1402 #ifdef HAVE_NETPACKET_PACKET_H
1405 struct sockaddr_ll
* addr
;
1407 char *interfaceName
;
1412 unsigned int halen
= 0;
1414 if (!PyTuple_Check(args
)) {
1418 "AF_PACKET address must be tuple, not %.500s",
1419 Py_TYPE(args
)->tp_name
);
1422 if (!PyArg_ParseTuple(args
, "si|iis#", &interfaceName
,
1423 &protoNumber
, &pkttype
, &hatype
,
1426 strncpy(ifr
.ifr_name
, interfaceName
, sizeof(ifr
.ifr_name
));
1427 ifr
.ifr_name
[(sizeof(ifr
.ifr_name
))-1] = '\0';
1428 if (ioctl(s
->sock_fd
, SIOCGIFINDEX
, &ifr
) < 0) {
1433 PyErr_SetString(PyExc_ValueError
,
1434 "Hardware address must be 8 bytes or less");
1437 if (protoNumber
< 0 || protoNumber
> 0xffff) {
1439 PyExc_OverflowError
,
1440 "getsockaddrarg: protoNumber must be 0-65535.");
1443 addr
= (struct sockaddr_ll
*)addr_ret
;
1444 addr
->sll_family
= AF_PACKET
;
1445 addr
->sll_protocol
= htons((short)protoNumber
);
1446 addr
->sll_ifindex
= ifr
.ifr_ifindex
;
1447 addr
->sll_pkttype
= pkttype
;
1448 addr
->sll_hatype
= hatype
;
1450 memcpy(&addr
->sll_addr
, haddr
, halen
);
1452 addr
->sll_halen
= halen
;
1453 *len_ret
= sizeof *addr
;
1458 #ifdef HAVE_LINUX_TIPC_H
1461 unsigned int atype
, v1
, v2
, v3
;
1462 unsigned int scope
= TIPC_CLUSTER_SCOPE
;
1463 struct sockaddr_tipc
*addr
;
1465 if (!PyTuple_Check(args
)) {
1469 "AF_TIPC address must be tuple, not %.500s",
1470 Py_TYPE(args
)->tp_name
);
1474 if (!PyArg_ParseTuple(args
,
1475 "IIII|I;Invalid TIPC address format",
1476 &atype
, &v1
, &v2
, &v3
, &scope
))
1479 addr
= (struct sockaddr_tipc
*) addr_ret
;
1480 memset(addr
, 0, sizeof(struct sockaddr_tipc
));
1482 addr
->family
= AF_TIPC
;
1483 addr
->scope
= scope
;
1484 addr
->addrtype
= atype
;
1486 if (atype
== TIPC_ADDR_NAMESEQ
) {
1487 addr
->addr
.nameseq
.type
= v1
;
1488 addr
->addr
.nameseq
.lower
= v2
;
1489 addr
->addr
.nameseq
.upper
= v3
;
1490 } else if (atype
== TIPC_ADDR_NAME
) {
1491 addr
->addr
.name
.name
.type
= v1
;
1492 addr
->addr
.name
.name
.instance
= v2
;
1493 } else if (atype
== TIPC_ADDR_ID
) {
1494 addr
->addr
.id
.node
= v1
;
1495 addr
->addr
.id
.ref
= v2
;
1497 /* Shouldn't happen */
1498 PyErr_SetString(PyExc_TypeError
, "Invalid address type");
1502 *len_ret
= sizeof(*addr
);
1508 /* More cases here... */
1511 PyErr_SetString(socket_error
, "getsockaddrarg: bad family");
1518 /* Get the address length according to the socket object's address family.
1519 Return 1 if the family is known, 0 otherwise. The length is returned
1523 getsockaddrlen(PySocketSockObject
*s
, socklen_t
*len_ret
)
1525 switch (s
->sock_family
) {
1527 #if defined(AF_UNIX)
1530 *len_ret
= sizeof (struct sockaddr_un
);
1533 #endif /* AF_UNIX */
1534 #if defined(AF_NETLINK)
1537 *len_ret
= sizeof (struct sockaddr_nl
);
1544 *len_ret
= sizeof (struct sockaddr_in
);
1551 *len_ret
= sizeof (struct sockaddr_in6
);
1556 #ifdef USE_BLUETOOTH
1559 switch(s
->sock_proto
)
1563 *len_ret
= sizeof (struct sockaddr_l2
);
1565 case BTPROTO_RFCOMM
:
1566 *len_ret
= sizeof (struct sockaddr_rc
);
1569 *len_ret
= sizeof (struct sockaddr_hci
);
1571 #if !defined(__FreeBSD__)
1573 *len_ret
= sizeof (struct sockaddr_sco
);
1577 PyErr_SetString(socket_error
, "getsockaddrlen: "
1578 "unknown BT protocol");
1585 #ifdef HAVE_NETPACKET_PACKET_H
1588 *len_ret
= sizeof (struct sockaddr_ll
);
1593 #ifdef HAVE_LINUX_TIPC_H
1596 *len_ret
= sizeof (struct sockaddr_tipc
);
1601 /* More cases here... */
1604 PyErr_SetString(socket_error
, "getsockaddrlen: bad family");
1611 /* s.accept() method */
1614 sock_accept(PySocketSockObject
*s
)
1616 sock_addr_t addrbuf
;
1619 PyObject
*sock
= NULL
;
1620 PyObject
*addr
= NULL
;
1621 PyObject
*res
= NULL
;
1624 if (!getsockaddrlen(s
, &addrlen
))
1626 memset(&addrbuf
, 0, addrlen
);
1629 newfd
= INVALID_SOCKET
;
1634 if (!IS_SELECTABLE(s
))
1635 return select_error();
1637 Py_BEGIN_ALLOW_THREADS
1638 timeout
= internal_select(s
, 0);
1640 newfd
= accept(s
->sock_fd
, SAS2SA(&addrbuf
), &addrlen
);
1641 Py_END_ALLOW_THREADS
1644 PyErr_SetString(socket_timeout
, "timed out");
1649 if (newfd
== INVALID_SOCKET
)
1653 return s
->errorhandler();
1655 /* Create the new object with unspecified family,
1656 to avoid calls to bind() etc. on it. */
1657 sock
= (PyObject
*) new_sockobject(newfd
,
1666 addr
= makesockaddr(s
->sock_fd
, SAS2SA(&addrbuf
),
1667 addrlen
, s
->sock_proto
);
1671 res
= PyTuple_Pack(2, sock
, addr
);
1679 PyDoc_STRVAR(accept_doc
,
1680 "accept() -> (socket object, address info)\n\
1682 Wait for an incoming connection. Return a new socket representing the\n\
1683 connection, and the address of the client. For IP sockets, the address\n\
1684 info is a pair (hostaddr, port).");
1686 /* s.setblocking(flag) method. Argument:
1687 False -- non-blocking mode; same as settimeout(0)
1688 True -- blocking mode; same as settimeout(None)
1692 sock_setblocking(PySocketSockObject
*s
, PyObject
*arg
)
1696 block
= PyInt_AsLong(arg
);
1697 if (block
== -1 && PyErr_Occurred())
1700 s
->sock_timeout
= block
? -1.0 : 0.0;
1701 internal_setblocking(s
, block
);
1707 PyDoc_STRVAR(setblocking_doc
,
1708 "setblocking(flag)\n\
1710 Set the socket to blocking (flag is true) or non-blocking (false).\n\
1711 setblocking(True) is equivalent to settimeout(None);\n\
1712 setblocking(False) is equivalent to settimeout(0.0).");
1714 /* s.settimeout(timeout) method. Argument:
1715 None -- no timeout, blocking mode; same as setblocking(True)
1716 0.0 -- non-blocking mode; same as setblocking(False)
1717 > 0 -- timeout mode; operations time out after timeout seconds
1718 < 0 -- illegal; raises an exception
1721 sock_settimeout(PySocketSockObject
*s
, PyObject
*arg
)
1728 timeout
= PyFloat_AsDouble(arg
);
1729 if (timeout
< 0.0) {
1730 if (!PyErr_Occurred())
1731 PyErr_SetString(PyExc_ValueError
,
1732 "Timeout value out of range");
1737 s
->sock_timeout
= timeout
;
1738 internal_setblocking(s
, timeout
< 0.0);
1744 PyDoc_STRVAR(settimeout_doc
,
1745 "settimeout(timeout)\n\
1747 Set a timeout on socket operations. 'timeout' can be a float,\n\
1748 giving in seconds, or None. Setting a timeout of None disables\n\
1749 the timeout feature and is equivalent to setblocking(1).\n\
1750 Setting a timeout of zero is the same as setblocking(0).");
1752 /* s.gettimeout() method.
1753 Returns the timeout associated with a socket. */
1755 sock_gettimeout(PySocketSockObject
*s
)
1757 if (s
->sock_timeout
< 0.0) {
1762 return PyFloat_FromDouble(s
->sock_timeout
);
1765 PyDoc_STRVAR(gettimeout_doc
,
1766 "gettimeout() -> timeout\n\
1768 Returns the timeout in floating seconds associated with socket \n\
1769 operations. A timeout of None indicates that timeouts on socket \n\
1770 operations are disabled.");
1773 /* s.sleeptaskw(1 | 0) method */
1776 sock_sleeptaskw(PySocketSockObject
*s
,PyObject
*arg
)
1779 block
= PyInt_AsLong(arg
);
1780 if (block
== -1 && PyErr_Occurred())
1782 Py_BEGIN_ALLOW_THREADS
1783 socketioctl(s
->sock_fd
, 0x80046679, (u_long
*)&block
);
1784 Py_END_ALLOW_THREADS
1789 PyDoc_STRVAR(sleeptaskw_doc
,
1790 "sleeptaskw(flag)\n\
1792 Allow sleeps in taskwindows.");
1796 /* s.setsockopt() method.
1797 With an integer third argument, sets an integer option.
1798 With a string third argument, sets an option from a buffer;
1799 use optional built-in module 'struct' to encode the string. */
1802 sock_setsockopt(PySocketSockObject
*s
, PyObject
*args
)
1811 if (PyArg_ParseTuple(args
, "iii:setsockopt",
1812 &level
, &optname
, &flag
)) {
1813 buf
= (char *) &flag
;
1814 buflen
= sizeof flag
;
1818 if (!PyArg_ParseTuple(args
, "iis#:setsockopt",
1819 &level
, &optname
, &buf
, &buflen
))
1822 res
= setsockopt(s
->sock_fd
, level
, optname
, (void *)buf
, buflen
);
1824 return s
->errorhandler();
1829 PyDoc_STRVAR(setsockopt_doc
,
1830 "setsockopt(level, option, value)\n\
1832 Set a socket option. See the Unix manual for level and option.\n\
1833 The value argument can either be an integer or a string.");
1836 /* s.getsockopt() method.
1837 With two arguments, retrieves an integer option.
1838 With a third integer argument, retrieves a string buffer of that size;
1839 use optional built-in module 'struct' to decode the string. */
1842 sock_getsockopt(PySocketSockObject
*s
, PyObject
*args
)
1848 socklen_t buflen
= 0;
1851 /* We have incomplete socket support. */
1852 PyErr_SetString(socket_error
, "getsockopt not supported");
1856 if (!PyArg_ParseTuple(args
, "ii|i:getsockopt",
1857 &level
, &optname
, &buflen
))
1862 socklen_t flagsize
= sizeof flag
;
1863 res
= getsockopt(s
->sock_fd
, level
, optname
,
1864 (void *)&flag
, &flagsize
);
1866 return s
->errorhandler();
1867 return PyInt_FromLong(flag
);
1870 /* socklen_t is unsigned so no negative test is needed,
1871 test buflen == 0 is previously done */
1872 if (buflen
> 1024) {
1874 if (buflen
<= 0 || buflen
> 1024) {
1876 PyErr_SetString(socket_error
,
1877 "getsockopt buflen out of range");
1880 buf
= PyString_FromStringAndSize((char *)NULL
, buflen
);
1883 res
= getsockopt(s
->sock_fd
, level
, optname
,
1884 (void *)PyString_AS_STRING(buf
), &buflen
);
1887 return s
->errorhandler();
1889 _PyString_Resize(&buf
, buflen
);
1891 #endif /* __BEOS__ */
1894 PyDoc_STRVAR(getsockopt_doc
,
1895 "getsockopt(level, option[, buffersize]) -> value\n\
1897 Get a socket option. See the Unix manual for level and option.\n\
1898 If a nonzero buffersize argument is given, the return value is a\n\
1899 string of that length; otherwise it is an integer.");
1902 /* s.bind(sockaddr) method */
1905 sock_bind(PySocketSockObject
*s
, PyObject
*addro
)
1907 sock_addr_t addrbuf
;
1911 if (!getsockaddrarg(s
, addro
, SAS2SA(&addrbuf
), &addrlen
))
1913 Py_BEGIN_ALLOW_THREADS
1914 res
= bind(s
->sock_fd
, SAS2SA(&addrbuf
), addrlen
);
1915 Py_END_ALLOW_THREADS
1917 return s
->errorhandler();
1922 PyDoc_STRVAR(bind_doc
,
1925 Bind the socket to a local address. For IP sockets, the address is a\n\
1926 pair (host, port); the host must refer to the local host. For raw packet\n\
1927 sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");
1930 /* s.close() method.
1931 Set the file descriptor to -1 so operations tried subsequently
1932 will surely fail. */
1935 sock_close(PySocketSockObject
*s
)
1939 if ((fd
= s
->sock_fd
) != -1) {
1941 Py_BEGIN_ALLOW_THREADS
1942 (void) SOCKETCLOSE(fd
);
1943 Py_END_ALLOW_THREADS
1949 PyDoc_STRVAR(close_doc
,
1952 Close the socket. It cannot be used after this call.");
1955 internal_connect(PySocketSockObject
*s
, struct sockaddr
*addr
, int addrlen
,
1961 res
= connect(s
->sock_fd
, addr
, addrlen
);
1965 if (s
->sock_timeout
> 0.0) {
1966 if (res
< 0 && WSAGetLastError() == WSAEWOULDBLOCK
&&
1968 /* This is a mess. Best solution: trust select */
1972 tv
.tv_sec
= (int)s
->sock_timeout
;
1973 tv
.tv_usec
= (int)((s
->sock_timeout
- tv
.tv_sec
) * 1e6
);
1975 FD_SET(s
->sock_fd
, &fds
);
1977 FD_SET(s
->sock_fd
, &fds_exc
);
1978 res
= select(s
->sock_fd
+1, NULL
, &fds
, &fds_exc
, &tv
);
1980 res
= WSAEWOULDBLOCK
;
1982 } else if (res
> 0) {
1983 if (FD_ISSET(s
->sock_fd
, &fds
))
1984 /* The socket is in the writeable set - this
1988 /* As per MS docs, we need to call getsockopt()
1989 to get the underlying error */
1990 int res_size
= sizeof res
;
1991 /* It must be in the exception set */
1992 assert(FD_ISSET(s
->sock_fd
, &fds_exc
));
1993 if (0 == getsockopt(s
->sock_fd
, SOL_SOCKET
, SO_ERROR
,
1994 (char *)&res
, &res_size
))
1995 /* getsockopt also clears WSAGetLastError,
1996 so reset it back. */
1997 WSASetLastError(res
);
1999 res
= WSAGetLastError();
2002 /* else if (res < 0) an error occurred */
2007 res
= WSAGetLastError();
2011 if (s
->sock_timeout
> 0.0) {
2012 if (res
< 0 && errno
== EINPROGRESS
&& IS_SELECTABLE(s
)) {
2013 timeout
= internal_select(s
, 1);
2015 /* Bug #1019808: in case of an EINPROGRESS,
2016 use getsockopt(SO_ERROR) to get the real
2018 socklen_t res_size
= sizeof res
;
2019 (void)getsockopt(s
->sock_fd
, SOL_SOCKET
,
2020 SO_ERROR
, &res
, &res_size
);
2025 else if (timeout
== -1) {
2026 res
= errno
; /* had error */
2029 res
= EWOULDBLOCK
; /* timed out */
2037 *timeoutp
= timeout
;
2042 /* s.connect(sockaddr) method */
2045 sock_connect(PySocketSockObject
*s
, PyObject
*addro
)
2047 sock_addr_t addrbuf
;
2052 if (!getsockaddrarg(s
, addro
, SAS2SA(&addrbuf
), &addrlen
))
2055 Py_BEGIN_ALLOW_THREADS
2056 res
= internal_connect(s
, SAS2SA(&addrbuf
), addrlen
, &timeout
);
2057 Py_END_ALLOW_THREADS
2060 PyErr_SetString(socket_timeout
, "timed out");
2064 return s
->errorhandler();
2069 PyDoc_STRVAR(connect_doc
,
2070 "connect(address)\n\
2072 Connect the socket to a remote address. For IP sockets, the address\n\
2073 is a pair (host, port).");
2076 /* s.connect_ex(sockaddr) method */
2079 sock_connect_ex(PySocketSockObject
*s
, PyObject
*addro
)
2081 sock_addr_t addrbuf
;
2086 if (!getsockaddrarg(s
, addro
, SAS2SA(&addrbuf
), &addrlen
))
2089 Py_BEGIN_ALLOW_THREADS
2090 res
= internal_connect(s
, SAS2SA(&addrbuf
), addrlen
, &timeout
);
2091 Py_END_ALLOW_THREADS
2093 /* Signals are not errors (though they may raise exceptions). Adapted
2094 from PyErr_SetFromErrnoWithFilenameObject(). */
2096 if (res
== EINTR
&& PyErr_CheckSignals())
2100 return PyInt_FromLong((long) res
);
2103 PyDoc_STRVAR(connect_ex_doc
,
2104 "connect_ex(address) -> errno\n\
2106 This is like connect(address), but returns an error code (the errno value)\n\
2107 instead of raising an exception when an error occurs.");
2110 /* s.fileno() method */
2113 sock_fileno(PySocketSockObject
*s
)
2115 #if SIZEOF_SOCKET_T <= SIZEOF_LONG
2116 return PyInt_FromLong((long) s
->sock_fd
);
2118 return PyLong_FromLongLong((PY_LONG_LONG
)s
->sock_fd
);
2122 PyDoc_STRVAR(fileno_doc
,
2123 "fileno() -> integer\n\
2125 Return the integer file descriptor of the socket.");
2129 /* s.dup() method */
2132 sock_dup(PySocketSockObject
*s
)
2137 newfd
= dup(s
->sock_fd
);
2139 return s
->errorhandler();
2140 sock
= (PyObject
*) new_sockobject(newfd
,
2149 PyDoc_STRVAR(dup_doc
,
2150 "dup() -> socket object\n\
2152 Return a new socket object connected to the same system resource.");
2157 /* s.getsockname() method */
2160 sock_getsockname(PySocketSockObject
*s
)
2162 sock_addr_t addrbuf
;
2166 if (!getsockaddrlen(s
, &addrlen
))
2168 memset(&addrbuf
, 0, addrlen
);
2169 Py_BEGIN_ALLOW_THREADS
2170 res
= getsockname(s
->sock_fd
, SAS2SA(&addrbuf
), &addrlen
);
2171 Py_END_ALLOW_THREADS
2173 return s
->errorhandler();
2174 return makesockaddr(s
->sock_fd
, SAS2SA(&addrbuf
), addrlen
,
2178 PyDoc_STRVAR(getsockname_doc
,
2179 "getsockname() -> address info\n\
2181 Return the address of the local endpoint. For IP sockets, the address\n\
2182 info is a pair (hostaddr, port).");
2185 #ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
2186 /* s.getpeername() method */
2189 sock_getpeername(PySocketSockObject
*s
)
2191 sock_addr_t addrbuf
;
2195 if (!getsockaddrlen(s
, &addrlen
))
2197 memset(&addrbuf
, 0, addrlen
);
2198 Py_BEGIN_ALLOW_THREADS
2199 res
= getpeername(s
->sock_fd
, SAS2SA(&addrbuf
), &addrlen
);
2200 Py_END_ALLOW_THREADS
2202 return s
->errorhandler();
2203 return makesockaddr(s
->sock_fd
, SAS2SA(&addrbuf
), addrlen
,
2207 PyDoc_STRVAR(getpeername_doc
,
2208 "getpeername() -> address info\n\
2210 Return the address of the remote endpoint. For IP sockets, the address\n\
2211 info is a pair (hostaddr, port).");
2213 #endif /* HAVE_GETPEERNAME */
2216 /* s.listen(n) method */
2219 sock_listen(PySocketSockObject
*s
, PyObject
*arg
)
2224 backlog
= PyInt_AsLong(arg
);
2225 if (backlog
== -1 && PyErr_Occurred())
2227 Py_BEGIN_ALLOW_THREADS
2230 res
= listen(s
->sock_fd
, backlog
);
2231 Py_END_ALLOW_THREADS
2233 return s
->errorhandler();
2238 PyDoc_STRVAR(listen_doc
,
2241 Enable a server to accept connections. The backlog argument must be at\n\
2242 least 1; it specifies the number of unaccepted connection that the system\n\
2243 will allow before refusing new connections.");
2247 /* s.makefile(mode) method.
2248 Create a new open file object referring to a dupped version of
2249 the socket's file descriptor. (The dup() call is necessary so
2250 that the open file and socket objects may be closed independent
2252 The mode argument specifies 'r' or 'w' passed to fdopen(). */
2255 sock_makefile(PySocketSockObject
*s
, PyObject
*args
)
2257 extern int fclose(FILE *);
2272 if (!PyArg_ParseTuple(args
, "|si:makefile", &mode
, &bufsize
))
2275 if (strcmp(mode
,"rb") == 0) {
2279 if (strcmp(mode
,"wb") == 0) {
2285 if (((fd
= _open_osfhandle(s
->sock_fd
, _O_BINARY
)) < 0) ||
2286 ((fd
= dup(fd
)) < 0) || ((fp
= fdopen(fd
, mode
)) == NULL
))
2288 if ((fd
= dup(s
->sock_fd
)) < 0 || (fp
= fdopen(fd
, mode
)) == NULL
)
2293 return s
->errorhandler();
2295 f
= PyFile_FromFile(fp
, "<socket>", mode
, fclose
);
2297 PyFile_SetBufSize(f
, bufsize
);
2301 PyDoc_STRVAR(makefile_doc
,
2302 "makefile([mode[, buffersize]]) -> file object\n\
2304 Return a regular file object corresponding to the socket.\n\
2305 The mode and buffersize arguments are as for the built-in open() function.");
2310 * This is the guts of the recv() and recv_into() methods, which reads into a
2311 * char buffer. If you have any inc/dec ref to do to the objects that contain
2312 * the buffer, do it in the caller. This function returns the number of bytes
2313 * succesfully read. If there was an error, it returns -1. Note that it is
2314 * also possible that we return a number of bytes smaller than the request
2318 sock_recv_guts(PySocketSockObject
*s
, char* cbuf
, int len
, int flags
)
2320 ssize_t outlen
= -1;
2327 if (!IS_SELECTABLE(s
)) {
2333 Py_BEGIN_ALLOW_THREADS
2334 timeout
= internal_select(s
, 0);
2336 outlen
= recv(s
->sock_fd
, cbuf
, len
, flags
);
2337 Py_END_ALLOW_THREADS
2340 PyErr_SetString(socket_timeout
, "timed out");
2344 /* Note: the call to errorhandler() ALWAYS indirectly returned
2345 NULL, so ignore its return value */
2352 while (remaining
!= 0) {
2353 unsigned int segment
;
2356 segment
= remaining
/SEGMENT_SIZE
;
2358 segment
= SEGMENT_SIZE
;
2361 segment
= remaining
;
2364 Py_BEGIN_ALLOW_THREADS
2365 timeout
= internal_select(s
, 0);
2367 nread
= recv(s
->sock_fd
, read_buf
, segment
, flags
);
2368 Py_END_ALLOW_THREADS
2371 PyErr_SetString(socket_timeout
, "timed out");
2378 if (nread
!= remaining
) {
2383 remaining
-= segment
;
2384 read_buf
+= segment
;
2386 outlen
= read_buf
- cbuf
;
2393 /* s.recv(nbytes [,flags]) method */
2396 sock_recv(PySocketSockObject
*s
, PyObject
*args
)
2398 int recvlen
, flags
= 0;
2402 if (!PyArg_ParseTuple(args
, "i|i:recv", &recvlen
, &flags
))
2406 PyErr_SetString(PyExc_ValueError
,
2407 "negative buffersize in recv");
2411 /* Allocate a new string. */
2412 buf
= PyString_FromStringAndSize((char *) 0, recvlen
);
2417 outlen
= sock_recv_guts(s
, PyString_AS_STRING(buf
), recvlen
, flags
);
2419 /* An error occurred, release the string and return an
2424 if (outlen
!= recvlen
) {
2425 /* We did not read as many bytes as we anticipated, resize the
2426 string if possible and be succesful. */
2427 if (_PyString_Resize(&buf
, outlen
) < 0)
2428 /* Oopsy, not so succesful after all. */
2435 PyDoc_STRVAR(recv_doc
,
2436 "recv(buffersize[, flags]) -> data\n\
2438 Receive up to buffersize bytes from the socket. For the optional flags\n\
2439 argument, see the Unix manual. When no data is available, block until\n\
2440 at least one byte is available or until the remote end is closed. When\n\
2441 the remote end is closed and all data is read, return the empty string.");
2444 /* s.recv_into(buffer, [nbytes [,flags]]) method */
2447 sock_recv_into(PySocketSockObject
*s
, PyObject
*args
, PyObject
*kwds
)
2449 static char *kwlist
[] = {"buffer", "nbytes", "flags", 0};
2451 int recvlen
= 0, flags
= 0;
2456 /* Get the buffer's memory */
2457 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "w*|ii:recv_into", kwlist
,
2458 &buf
, &recvlen
, &flags
))
2461 assert(buf
.buf
!= 0 && buflen
> 0);
2464 PyErr_SetString(PyExc_ValueError
,
2465 "negative buffersize in recv_into");
2469 /* If nbytes was not specified, use the buffer's length */
2473 /* Check if the buffer is large enough */
2474 if (buflen
< recvlen
) {
2475 PyErr_SetString(PyExc_ValueError
,
2476 "buffer too small for requested bytes");
2481 readlen
= sock_recv_guts(s
, buf
.buf
, recvlen
, flags
);
2483 /* Return an error. */
2487 PyBuffer_Release(&buf
);
2488 /* Return the number of bytes read. Note that we do not do anything
2489 special here in the case that readlen < recvlen. */
2490 return PyInt_FromSsize_t(readlen
);
2493 PyBuffer_Release(&buf
);
2497 PyDoc_STRVAR(recv_into_doc
,
2498 "recv_into(buffer, [nbytes[, flags]]) -> nbytes_read\n\
2500 A version of recv() that stores its data into a buffer rather than creating \n\
2501 a new string. Receive up to buffersize bytes from the socket. If buffersize \n\
2502 is not specified (or 0), receive up to the size available in the given buffer.\n\
2504 See recv() for documentation about the flags.");
2508 * This is the guts of the recvfrom() and recvfrom_into() methods, which reads
2509 * into a char buffer. If you have any inc/def ref to do to the objects that
2510 * contain the buffer, do it in the caller. This function returns the number
2511 * of bytes succesfully read. If there was an error, it returns -1. Note
2512 * that it is also possible that we return a number of bytes smaller than the
2515 * 'addr' is a return value for the address object. Note that you must decref
2519 sock_recvfrom_guts(PySocketSockObject
*s
, char* cbuf
, int len
, int flags
,
2522 sock_addr_t addrbuf
;
2529 if (!getsockaddrlen(s
, &addrlen
))
2532 if (!IS_SELECTABLE(s
)) {
2537 Py_BEGIN_ALLOW_THREADS
2538 memset(&addrbuf
, 0, addrlen
);
2539 timeout
= internal_select(s
, 0);
2542 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
2543 n
= recvfrom(s
->sock_fd
, cbuf
, len
, flags
,
2544 SAS2SA(&addrbuf
), &addrlen
);
2546 n
= recvfrom(s
->sock_fd
, cbuf
, len
, flags
,
2547 (void *) &addrbuf
, &addrlen
);
2550 n
= recvfrom(s
->sock_fd
, cbuf
, len
, flags
,
2551 SAS2SA(&addrbuf
), &addrlen
);
2554 Py_END_ALLOW_THREADS
2557 PyErr_SetString(socket_timeout
, "timed out");
2565 if (!(*addr
= makesockaddr(s
->sock_fd
, SAS2SA(&addrbuf
),
2566 addrlen
, s
->sock_proto
)))
2572 /* s.recvfrom(nbytes [,flags]) method */
2575 sock_recvfrom(PySocketSockObject
*s
, PyObject
*args
)
2577 PyObject
*buf
= NULL
;
2578 PyObject
*addr
= NULL
;
2579 PyObject
*ret
= NULL
;
2580 int recvlen
, flags
= 0;
2583 if (!PyArg_ParseTuple(args
, "i|i:recvfrom", &recvlen
, &flags
))
2587 PyErr_SetString(PyExc_ValueError
,
2588 "negative buffersize in recvfrom");
2592 buf
= PyString_FromStringAndSize((char *) 0, recvlen
);
2596 outlen
= sock_recvfrom_guts(s
, PyString_AS_STRING(buf
),
2597 recvlen
, flags
, &addr
);
2602 if (outlen
!= recvlen
) {
2603 /* We did not read as many bytes as we anticipated, resize the
2604 string if possible and be succesful. */
2605 if (_PyString_Resize(&buf
, outlen
) < 0)
2606 /* Oopsy, not so succesful after all. */
2610 ret
= PyTuple_Pack(2, buf
, addr
);
2618 PyDoc_STRVAR(recvfrom_doc
,
2619 "recvfrom(buffersize[, flags]) -> (data, address info)\n\
2621 Like recv(buffersize, flags) but also return the sender's address info.");
2624 /* s.recvfrom_into(buffer[, nbytes [,flags]]) method */
2627 sock_recvfrom_into(PySocketSockObject
*s
, PyObject
*args
, PyObject
* kwds
)
2629 static char *kwlist
[] = {"buffer", "nbytes", "flags", 0};
2631 int recvlen
= 0, flags
= 0;
2636 PyObject
*addr
= NULL
;
2638 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "w*|ii:recvfrom_into",
2643 assert(buf
.buf
!= 0 && buflen
> 0);
2646 PyErr_SetString(PyExc_ValueError
,
2647 "negative buffersize in recvfrom_into");
2651 /* If nbytes was not specified, use the buffer's length */
2655 readlen
= sock_recvfrom_guts(s
, buf
.buf
, recvlen
, flags
, &addr
);
2657 /* Return an error */
2661 PyBuffer_Release(&buf
);
2662 /* Return the number of bytes read and the address. Note that we do
2663 not do anything special here in the case that readlen < recvlen. */
2664 return Py_BuildValue("lN", readlen
, addr
);
2668 PyBuffer_Release(&buf
);
2672 PyDoc_STRVAR(recvfrom_into_doc
,
2673 "recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)\n\
2675 Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.");
2678 /* s.send(data [,flags]) method */
2681 sock_send(PySocketSockObject
*s
, PyObject
*args
)
2684 int len
, n
= -1, flags
= 0, timeout
;
2687 if (!PyArg_ParseTuple(args
, "s*|i:send", &pbuf
, &flags
))
2690 if (!IS_SELECTABLE(s
)) {
2691 PyBuffer_Release(&pbuf
);
2692 return select_error();
2697 Py_BEGIN_ALLOW_THREADS
2698 timeout
= internal_select(s
, 1);
2701 n
= sendsegmented(s
->sock_fd
, buf
, len
, flags
);
2703 n
= send(s
->sock_fd
, buf
, len
, flags
);
2705 Py_END_ALLOW_THREADS
2707 PyBuffer_Release(&pbuf
);
2710 PyErr_SetString(socket_timeout
, "timed out");
2714 return s
->errorhandler();
2715 return PyInt_FromLong((long)n
);
2718 PyDoc_STRVAR(send_doc
,
2719 "send(data[, flags]) -> count\n\
2721 Send a data string to the socket. For the optional flags\n\
2722 argument, see the Unix manual. Return the number of bytes\n\
2723 sent; this may be less than len(data) if the network is busy.");
2726 /* s.sendall(data [,flags]) method */
2729 sock_sendall(PySocketSockObject
*s
, PyObject
*args
)
2732 int len
, n
= -1, flags
= 0, timeout
;
2735 if (!PyArg_ParseTuple(args
, "s*|i:sendall", &pbuf
, &flags
))
2740 if (!IS_SELECTABLE(s
)) {
2741 PyBuffer_Release(&pbuf
);
2742 return select_error();
2745 Py_BEGIN_ALLOW_THREADS
2747 timeout
= internal_select(s
, 1);
2752 n
= sendsegmented(s
->sock_fd
, buf
, len
, flags
);
2754 n
= send(s
->sock_fd
, buf
, len
, flags
);
2758 /* We must handle EINTR here as there is no way for
2759 * the caller to know how much was sent otherwise. */
2760 if (errno
== EINTR
) {
2761 /* Run signal handlers. If an exception was
2762 * raised, abort and leave this socket in
2763 * an unknown state. */
2764 if (PyErr_CheckSignals())
2774 Py_END_ALLOW_THREADS
2775 PyBuffer_Release(&pbuf
);
2778 PyErr_SetString(socket_timeout
, "timed out");
2782 return s
->errorhandler();
2788 PyDoc_STRVAR(sendall_doc
,
2789 "sendall(data[, flags])\n\
2791 Send a data string to the socket. For the optional flags\n\
2792 argument, see the Unix manual. This calls send() repeatedly\n\
2793 until all data is sent. If an error occurs, it's impossible\n\
2794 to tell how much data has been sent.");
2797 /* s.sendto(data, [flags,] sockaddr) method */
2800 sock_sendto(PySocketSockObject
*s
, PyObject
*args
)
2806 sock_addr_t addrbuf
;
2807 int addrlen
, n
= -1, flags
, timeout
;
2810 if (!PyArg_ParseTuple(args
, "s*O:sendto", &pbuf
, &addro
)) {
2812 if (!PyArg_ParseTuple(args
, "s*iO:sendto",
2813 &pbuf
, &flags
, &addro
))
2819 if (!IS_SELECTABLE(s
)) {
2820 PyBuffer_Release(&pbuf
);
2821 return select_error();
2824 if (!getsockaddrarg(s
, addro
, SAS2SA(&addrbuf
), &addrlen
)) {
2825 PyBuffer_Release(&pbuf
);
2829 Py_BEGIN_ALLOW_THREADS
2830 timeout
= internal_select(s
, 1);
2832 n
= sendto(s
->sock_fd
, buf
, len
, flags
, SAS2SA(&addrbuf
), addrlen
);
2833 Py_END_ALLOW_THREADS
2835 PyBuffer_Release(&pbuf
);
2837 PyErr_SetString(socket_timeout
, "timed out");
2841 return s
->errorhandler();
2842 return PyInt_FromLong((long)n
);
2845 PyDoc_STRVAR(sendto_doc
,
2846 "sendto(data[, flags], address) -> count\n\
2848 Like send(data, flags) but allows specifying the destination address.\n\
2849 For IP sockets, the address is a pair (hostaddr, port).");
2852 /* s.shutdown(how) method */
2855 sock_shutdown(PySocketSockObject
*s
, PyObject
*arg
)
2860 how
= PyInt_AsLong(arg
);
2861 if (how
== -1 && PyErr_Occurred())
2863 Py_BEGIN_ALLOW_THREADS
2864 res
= shutdown(s
->sock_fd
, how
);
2865 Py_END_ALLOW_THREADS
2867 return s
->errorhandler();
2872 PyDoc_STRVAR(shutdown_doc
,
2875 Shut down the reading side of the socket (flag == SHUT_RD), the writing side\n\
2876 of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).");
2878 #if defined(MS_WINDOWS) && defined(SIO_RCVALL)
2880 sock_ioctl(PySocketSockObject
*s
, PyObject
*arg
)
2882 unsigned long cmd
= SIO_RCVALL
;
2886 if (!PyArg_ParseTuple(arg
, "kO:ioctl", &cmd
, &argO
))
2891 unsigned int option
= RCVALL_ON
;
2892 if (!PyArg_ParseTuple(arg
, "kI:ioctl", &cmd
, &option
))
2894 if (WSAIoctl(s
->sock_fd
, cmd
, &option
, sizeof(option
),
2895 NULL
, 0, &recv
, NULL
, NULL
) == SOCKET_ERROR
) {
2898 return PyLong_FromUnsignedLong(recv
); }
2899 case SIO_KEEPALIVE_VALS
: {
2900 struct tcp_keepalive ka
;
2901 if (!PyArg_ParseTuple(arg
, "k(kkk):ioctl", &cmd
,
2902 &ka
.onoff
, &ka
.keepalivetime
, &ka
.keepaliveinterval
))
2904 if (WSAIoctl(s
->sock_fd
, cmd
, &ka
, sizeof(ka
),
2905 NULL
, 0, &recv
, NULL
, NULL
) == SOCKET_ERROR
) {
2908 return PyLong_FromUnsignedLong(recv
); }
2910 PyErr_Format(PyExc_ValueError
, "invalid ioctl command %d", cmd
);
2914 PyDoc_STRVAR(sock_ioctl_doc
,
2915 "ioctl(cmd, option) -> long\n\
2917 Control the socket with WSAIoctl syscall. Currently supported 'cmd' values are\n\
2918 SIO_RCVALL: 'option' must be one of the socket.RCVALL_* constants.\n\
2919 SIO_KEEPALIVE_VALS: 'option' is a tuple of (onoff, timeout, interval).");
2923 /* List of methods for socket objects */
2925 static PyMethodDef sock_methods
[] = {
2926 {"accept", (PyCFunction
)sock_accept
, METH_NOARGS
,
2928 {"bind", (PyCFunction
)sock_bind
, METH_O
,
2930 {"close", (PyCFunction
)sock_close
, METH_NOARGS
,
2932 {"connect", (PyCFunction
)sock_connect
, METH_O
,
2934 {"connect_ex", (PyCFunction
)sock_connect_ex
, METH_O
,
2937 {"dup", (PyCFunction
)sock_dup
, METH_NOARGS
,
2940 {"fileno", (PyCFunction
)sock_fileno
, METH_NOARGS
,
2942 #ifdef HAVE_GETPEERNAME
2943 {"getpeername", (PyCFunction
)sock_getpeername
,
2944 METH_NOARGS
, getpeername_doc
},
2946 {"getsockname", (PyCFunction
)sock_getsockname
,
2947 METH_NOARGS
, getsockname_doc
},
2948 {"getsockopt", (PyCFunction
)sock_getsockopt
, METH_VARARGS
,
2950 #if defined(MS_WINDOWS) && defined(SIO_RCVALL)
2951 {"ioctl", (PyCFunction
)sock_ioctl
, METH_VARARGS
,
2954 {"listen", (PyCFunction
)sock_listen
, METH_O
,
2957 {"makefile", (PyCFunction
)sock_makefile
, METH_VARARGS
,
2960 {"recv", (PyCFunction
)sock_recv
, METH_VARARGS
,
2962 {"recv_into", (PyCFunction
)sock_recv_into
, METH_VARARGS
| METH_KEYWORDS
,
2964 {"recvfrom", (PyCFunction
)sock_recvfrom
, METH_VARARGS
,
2966 {"recvfrom_into", (PyCFunction
)sock_recvfrom_into
, METH_VARARGS
| METH_KEYWORDS
,
2968 {"send", (PyCFunction
)sock_send
, METH_VARARGS
,
2970 {"sendall", (PyCFunction
)sock_sendall
, METH_VARARGS
,
2972 {"sendto", (PyCFunction
)sock_sendto
, METH_VARARGS
,
2974 {"setblocking", (PyCFunction
)sock_setblocking
, METH_O
,
2976 {"settimeout", (PyCFunction
)sock_settimeout
, METH_O
,
2978 {"gettimeout", (PyCFunction
)sock_gettimeout
, METH_NOARGS
,
2980 {"setsockopt", (PyCFunction
)sock_setsockopt
, METH_VARARGS
,
2982 {"shutdown", (PyCFunction
)sock_shutdown
, METH_O
,
2985 {"sleeptaskw", (PyCFunction
)sock_sleeptaskw
, METH_O
,
2988 {NULL
, NULL
} /* sentinel */
2991 /* SockObject members */
2992 static PyMemberDef sock_memberlist
[] = {
2993 {"family", T_INT
, offsetof(PySocketSockObject
, sock_family
), READONLY
, "the socket family"},
2994 {"type", T_INT
, offsetof(PySocketSockObject
, sock_type
), READONLY
, "the socket type"},
2995 {"proto", T_INT
, offsetof(PySocketSockObject
, sock_proto
), READONLY
, "the socket protocol"},
2996 {"timeout", T_DOUBLE
, offsetof(PySocketSockObject
, sock_timeout
), READONLY
, "the socket timeout"},
3000 /* Deallocate a socket object in response to the last Py_DECREF().
3001 First close the file description. */
3004 sock_dealloc(PySocketSockObject
*s
)
3006 if (s
->sock_fd
!= -1)
3007 (void) SOCKETCLOSE(s
->sock_fd
);
3008 Py_TYPE(s
)->tp_free((PyObject
*)s
);
3013 sock_repr(PySocketSockObject
*s
)
3016 #if SIZEOF_SOCKET_T > SIZEOF_LONG
3017 if (s
->sock_fd
> LONG_MAX
) {
3018 /* this can occur on Win64, and actually there is a special
3019 ugly printf formatter for decimal pointer length integer
3020 printing, only bother if necessary*/
3021 PyErr_SetString(PyExc_OverflowError
,
3022 "no printf formatter to display "
3023 "the socket descriptor in decimal");
3029 "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
3030 (long)s
->sock_fd
, s
->sock_family
,
3033 return PyString_FromString(buf
);
3037 /* Create a new, uninitialized socket object. */
3040 sock_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
3044 new = type
->tp_alloc(type
, 0);
3046 ((PySocketSockObject
*)new)->sock_fd
= -1;
3047 ((PySocketSockObject
*)new)->sock_timeout
= -1.0;
3048 ((PySocketSockObject
*)new)->errorhandler
= &set_error
;
3054 /* Initialize a new socket object. */
3058 sock_initobj(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
3060 PySocketSockObject
*s
= (PySocketSockObject
*)self
;
3062 int family
= AF_INET
, type
= SOCK_STREAM
, proto
= 0;
3063 static char *keywords
[] = {"family", "type", "proto", 0};
3065 if (!PyArg_ParseTupleAndKeywords(args
, kwds
,
3066 "|iii:socket", keywords
,
3067 &family
, &type
, &proto
))
3070 Py_BEGIN_ALLOW_THREADS
3071 fd
= socket(family
, type
, proto
);
3072 Py_END_ALLOW_THREADS
3075 if (fd
== INVALID_SOCKET
)
3083 init_sockobject(s
, fd
, family
, type
, proto
);
3090 /* Type object for socket objects. */
3092 static PyTypeObject sock_type
= {
3093 PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */
3094 "_socket.socket", /* tp_name */
3095 sizeof(PySocketSockObject
), /* tp_basicsize */
3096 0, /* tp_itemsize */
3097 (destructor
)sock_dealloc
, /* tp_dealloc */
3102 (reprfunc
)sock_repr
, /* tp_repr */
3103 0, /* tp_as_number */
3104 0, /* tp_as_sequence */
3105 0, /* tp_as_mapping */
3109 PyObject_GenericGetAttr
, /* tp_getattro */
3110 0, /* tp_setattro */
3111 0, /* tp_as_buffer */
3112 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
3113 sock_doc
, /* tp_doc */
3114 0, /* tp_traverse */
3116 0, /* tp_richcompare */
3117 0, /* tp_weaklistoffset */
3119 0, /* tp_iternext */
3120 sock_methods
, /* tp_methods */
3121 sock_memberlist
, /* tp_members */
3125 0, /* tp_descr_get */
3126 0, /* tp_descr_set */
3127 0, /* tp_dictoffset */
3128 sock_initobj
, /* tp_init */
3129 PyType_GenericAlloc
, /* tp_alloc */
3130 sock_new
, /* tp_new */
3131 PyObject_Del
, /* tp_free */
3135 /* Python interface to gethostname(). */
3139 socket_gethostname(PyObject
*self
, PyObject
*unused
)
3143 Py_BEGIN_ALLOW_THREADS
3144 res
= gethostname(buf
, (int) sizeof buf
- 1);
3145 Py_END_ALLOW_THREADS
3148 buf
[sizeof buf
- 1] = '\0';
3149 return PyString_FromString(buf
);
3152 PyDoc_STRVAR(gethostname_doc
,
3153 "gethostname() -> string\n\
3155 Return the current host name.");
3158 /* Python interface to gethostbyname(name). */
3162 socket_gethostbyname(PyObject
*self
, PyObject
*args
)
3165 sock_addr_t addrbuf
;
3167 if (!PyArg_ParseTuple(args
, "s:gethostbyname", &name
))
3169 if (setipaddr(name
, SAS2SA(&addrbuf
), sizeof(addrbuf
), AF_INET
) < 0)
3171 return makeipaddr(SAS2SA(&addrbuf
), sizeof(struct sockaddr_in
));
3174 PyDoc_STRVAR(gethostbyname_doc
,
3175 "gethostbyname(host) -> address\n\
3177 Return the IP address (a string of the form '255.255.255.255') for a host.");
3180 /* Convenience function common to gethostbyname_ex and gethostbyaddr */
3183 gethost_common(struct hostent
*h
, struct sockaddr
*addr
, int alen
, int af
)
3186 PyObject
*rtn_tuple
= (PyObject
*)NULL
;
3187 PyObject
*name_list
= (PyObject
*)NULL
;
3188 PyObject
*addr_list
= (PyObject
*)NULL
;
3192 /* Let's get real error message to return */
3194 set_herror(h_errno
);
3196 PyErr_SetString(socket_error
, "host not found");
3201 if (h
->h_addrtype
!= af
) {
3202 /* Let's get real error message to return */
3203 PyErr_SetString(socket_error
,
3204 (char *)strerror(EAFNOSUPPORT
));
3212 if (alen
< sizeof(struct sockaddr_in
))
3218 if (alen
< sizeof(struct sockaddr_in6
))
3225 if ((name_list
= PyList_New(0)) == NULL
)
3228 if ((addr_list
= PyList_New(0)) == NULL
)
3231 /* SF #1511317: h_aliases can be NULL */
3233 for (pch
= h
->h_aliases
; *pch
!= NULL
; pch
++) {
3235 tmp
= PyString_FromString(*pch
);
3239 status
= PyList_Append(name_list
, tmp
);
3247 for (pch
= h
->h_addr_list
; *pch
!= NULL
; pch
++) {
3254 struct sockaddr_in sin
;
3255 memset(&sin
, 0, sizeof(sin
));
3256 sin
.sin_family
= af
;
3257 #ifdef HAVE_SOCKADDR_SA_LEN
3258 sin
.sin_len
= sizeof(sin
);
3260 memcpy(&sin
.sin_addr
, *pch
, sizeof(sin
.sin_addr
));
3261 tmp
= makeipaddr((struct sockaddr
*)&sin
, sizeof(sin
));
3263 if (pch
== h
->h_addr_list
&& alen
>= sizeof(sin
))
3264 memcpy((char *) addr
, &sin
, sizeof(sin
));
3271 struct sockaddr_in6 sin6
;
3272 memset(&sin6
, 0, sizeof(sin6
));
3273 sin6
.sin6_family
= af
;
3274 #ifdef HAVE_SOCKADDR_SA_LEN
3275 sin6
.sin6_len
= sizeof(sin6
);
3277 memcpy(&sin6
.sin6_addr
, *pch
, sizeof(sin6
.sin6_addr
));
3278 tmp
= makeipaddr((struct sockaddr
*)&sin6
,
3281 if (pch
== h
->h_addr_list
&& alen
>= sizeof(sin6
))
3282 memcpy((char *) addr
, &sin6
, sizeof(sin6
));
3287 default: /* can't happen */
3288 PyErr_SetString(socket_error
,
3289 "unsupported address family");
3296 status
= PyList_Append(addr_list
, tmp
);
3303 rtn_tuple
= Py_BuildValue("sOO", h
->h_name
, name_list
, addr_list
);
3306 Py_XDECREF(name_list
);
3307 Py_XDECREF(addr_list
);
3312 /* Python interface to gethostbyname_ex(name). */
3316 socket_gethostbyname_ex(PyObject
*self
, PyObject
*args
)
3321 struct sockaddr_storage addr
;
3323 struct sockaddr_in addr
;
3325 struct sockaddr
*sa
;
3327 #ifdef HAVE_GETHOSTBYNAME_R
3328 struct hostent hp_allocated
;
3329 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
3330 struct hostent_data data
;
3333 int buf_len
= (sizeof buf
) - 1;
3336 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3339 #endif /* HAVE_GETHOSTBYNAME_R */
3341 if (!PyArg_ParseTuple(args
, "s:gethostbyname_ex", &name
))
3343 if (setipaddr(name
, (struct sockaddr
*)&addr
, sizeof(addr
), AF_INET
) < 0)
3345 Py_BEGIN_ALLOW_THREADS
3346 #ifdef HAVE_GETHOSTBYNAME_R
3347 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3348 result
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
,
3350 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
3351 h
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
, &errnop
);
3352 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
3353 memset((void *) &data
, '\0', sizeof(data
));
3354 result
= gethostbyname_r(name
, &hp_allocated
, &data
);
3355 h
= (result
!= 0) ? NULL
: &hp_allocated
;
3357 #else /* not HAVE_GETHOSTBYNAME_R */
3358 #ifdef USE_GETHOSTBYNAME_LOCK
3359 PyThread_acquire_lock(netdb_lock
, 1);
3361 h
= gethostbyname(name
);
3362 #endif /* HAVE_GETHOSTBYNAME_R */
3363 Py_END_ALLOW_THREADS
3364 /* Some C libraries would require addr.__ss_family instead of
3366 Therefore, we cast the sockaddr_storage into sockaddr to
3367 access sa_family. */
3368 sa
= (struct sockaddr
*)&addr
;
3369 ret
= gethost_common(h
, (struct sockaddr
*)&addr
, sizeof(addr
),
3371 #ifdef USE_GETHOSTBYNAME_LOCK
3372 PyThread_release_lock(netdb_lock
);
3377 PyDoc_STRVAR(ghbn_ex_doc
,
3378 "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
3380 Return the true host name, a list of aliases, and a list of IP addresses,\n\
3381 for a host. The host argument is a string giving a host name or IP number.");
3384 /* Python interface to gethostbyaddr(IP). */
3388 socket_gethostbyaddr(PyObject
*self
, PyObject
*args
)
3391 struct sockaddr_storage addr
;
3393 struct sockaddr_in addr
;
3395 struct sockaddr
*sa
= (struct sockaddr
*)&addr
;
3399 #ifdef HAVE_GETHOSTBYNAME_R
3400 struct hostent hp_allocated
;
3401 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
3402 struct hostent_data data
;
3404 /* glibcs up to 2.10 assume that the buf argument to
3405 gethostbyaddr_r is 8-byte aligned, which at least llvm-gcc
3406 does not ensure. The attribute below instructs the compiler
3407 to maintain this alignment. */
3408 char buf
[16384] Py_ALIGNED(8);
3409 int buf_len
= (sizeof buf
) - 1;
3412 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3415 #endif /* HAVE_GETHOSTBYNAME_R */
3420 if (!PyArg_ParseTuple(args
, "s:gethostbyaddr", &ip_num
))
3423 if (setipaddr(ip_num
, sa
, sizeof(addr
), af
) < 0)
3429 ap
= (char *)&((struct sockaddr_in
*)sa
)->sin_addr
;
3430 al
= sizeof(((struct sockaddr_in
*)sa
)->sin_addr
);
3434 ap
= (char *)&((struct sockaddr_in6
*)sa
)->sin6_addr
;
3435 al
= sizeof(((struct sockaddr_in6
*)sa
)->sin6_addr
);
3439 PyErr_SetString(socket_error
, "unsupported address family");
3442 Py_BEGIN_ALLOW_THREADS
3443 #ifdef HAVE_GETHOSTBYNAME_R
3444 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3445 result
= gethostbyaddr_r(ap
, al
, af
,
3446 &hp_allocated
, buf
, buf_len
,
3448 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
3449 h
= gethostbyaddr_r(ap
, al
, af
,
3450 &hp_allocated
, buf
, buf_len
, &errnop
);
3451 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
3452 memset((void *) &data
, '\0', sizeof(data
));
3453 result
= gethostbyaddr_r(ap
, al
, af
, &hp_allocated
, &data
);
3454 h
= (result
!= 0) ? NULL
: &hp_allocated
;
3456 #else /* not HAVE_GETHOSTBYNAME_R */
3457 #ifdef USE_GETHOSTBYNAME_LOCK
3458 PyThread_acquire_lock(netdb_lock
, 1);
3460 h
= gethostbyaddr(ap
, al
, af
);
3461 #endif /* HAVE_GETHOSTBYNAME_R */
3462 Py_END_ALLOW_THREADS
3463 ret
= gethost_common(h
, (struct sockaddr
*)&addr
, sizeof(addr
), af
);
3464 #ifdef USE_GETHOSTBYNAME_LOCK
3465 PyThread_release_lock(netdb_lock
);
3470 PyDoc_STRVAR(gethostbyaddr_doc
,
3471 "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
3473 Return the true host name, a list of aliases, and a list of IP addresses,\n\
3474 for a host. The host argument is a string giving a host name or IP number.");
3477 /* Python interface to getservbyname(name).
3478 This only returns the port number, since the other info is already
3479 known or not useful (like the list of aliases). */
3483 socket_getservbyname(PyObject
*self
, PyObject
*args
)
3485 char *name
, *proto
=NULL
;
3487 if (!PyArg_ParseTuple(args
, "s|s:getservbyname", &name
, &proto
))
3489 Py_BEGIN_ALLOW_THREADS
3490 sp
= getservbyname(name
, proto
);
3491 Py_END_ALLOW_THREADS
3493 PyErr_SetString(socket_error
, "service/proto not found");
3496 return PyInt_FromLong((long) ntohs(sp
->s_port
));
3499 PyDoc_STRVAR(getservbyname_doc
,
3500 "getservbyname(servicename[, protocolname]) -> integer\n\
3502 Return a port number from a service name and protocol name.\n\
3503 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3504 otherwise any protocol will match.");
3507 /* Python interface to getservbyport(port).
3508 This only returns the service name, since the other info is already
3509 known or not useful (like the list of aliases). */
3513 socket_getservbyport(PyObject
*self
, PyObject
*args
)
3518 if (!PyArg_ParseTuple(args
, "i|s:getservbyport", &port
, &proto
))
3520 if (port
< 0 || port
> 0xffff) {
3522 PyExc_OverflowError
,
3523 "getservbyport: port must be 0-65535.");
3526 Py_BEGIN_ALLOW_THREADS
3527 sp
= getservbyport(htons((short)port
), proto
);
3528 Py_END_ALLOW_THREADS
3530 PyErr_SetString(socket_error
, "port/proto not found");
3533 return PyString_FromString(sp
->s_name
);
3536 PyDoc_STRVAR(getservbyport_doc
,
3537 "getservbyport(port[, protocolname]) -> string\n\
3539 Return the service name from a port number and protocol name.\n\
3540 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3541 otherwise any protocol will match.");
3543 /* Python interface to getprotobyname(name).
3544 This only returns the protocol number, since the other info is
3545 already known or not useful (like the list of aliases). */
3549 socket_getprotobyname(PyObject
*self
, PyObject
*args
)
3552 struct protoent
*sp
;
3554 /* Not available in BeOS yet. - [cjh] */
3555 PyErr_SetString(socket_error
, "getprotobyname not supported");
3558 if (!PyArg_ParseTuple(args
, "s:getprotobyname", &name
))
3560 Py_BEGIN_ALLOW_THREADS
3561 sp
= getprotobyname(name
);
3562 Py_END_ALLOW_THREADS
3564 PyErr_SetString(socket_error
, "protocol not found");
3567 return PyInt_FromLong((long) sp
->p_proto
);
3571 PyDoc_STRVAR(getprotobyname_doc
,
3572 "getprotobyname(name) -> integer\n\
3574 Return the protocol number for the named protocol. (Rarely used.)");
3577 #ifdef HAVE_SOCKETPAIR
3578 /* Create a pair of sockets using the socketpair() function.
3579 Arguments as for socket() except the default family is AF_UNIX if
3580 defined on the platform; otherwise, the default is AF_INET. */
3584 socket_socketpair(PyObject
*self
, PyObject
*args
)
3586 PySocketSockObject
*s0
= NULL
, *s1
= NULL
;
3588 int family
, type
= SOCK_STREAM
, proto
= 0;
3589 PyObject
*res
= NULL
;
3591 #if defined(AF_UNIX)
3596 if (!PyArg_ParseTuple(args
, "|iii:socketpair",
3597 &family
, &type
, &proto
))
3599 /* Create a pair of socket fds */
3600 if (socketpair(family
, type
, proto
, sv
) < 0)
3602 s0
= new_sockobject(sv
[0], family
, type
, proto
);
3605 s1
= new_sockobject(sv
[1], family
, type
, proto
);
3608 res
= PyTuple_Pack(2, s0
, s1
);
3622 PyDoc_STRVAR(socketpair_doc
,
3623 "socketpair([family[, type[, proto]]]) -> (socket object, socket object)\n\
3625 Create a pair of socket objects from the sockets returned by the platform\n\
3626 socketpair() function.\n\
3627 The arguments are the same as for socket() except the default family is\n\
3628 AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");
3630 #endif /* HAVE_SOCKETPAIR */
3634 /* Create a socket object from a numeric file description.
3635 Useful e.g. if stdin is a socket.
3636 Additional arguments as for socket(). */
3640 socket_fromfd(PyObject
*self
, PyObject
*args
)
3642 PySocketSockObject
*s
;
3644 int family
, type
, proto
= 0;
3645 if (!PyArg_ParseTuple(args
, "iii|i:fromfd",
3646 &fd
, &family
, &type
, &proto
))
3648 /* Dup the fd so it and the socket can be closed independently */
3652 s
= new_sockobject(fd
, family
, type
, proto
);
3653 return (PyObject
*) s
;
3656 PyDoc_STRVAR(fromfd_doc
,
3657 "fromfd(fd, family, type[, proto]) -> socket object\n\
3659 Create a socket object from a duplicate of the given\n\
3661 The remaining arguments are the same as for socket().");
3667 socket_ntohs(PyObject
*self
, PyObject
*args
)
3671 if (!PyArg_ParseTuple(args
, "i:ntohs", &x1
)) {
3675 PyErr_SetString(PyExc_OverflowError
,
3676 "can't convert negative number to unsigned long");
3679 x2
= (unsigned int)ntohs((unsigned short)x1
);
3680 return PyInt_FromLong(x2
);
3683 PyDoc_STRVAR(ntohs_doc
,
3684 "ntohs(integer) -> integer\n\
3686 Convert a 16-bit integer from network to host byte order.");
3690 socket_ntohl(PyObject
*self
, PyObject
*arg
)
3694 if (PyInt_Check(arg
)) {
3695 x
= PyInt_AS_LONG(arg
);
3696 if (x
== (unsigned long) -1 && PyErr_Occurred())
3699 PyErr_SetString(PyExc_OverflowError
,
3700 "can't convert negative number to unsigned long");
3704 else if (PyLong_Check(arg
)) {
3705 x
= PyLong_AsUnsignedLong(arg
);
3706 if (x
== (unsigned long) -1 && PyErr_Occurred())
3711 /* only want the trailing 32 bits */
3712 y
= x
& 0xFFFFFFFFUL
;
3714 return PyErr_Format(PyExc_OverflowError
,
3715 "long int larger than 32 bits");
3721 return PyErr_Format(PyExc_TypeError
,
3722 "expected int/long, %s found",
3723 Py_TYPE(arg
)->tp_name
);
3724 if (x
== (unsigned long) -1 && PyErr_Occurred())
3726 return PyLong_FromUnsignedLong(ntohl(x
));
3729 PyDoc_STRVAR(ntohl_doc
,
3730 "ntohl(integer) -> integer\n\
3732 Convert a 32-bit integer from network to host byte order.");
3736 socket_htons(PyObject
*self
, PyObject
*args
)
3740 if (!PyArg_ParseTuple(args
, "i:htons", &x1
)) {
3744 PyErr_SetString(PyExc_OverflowError
,
3745 "can't convert negative number to unsigned long");
3748 x2
= (unsigned int)htons((unsigned short)x1
);
3749 return PyInt_FromLong(x2
);
3752 PyDoc_STRVAR(htons_doc
,
3753 "htons(integer) -> integer\n\
3755 Convert a 16-bit integer from host to network byte order.");
3759 socket_htonl(PyObject
*self
, PyObject
*arg
)
3763 if (PyInt_Check(arg
)) {
3764 x
= PyInt_AS_LONG(arg
);
3765 if (x
== (unsigned long) -1 && PyErr_Occurred())
3768 PyErr_SetString(PyExc_OverflowError
,
3769 "can't convert negative number to unsigned long");
3773 else if (PyLong_Check(arg
)) {
3774 x
= PyLong_AsUnsignedLong(arg
);
3775 if (x
== (unsigned long) -1 && PyErr_Occurred())
3780 /* only want the trailing 32 bits */
3781 y
= x
& 0xFFFFFFFFUL
;
3783 return PyErr_Format(PyExc_OverflowError
,
3784 "long int larger than 32 bits");
3790 return PyErr_Format(PyExc_TypeError
,
3791 "expected int/long, %s found",
3792 Py_TYPE(arg
)->tp_name
);
3793 return PyLong_FromUnsignedLong(htonl((unsigned long)x
));
3796 PyDoc_STRVAR(htonl_doc
,
3797 "htonl(integer) -> integer\n\
3799 Convert a 32-bit integer from host to network byte order.");
3801 /* socket.inet_aton() and socket.inet_ntoa() functions. */
3803 PyDoc_STRVAR(inet_aton_doc
,
3804 "inet_aton(string) -> packed 32-bit IP representation\n\
3806 Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
3807 binary format used in low-level network functions.");
3810 socket_inet_aton(PyObject
*self
, PyObject
*args
)
3813 #define INADDR_NONE (-1)
3815 #ifdef HAVE_INET_ATON
3819 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
3820 #if (SIZEOF_INT != 4)
3821 #error "Not sure if in_addr_t exists and int is not 32-bits."
3823 /* Have to use inet_addr() instead */
3824 unsigned int packed_addr
;
3828 if (!PyArg_ParseTuple(args
, "s:inet_aton", &ip_addr
))
3832 #ifdef HAVE_INET_ATON
3834 #ifdef USE_INET_ATON_WEAKLINK
3835 if (inet_aton
!= NULL
) {
3837 if (inet_aton(ip_addr
, &buf
))
3838 return PyString_FromStringAndSize((char *)(&buf
),
3841 PyErr_SetString(socket_error
,
3842 "illegal IP address string passed to inet_aton");
3845 #ifdef USE_INET_ATON_WEAKLINK
3851 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
3853 /* special-case this address as inet_addr might return INADDR_NONE
3855 if (strcmp(ip_addr
, "255.255.255.255") == 0) {
3856 packed_addr
= 0xFFFFFFFF;
3859 packed_addr
= inet_addr(ip_addr
);
3861 if (packed_addr
== INADDR_NONE
) { /* invalid address */
3862 PyErr_SetString(socket_error
,
3863 "illegal IP address string passed to inet_aton");
3867 return PyString_FromStringAndSize((char *) &packed_addr
,
3868 sizeof(packed_addr
));
3870 #ifdef USE_INET_ATON_WEAKLINK
3877 PyDoc_STRVAR(inet_ntoa_doc
,
3878 "inet_ntoa(packed_ip) -> ip_address_string\n\
3880 Convert an IP address from 32-bit packed binary format to string format");
3883 socket_inet_ntoa(PyObject
*self
, PyObject
*args
)
3887 struct in_addr packed_addr
;
3889 if (!PyArg_ParseTuple(args
, "s#:inet_ntoa", &packed_str
, &addr_len
)) {
3893 if (addr_len
!= sizeof(packed_addr
)) {
3894 PyErr_SetString(socket_error
,
3895 "packed IP wrong length for inet_ntoa");
3899 memcpy(&packed_addr
, packed_str
, addr_len
);
3901 return PyString_FromString(inet_ntoa(packed_addr
));
3904 #ifdef HAVE_INET_PTON
3906 PyDoc_STRVAR(inet_pton_doc
,
3907 "inet_pton(af, ip) -> packed IP address string\n\
3909 Convert an IP address from string format to a packed string suitable\n\
3910 for use with low-level network functions.");
3913 socket_inet_pton(PyObject
*self
, PyObject
*args
)
3919 char packed
[MAX(sizeof(struct in_addr
), sizeof(struct in6_addr
))];
3921 char packed
[sizeof(struct in_addr
)];
3923 if (!PyArg_ParseTuple(args
, "is:inet_pton", &af
, &ip
)) {
3927 #if !defined(ENABLE_IPV6) && defined(AF_INET6)
3928 if(af
== AF_INET6
) {
3929 PyErr_SetString(socket_error
,
3930 "can't use AF_INET6, IPv6 is disabled");
3935 retval
= inet_pton(af
, ip
, packed
);
3937 PyErr_SetFromErrno(socket_error
);
3939 } else if (retval
== 0) {
3940 PyErr_SetString(socket_error
,
3941 "illegal IP address string passed to inet_pton");
3943 } else if (af
== AF_INET
) {
3944 return PyString_FromStringAndSize(packed
,
3945 sizeof(struct in_addr
));
3947 } else if (af
== AF_INET6
) {
3948 return PyString_FromStringAndSize(packed
,
3949 sizeof(struct in6_addr
));
3952 PyErr_SetString(socket_error
, "unknown address family");
3957 PyDoc_STRVAR(inet_ntop_doc
,
3958 "inet_ntop(af, packed_ip) -> string formatted IP address\n\
3960 Convert a packed IP address of the given family to string format.");
3963 socket_inet_ntop(PyObject
*self
, PyObject
*args
)
3970 char ip
[MAX(INET_ADDRSTRLEN
, INET6_ADDRSTRLEN
) + 1];
3972 char ip
[INET_ADDRSTRLEN
+ 1];
3975 /* Guarantee NUL-termination for PyString_FromString() below */
3976 memset((void *) &ip
[0], '\0', sizeof(ip
));
3978 if (!PyArg_ParseTuple(args
, "is#:inet_ntop", &af
, &packed
, &len
)) {
3982 if (af
== AF_INET
) {
3983 if (len
!= sizeof(struct in_addr
)) {
3984 PyErr_SetString(PyExc_ValueError
,
3985 "invalid length of packed IP address string");
3989 } else if (af
== AF_INET6
) {
3990 if (len
!= sizeof(struct in6_addr
)) {
3991 PyErr_SetString(PyExc_ValueError
,
3992 "invalid length of packed IP address string");
3997 PyErr_Format(PyExc_ValueError
,
3998 "unknown address family %d", af
);
4002 retval
= inet_ntop(af
, packed
, ip
, sizeof(ip
));
4004 PyErr_SetFromErrno(socket_error
);
4007 return PyString_FromString(retval
);
4011 PyErr_SetString(PyExc_RuntimeError
, "invalid handling of inet_ntop");
4015 #endif /* HAVE_INET_PTON */
4017 /* Python interface to getaddrinfo(host, port). */
4021 socket_getaddrinfo(PyObject
*self
, PyObject
*args
)
4023 struct addrinfo hints
, *res
;
4024 struct addrinfo
*res0
= NULL
;
4025 PyObject
*hobj
= NULL
;
4026 PyObject
*pobj
= (PyObject
*)NULL
;
4029 int family
, socktype
, protocol
, flags
;
4031 PyObject
*all
= (PyObject
*)NULL
;
4032 PyObject
*single
= (PyObject
*)NULL
;
4033 PyObject
*idna
= NULL
;
4035 family
= socktype
= protocol
= flags
= 0;
4037 if (!PyArg_ParseTuple(args
, "OO|iiii:getaddrinfo",
4038 &hobj
, &pobj
, &family
, &socktype
,
4039 &protocol
, &flags
)) {
4042 if (hobj
== Py_None
) {
4044 } else if (PyUnicode_Check(hobj
)) {
4045 idna
= PyObject_CallMethod(hobj
, "encode", "s", "idna");
4048 hptr
= PyString_AsString(idna
);
4049 } else if (PyString_Check(hobj
)) {
4050 hptr
= PyString_AsString(hobj
);
4052 PyErr_SetString(PyExc_TypeError
,
4053 "getaddrinfo() argument 1 must be string or None");
4056 if (PyInt_Check(pobj
)) {
4057 PyOS_snprintf(pbuf
, sizeof(pbuf
), "%ld", PyInt_AsLong(pobj
));
4059 } else if (PyString_Check(pobj
)) {
4060 pptr
= PyString_AsString(pobj
);
4061 } else if (pobj
== Py_None
) {
4062 pptr
= (char *)NULL
;
4064 PyErr_SetString(socket_error
, "Int or String expected");
4067 memset(&hints
, 0, sizeof(hints
));
4068 hints
.ai_family
= family
;
4069 hints
.ai_socktype
= socktype
;
4070 hints
.ai_protocol
= protocol
;
4071 hints
.ai_flags
= flags
;
4072 Py_BEGIN_ALLOW_THREADS
4073 ACQUIRE_GETADDRINFO_LOCK
4074 error
= getaddrinfo(hptr
, pptr
, &hints
, &res0
);
4075 Py_END_ALLOW_THREADS
4076 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
4078 set_gaierror(error
);
4082 if ((all
= PyList_New(0)) == NULL
)
4084 for (res
= res0
; res
; res
= res
->ai_next
) {
4086 makesockaddr(-1, res
->ai_addr
, res
->ai_addrlen
, protocol
);
4089 single
= Py_BuildValue("iiisO", res
->ai_family
,
4090 res
->ai_socktype
, res
->ai_protocol
,
4091 res
->ai_canonname
? res
->ai_canonname
: "",
4097 if (PyList_Append(all
, single
))
4111 return (PyObject
*)NULL
;
4114 PyDoc_STRVAR(getaddrinfo_doc
,
4115 "getaddrinfo(host, port [, family, socktype, proto, flags])\n\
4116 -> list of (family, socktype, proto, canonname, sockaddr)\n\
4118 Resolve host and port into addrinfo struct.");
4120 /* Python interface to getnameinfo(sa, flags). */
4124 socket_getnameinfo(PyObject
*self
, PyObject
*args
)
4126 PyObject
*sa
= (PyObject
*)NULL
;
4129 int port
, flowinfo
, scope_id
;
4130 char hbuf
[NI_MAXHOST
], pbuf
[NI_MAXSERV
];
4131 struct addrinfo hints
, *res
= NULL
;
4133 PyObject
*ret
= (PyObject
*)NULL
;
4135 flags
= flowinfo
= scope_id
= 0;
4136 if (!PyArg_ParseTuple(args
, "Oi:getnameinfo", &sa
, &flags
))
4138 if (!PyTuple_Check(sa
)) {
4139 PyErr_SetString(PyExc_TypeError
,
4140 "getnameinfo() argument 1 must be a tuple");
4143 if (!PyArg_ParseTuple(sa
, "si|ii",
4144 &hostp
, &port
, &flowinfo
, &scope_id
))
4146 PyOS_snprintf(pbuf
, sizeof(pbuf
), "%d", port
);
4147 memset(&hints
, 0, sizeof(hints
));
4148 hints
.ai_family
= AF_UNSPEC
;
4149 hints
.ai_socktype
= SOCK_DGRAM
; /* make numeric port happy */
4150 Py_BEGIN_ALLOW_THREADS
4151 ACQUIRE_GETADDRINFO_LOCK
4152 error
= getaddrinfo(hostp
, pbuf
, &hints
, &res
);
4153 Py_END_ALLOW_THREADS
4154 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
4156 set_gaierror(error
);
4160 PyErr_SetString(socket_error
,
4161 "sockaddr resolved to multiple addresses");
4164 switch (res
->ai_family
) {
4167 if (PyTuple_GET_SIZE(sa
) != 2) {
4168 PyErr_SetString(socket_error
,
4169 "IPv4 sockaddr must be 2 tuple");
4177 struct sockaddr_in6
*sin6
;
4178 sin6
= (struct sockaddr_in6
*)res
->ai_addr
;
4179 sin6
->sin6_flowinfo
= flowinfo
;
4180 sin6
->sin6_scope_id
= scope_id
;
4185 error
= getnameinfo(res
->ai_addr
, res
->ai_addrlen
,
4186 hbuf
, sizeof(hbuf
), pbuf
, sizeof(pbuf
), flags
);
4188 set_gaierror(error
);
4191 ret
= Py_BuildValue("ss", hbuf
, pbuf
);
4199 PyDoc_STRVAR(getnameinfo_doc
,
4200 "getnameinfo(sockaddr, flags) --> (host, port)\n\
4202 Get host and port for a sockaddr.");
4205 /* Python API to getting and setting the default timeout value. */
4208 socket_getdefaulttimeout(PyObject
*self
)
4210 if (defaulttimeout
< 0.0) {
4215 return PyFloat_FromDouble(defaulttimeout
);
4218 PyDoc_STRVAR(getdefaulttimeout_doc
,
4219 "getdefaulttimeout() -> timeout\n\
4221 Returns the default timeout in floating seconds for new socket objects.\n\
4222 A value of None indicates that new socket objects have no timeout.\n\
4223 When the socket module is first imported, the default is None.");
4226 socket_setdefaulttimeout(PyObject
*self
, PyObject
*arg
)
4233 timeout
= PyFloat_AsDouble(arg
);
4234 if (timeout
< 0.0) {
4235 if (!PyErr_Occurred())
4236 PyErr_SetString(PyExc_ValueError
,
4237 "Timeout value out of range");
4242 defaulttimeout
= timeout
;
4248 PyDoc_STRVAR(setdefaulttimeout_doc
,
4249 "setdefaulttimeout(timeout)\n\
4251 Set the default timeout in floating seconds for new socket objects.\n\
4252 A value of None indicates that new socket objects have no timeout.\n\
4253 When the socket module is first imported, the default is None.");
4256 /* List of functions exported by this module. */
4258 static PyMethodDef socket_methods
[] = {
4259 {"gethostbyname", socket_gethostbyname
,
4260 METH_VARARGS
, gethostbyname_doc
},
4261 {"gethostbyname_ex", socket_gethostbyname_ex
,
4262 METH_VARARGS
, ghbn_ex_doc
},
4263 {"gethostbyaddr", socket_gethostbyaddr
,
4264 METH_VARARGS
, gethostbyaddr_doc
},
4265 {"gethostname", socket_gethostname
,
4266 METH_NOARGS
, gethostname_doc
},
4267 {"getservbyname", socket_getservbyname
,
4268 METH_VARARGS
, getservbyname_doc
},
4269 {"getservbyport", socket_getservbyport
,
4270 METH_VARARGS
, getservbyport_doc
},
4271 {"getprotobyname", socket_getprotobyname
,
4272 METH_VARARGS
, getprotobyname_doc
},
4274 {"fromfd", socket_fromfd
,
4275 METH_VARARGS
, fromfd_doc
},
4277 #ifdef HAVE_SOCKETPAIR
4278 {"socketpair", socket_socketpair
,
4279 METH_VARARGS
, socketpair_doc
},
4281 {"ntohs", socket_ntohs
,
4282 METH_VARARGS
, ntohs_doc
},
4283 {"ntohl", socket_ntohl
,
4285 {"htons", socket_htons
,
4286 METH_VARARGS
, htons_doc
},
4287 {"htonl", socket_htonl
,
4289 {"inet_aton", socket_inet_aton
,
4290 METH_VARARGS
, inet_aton_doc
},
4291 {"inet_ntoa", socket_inet_ntoa
,
4292 METH_VARARGS
, inet_ntoa_doc
},
4293 #ifdef HAVE_INET_PTON
4294 {"inet_pton", socket_inet_pton
,
4295 METH_VARARGS
, inet_pton_doc
},
4296 {"inet_ntop", socket_inet_ntop
,
4297 METH_VARARGS
, inet_ntop_doc
},
4299 {"getaddrinfo", socket_getaddrinfo
,
4300 METH_VARARGS
, getaddrinfo_doc
},
4301 {"getnameinfo", socket_getnameinfo
,
4302 METH_VARARGS
, getnameinfo_doc
},
4303 {"getdefaulttimeout", (PyCFunction
)socket_getdefaulttimeout
,
4304 METH_NOARGS
, getdefaulttimeout_doc
},
4305 {"setdefaulttimeout", socket_setdefaulttimeout
,
4306 METH_O
, setdefaulttimeout_doc
},
4307 {NULL
, NULL
} /* Sentinel */
4312 #define OS_INIT_DEFINED
4320 _kernel_swi(0x43380, &r
, &r
);
4321 taskwindow
= r
.r
[0];
4330 #define OS_INIT_DEFINED
4332 /* Additional initialization and cleanup for Windows */
4346 ret
= WSAStartup(0x0101, &WSAData
);
4348 case 0: /* No error */
4349 Py_AtExit(os_cleanup
);
4350 return 1; /* Success */
4351 case WSASYSNOTREADY
:
4352 PyErr_SetString(PyExc_ImportError
,
4353 "WSAStartup failed: network not ready");
4355 case WSAVERNOTSUPPORTED
:
4359 "WSAStartup failed: requested version not supported");
4362 PyOS_snprintf(buf
, sizeof(buf
),
4363 "WSAStartup failed: error code %d", ret
);
4364 PyErr_SetString(PyExc_ImportError
, buf
);
4367 return 0; /* Failure */
4370 #endif /* MS_WINDOWS */
4374 #define OS_INIT_DEFINED
4376 /* Additional initialization for OS/2 */
4383 int rc
= sock_init();
4386 return 1; /* Success */
4389 PyOS_snprintf(reason
, sizeof(reason
),
4390 "OS/2 TCP/IP Error# %d", sock_errno());
4391 PyErr_SetString(PyExc_ImportError
, reason
);
4393 return 0; /* Failure */
4395 /* No need to initialise sockets with GCC/EMX */
4396 return 1; /* Success */
4400 #endif /* PYOS_OS2 */
4403 #ifndef OS_INIT_DEFINED
4407 return 1; /* Success */
4412 /* C API table - always add new things to the end for binary
4415 PySocketModule_APIObject PySocketModuleAPI
=
4422 /* Initialize the _socket module.
4424 This module is actually called "_socket", and there's a wrapper
4425 "socket.py" which implements some additional functionality. On some
4426 platforms (e.g. Windows and OS/2), socket.py also implements a
4427 wrapper for the socket type that provides missing functionality such
4428 as makefile(), dup() and fromfd(). The import of "_socket" may fail
4429 with an ImportError exception if os-specific initialization fails.
4430 On Windows, this does WINSOCK initialization. When WINSOCK is
4431 initialized succesfully, a call to WSACleanup() is scheduled to be
4435 PyDoc_STRVAR(socket_doc
,
4436 "Implementation module for socket operations.\n\
4438 See the socket module for documentation.");
4443 PyObject
*m
, *has_ipv6
;
4448 Py_TYPE(&sock_type
) = &PyType_Type
;
4449 m
= Py_InitModule3(PySocket_MODULE_NAME
,
4455 socket_error
= PyErr_NewException("socket.error",
4456 PyExc_IOError
, NULL
);
4457 if (socket_error
== NULL
)
4459 PySocketModuleAPI
.error
= socket_error
;
4460 Py_INCREF(socket_error
);
4461 PyModule_AddObject(m
, "error", socket_error
);
4462 socket_herror
= PyErr_NewException("socket.herror",
4463 socket_error
, NULL
);
4464 if (socket_herror
== NULL
)
4466 Py_INCREF(socket_herror
);
4467 PyModule_AddObject(m
, "herror", socket_herror
);
4468 socket_gaierror
= PyErr_NewException("socket.gaierror", socket_error
,
4470 if (socket_gaierror
== NULL
)
4472 Py_INCREF(socket_gaierror
);
4473 PyModule_AddObject(m
, "gaierror", socket_gaierror
);
4474 socket_timeout
= PyErr_NewException("socket.timeout",
4475 socket_error
, NULL
);
4476 if (socket_timeout
== NULL
)
4478 Py_INCREF(socket_timeout
);
4479 PyModule_AddObject(m
, "timeout", socket_timeout
);
4480 Py_INCREF((PyObject
*)&sock_type
);
4481 if (PyModule_AddObject(m
, "SocketType",
4482 (PyObject
*)&sock_type
) != 0)
4484 Py_INCREF((PyObject
*)&sock_type
);
4485 if (PyModule_AddObject(m
, "socket",
4486 (PyObject
*)&sock_type
) != 0)
4492 has_ipv6
= Py_False
;
4494 Py_INCREF(has_ipv6
);
4495 PyModule_AddObject(m
, "has_ipv6", has_ipv6
);
4498 if (PyModule_AddObject(m
, PySocket_CAPI_NAME
,
4499 PyCapsule_New(&PySocketModuleAPI
, PySocket_CAPSULE_NAME
, NULL
)
4503 /* Address families (we only support AF_INET and AF_UNIX) */
4505 PyModule_AddIntConstant(m
, "AF_UNSPEC", AF_UNSPEC
);
4507 PyModule_AddIntConstant(m
, "AF_INET", AF_INET
);
4509 PyModule_AddIntConstant(m
, "AF_INET6", AF_INET6
);
4510 #endif /* AF_INET6 */
4511 #if defined(AF_UNIX)
4512 PyModule_AddIntConstant(m
, "AF_UNIX", AF_UNIX
);
4513 #endif /* AF_UNIX */
4515 /* Amateur Radio AX.25 */
4516 PyModule_AddIntConstant(m
, "AF_AX25", AF_AX25
);
4519 PyModule_AddIntConstant(m
, "AF_IPX", AF_IPX
); /* Novell IPX */
4523 PyModule_AddIntConstant(m
, "AF_APPLETALK", AF_APPLETALK
);
4526 /* Amateur radio NetROM */
4527 PyModule_AddIntConstant(m
, "AF_NETROM", AF_NETROM
);
4530 /* Multiprotocol bridge */
4531 PyModule_AddIntConstant(m
, "AF_BRIDGE", AF_BRIDGE
);
4535 PyModule_AddIntConstant(m
, "AF_ATMPVC", AF_ATMPVC
);
4538 /* Reserved for Werner's ATM */
4539 PyModule_AddIntConstant(m
, "AF_AAL5", AF_AAL5
);
4542 /* Reserved for X.25 project */
4543 PyModule_AddIntConstant(m
, "AF_X25", AF_X25
);
4546 PyModule_AddIntConstant(m
, "AF_INET6", AF_INET6
); /* IP version 6 */
4549 /* Amateur Radio X.25 PLP */
4550 PyModule_AddIntConstant(m
, "AF_ROSE", AF_ROSE
);
4553 /* Reserved for DECnet project */
4554 PyModule_AddIntConstant(m
, "AF_DECnet", AF_DECnet
);
4557 /* Reserved for 802.2LLC project */
4558 PyModule_AddIntConstant(m
, "AF_NETBEUI", AF_NETBEUI
);
4561 /* Security callback pseudo AF */
4562 PyModule_AddIntConstant(m
, "AF_SECURITY", AF_SECURITY
);
4565 /* PF_KEY key management API */
4566 PyModule_AddIntConstant(m
, "AF_KEY", AF_KEY
);
4570 PyModule_AddIntConstant(m
, "AF_NETLINK", AF_NETLINK
);
4571 PyModule_AddIntConstant(m
, "NETLINK_ROUTE", NETLINK_ROUTE
);
4573 PyModule_AddIntConstant(m
, "NETLINK_SKIP", NETLINK_SKIP
);
4576 PyModule_AddIntConstant(m
, "NETLINK_W1", NETLINK_W1
);
4578 PyModule_AddIntConstant(m
, "NETLINK_USERSOCK", NETLINK_USERSOCK
);
4579 PyModule_AddIntConstant(m
, "NETLINK_FIREWALL", NETLINK_FIREWALL
);
4580 #ifdef NETLINK_TCPDIAG
4581 PyModule_AddIntConstant(m
, "NETLINK_TCPDIAG", NETLINK_TCPDIAG
);
4583 #ifdef NETLINK_NFLOG
4584 PyModule_AddIntConstant(m
, "NETLINK_NFLOG", NETLINK_NFLOG
);
4587 PyModule_AddIntConstant(m
, "NETLINK_XFRM", NETLINK_XFRM
);
4590 PyModule_AddIntConstant(m
, "NETLINK_ARPD", NETLINK_ARPD
);
4592 #ifdef NETLINK_ROUTE6
4593 PyModule_AddIntConstant(m
, "NETLINK_ROUTE6", NETLINK_ROUTE6
);
4595 PyModule_AddIntConstant(m
, "NETLINK_IP6_FW", NETLINK_IP6_FW
);
4596 #ifdef NETLINK_DNRTMSG
4597 PyModule_AddIntConstant(m
, "NETLINK_DNRTMSG", NETLINK_DNRTMSG
);
4599 #ifdef NETLINK_TAPBASE
4600 PyModule_AddIntConstant(m
, "NETLINK_TAPBASE", NETLINK_TAPBASE
);
4602 #endif /* AF_NETLINK */
4604 /* Alias to emulate 4.4BSD */
4605 PyModule_AddIntConstant(m
, "AF_ROUTE", AF_ROUTE
);
4609 PyModule_AddIntConstant(m
, "AF_ASH", AF_ASH
);
4613 PyModule_AddIntConstant(m
, "AF_ECONET", AF_ECONET
);
4617 PyModule_AddIntConstant(m
, "AF_ATMSVC", AF_ATMSVC
);
4620 /* Linux SNA Project (nutters!) */
4621 PyModule_AddIntConstant(m
, "AF_SNA", AF_SNA
);
4625 PyModule_AddIntConstant(m
, "AF_IRDA", AF_IRDA
);
4629 PyModule_AddIntConstant(m
, "AF_PPPOX", AF_PPPOX
);
4632 /* Wanpipe API Sockets */
4633 PyModule_AddIntConstant(m
, "AF_WANPIPE", AF_WANPIPE
);
4637 PyModule_AddIntConstant(m
, "AF_LLC", AF_LLC
);
4640 #ifdef USE_BLUETOOTH
4641 PyModule_AddIntConstant(m
, "AF_BLUETOOTH", AF_BLUETOOTH
);
4642 PyModule_AddIntConstant(m
, "BTPROTO_L2CAP", BTPROTO_L2CAP
);
4643 PyModule_AddIntConstant(m
, "BTPROTO_HCI", BTPROTO_HCI
);
4644 PyModule_AddIntConstant(m
, "SOL_HCI", SOL_HCI
);
4645 PyModule_AddIntConstant(m
, "HCI_FILTER", HCI_FILTER
);
4646 #if !defined(__FreeBSD__)
4647 PyModule_AddIntConstant(m
, "HCI_TIME_STAMP", HCI_TIME_STAMP
);
4648 PyModule_AddIntConstant(m
, "HCI_DATA_DIR", HCI_DATA_DIR
);
4649 PyModule_AddIntConstant(m
, "BTPROTO_SCO", BTPROTO_SCO
);
4651 PyModule_AddIntConstant(m
, "BTPROTO_RFCOMM", BTPROTO_RFCOMM
);
4652 PyModule_AddStringConstant(m
, "BDADDR_ANY", "00:00:00:00:00:00");
4653 PyModule_AddStringConstant(m
, "BDADDR_LOCAL", "00:00:00:FF:FF:FF");
4656 #ifdef HAVE_NETPACKET_PACKET_H
4657 PyModule_AddIntConstant(m
, "AF_PACKET", AF_PACKET
);
4658 PyModule_AddIntConstant(m
, "PF_PACKET", PF_PACKET
);
4659 PyModule_AddIntConstant(m
, "PACKET_HOST", PACKET_HOST
);
4660 PyModule_AddIntConstant(m
, "PACKET_BROADCAST", PACKET_BROADCAST
);
4661 PyModule_AddIntConstant(m
, "PACKET_MULTICAST", PACKET_MULTICAST
);
4662 PyModule_AddIntConstant(m
, "PACKET_OTHERHOST", PACKET_OTHERHOST
);
4663 PyModule_AddIntConstant(m
, "PACKET_OUTGOING", PACKET_OUTGOING
);
4664 PyModule_AddIntConstant(m
, "PACKET_LOOPBACK", PACKET_LOOPBACK
);
4665 PyModule_AddIntConstant(m
, "PACKET_FASTROUTE", PACKET_FASTROUTE
);
4668 #ifdef HAVE_LINUX_TIPC_H
4669 PyModule_AddIntConstant(m
, "AF_TIPC", AF_TIPC
);
4672 PyModule_AddIntConstant(m
, "TIPC_ADDR_NAMESEQ", TIPC_ADDR_NAMESEQ
);
4673 PyModule_AddIntConstant(m
, "TIPC_ADDR_NAME", TIPC_ADDR_NAME
);
4674 PyModule_AddIntConstant(m
, "TIPC_ADDR_ID", TIPC_ADDR_ID
);
4676 PyModule_AddIntConstant(m
, "TIPC_ZONE_SCOPE", TIPC_ZONE_SCOPE
);
4677 PyModule_AddIntConstant(m
, "TIPC_CLUSTER_SCOPE", TIPC_CLUSTER_SCOPE
);
4678 PyModule_AddIntConstant(m
, "TIPC_NODE_SCOPE", TIPC_NODE_SCOPE
);
4680 /* for setsockopt() */
4681 PyModule_AddIntConstant(m
, "SOL_TIPC", SOL_TIPC
);
4682 PyModule_AddIntConstant(m
, "TIPC_IMPORTANCE", TIPC_IMPORTANCE
);
4683 PyModule_AddIntConstant(m
, "TIPC_SRC_DROPPABLE", TIPC_SRC_DROPPABLE
);
4684 PyModule_AddIntConstant(m
, "TIPC_DEST_DROPPABLE",
4685 TIPC_DEST_DROPPABLE
);
4686 PyModule_AddIntConstant(m
, "TIPC_CONN_TIMEOUT", TIPC_CONN_TIMEOUT
);
4688 PyModule_AddIntConstant(m
, "TIPC_LOW_IMPORTANCE",
4689 TIPC_LOW_IMPORTANCE
);
4690 PyModule_AddIntConstant(m
, "TIPC_MEDIUM_IMPORTANCE",
4691 TIPC_MEDIUM_IMPORTANCE
);
4692 PyModule_AddIntConstant(m
, "TIPC_HIGH_IMPORTANCE",
4693 TIPC_HIGH_IMPORTANCE
);
4694 PyModule_AddIntConstant(m
, "TIPC_CRITICAL_IMPORTANCE",
4695 TIPC_CRITICAL_IMPORTANCE
);
4697 /* for subscriptions */
4698 PyModule_AddIntConstant(m
, "TIPC_SUB_PORTS", TIPC_SUB_PORTS
);
4699 PyModule_AddIntConstant(m
, "TIPC_SUB_SERVICE", TIPC_SUB_SERVICE
);
4700 #ifdef TIPC_SUB_CANCEL
4701 /* doesn't seem to be available everywhere */
4702 PyModule_AddIntConstant(m
, "TIPC_SUB_CANCEL", TIPC_SUB_CANCEL
);
4704 PyModule_AddIntConstant(m
, "TIPC_WAIT_FOREVER", TIPC_WAIT_FOREVER
);
4705 PyModule_AddIntConstant(m
, "TIPC_PUBLISHED", TIPC_PUBLISHED
);
4706 PyModule_AddIntConstant(m
, "TIPC_WITHDRAWN", TIPC_WITHDRAWN
);
4707 PyModule_AddIntConstant(m
, "TIPC_SUBSCR_TIMEOUT", TIPC_SUBSCR_TIMEOUT
);
4708 PyModule_AddIntConstant(m
, "TIPC_CFG_SRV", TIPC_CFG_SRV
);
4709 PyModule_AddIntConstant(m
, "TIPC_TOP_SRV", TIPC_TOP_SRV
);
4713 PyModule_AddIntConstant(m
, "SOCK_STREAM", SOCK_STREAM
);
4714 PyModule_AddIntConstant(m
, "SOCK_DGRAM", SOCK_DGRAM
);
4716 /* We have incomplete socket support. */
4717 PyModule_AddIntConstant(m
, "SOCK_RAW", SOCK_RAW
);
4718 PyModule_AddIntConstant(m
, "SOCK_SEQPACKET", SOCK_SEQPACKET
);
4719 #if defined(SOCK_RDM)
4720 PyModule_AddIntConstant(m
, "SOCK_RDM", SOCK_RDM
);
4725 PyModule_AddIntConstant(m
, "SO_DEBUG", SO_DEBUG
);
4727 #ifdef SO_ACCEPTCONN
4728 PyModule_AddIntConstant(m
, "SO_ACCEPTCONN", SO_ACCEPTCONN
);
4731 PyModule_AddIntConstant(m
, "SO_REUSEADDR", SO_REUSEADDR
);
4733 #ifdef SO_EXCLUSIVEADDRUSE
4734 PyModule_AddIntConstant(m
, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE
);
4738 PyModule_AddIntConstant(m
, "SO_KEEPALIVE", SO_KEEPALIVE
);
4741 PyModule_AddIntConstant(m
, "SO_DONTROUTE", SO_DONTROUTE
);
4744 PyModule_AddIntConstant(m
, "SO_BROADCAST", SO_BROADCAST
);
4746 #ifdef SO_USELOOPBACK
4747 PyModule_AddIntConstant(m
, "SO_USELOOPBACK", SO_USELOOPBACK
);
4750 PyModule_AddIntConstant(m
, "SO_LINGER", SO_LINGER
);
4753 PyModule_AddIntConstant(m
, "SO_OOBINLINE", SO_OOBINLINE
);
4756 PyModule_AddIntConstant(m
, "SO_REUSEPORT", SO_REUSEPORT
);
4759 PyModule_AddIntConstant(m
, "SO_SNDBUF", SO_SNDBUF
);
4762 PyModule_AddIntConstant(m
, "SO_RCVBUF", SO_RCVBUF
);
4765 PyModule_AddIntConstant(m
, "SO_SNDLOWAT", SO_SNDLOWAT
);
4768 PyModule_AddIntConstant(m
, "SO_RCVLOWAT", SO_RCVLOWAT
);
4771 PyModule_AddIntConstant(m
, "SO_SNDTIMEO", SO_SNDTIMEO
);
4774 PyModule_AddIntConstant(m
, "SO_RCVTIMEO", SO_RCVTIMEO
);
4777 PyModule_AddIntConstant(m
, "SO_ERROR", SO_ERROR
);
4780 PyModule_AddIntConstant(m
, "SO_TYPE", SO_TYPE
);
4783 PyModule_AddIntConstant(m
, "SO_SETFIB", SO_SETFIB
);
4786 /* Maximum number of connections for "listen" */
4788 PyModule_AddIntConstant(m
, "SOMAXCONN", SOMAXCONN
);
4790 PyModule_AddIntConstant(m
, "SOMAXCONN", 5); /* Common value */
4793 /* Flags for send, recv */
4795 PyModule_AddIntConstant(m
, "MSG_OOB", MSG_OOB
);
4798 PyModule_AddIntConstant(m
, "MSG_PEEK", MSG_PEEK
);
4800 #ifdef MSG_DONTROUTE
4801 PyModule_AddIntConstant(m
, "MSG_DONTROUTE", MSG_DONTROUTE
);
4804 PyModule_AddIntConstant(m
, "MSG_DONTWAIT", MSG_DONTWAIT
);
4807 PyModule_AddIntConstant(m
, "MSG_EOR", MSG_EOR
);
4810 PyModule_AddIntConstant(m
, "MSG_TRUNC", MSG_TRUNC
);
4813 PyModule_AddIntConstant(m
, "MSG_CTRUNC", MSG_CTRUNC
);
4816 PyModule_AddIntConstant(m
, "MSG_WAITALL", MSG_WAITALL
);
4819 PyModule_AddIntConstant(m
, "MSG_BTAG", MSG_BTAG
);
4822 PyModule_AddIntConstant(m
, "MSG_ETAG", MSG_ETAG
);
4825 /* Protocol level and numbers, usable for [gs]etsockopt */
4827 PyModule_AddIntConstant(m
, "SOL_SOCKET", SOL_SOCKET
);
4830 PyModule_AddIntConstant(m
, "SOL_IP", SOL_IP
);
4832 PyModule_AddIntConstant(m
, "SOL_IP", 0);
4835 PyModule_AddIntConstant(m
, "SOL_IPX", SOL_IPX
);
4838 PyModule_AddIntConstant(m
, "SOL_AX25", SOL_AX25
);
4841 PyModule_AddIntConstant(m
, "SOL_ATALK", SOL_ATALK
);
4844 PyModule_AddIntConstant(m
, "SOL_NETROM", SOL_NETROM
);
4847 PyModule_AddIntConstant(m
, "SOL_ROSE", SOL_ROSE
);
4850 PyModule_AddIntConstant(m
, "SOL_TCP", SOL_TCP
);
4852 PyModule_AddIntConstant(m
, "SOL_TCP", 6);
4855 PyModule_AddIntConstant(m
, "SOL_UDP", SOL_UDP
);
4857 PyModule_AddIntConstant(m
, "SOL_UDP", 17);
4860 PyModule_AddIntConstant(m
, "IPPROTO_IP", IPPROTO_IP
);
4862 PyModule_AddIntConstant(m
, "IPPROTO_IP", 0);
4864 #ifdef IPPROTO_HOPOPTS
4865 PyModule_AddIntConstant(m
, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS
);
4868 PyModule_AddIntConstant(m
, "IPPROTO_ICMP", IPPROTO_ICMP
);
4870 PyModule_AddIntConstant(m
, "IPPROTO_ICMP", 1);
4873 PyModule_AddIntConstant(m
, "IPPROTO_IGMP", IPPROTO_IGMP
);
4876 PyModule_AddIntConstant(m
, "IPPROTO_GGP", IPPROTO_GGP
);
4879 PyModule_AddIntConstant(m
, "IPPROTO_IPV4", IPPROTO_IPV4
);
4882 PyModule_AddIntConstant(m
, "IPPROTO_IPV6", IPPROTO_IPV6
);
4885 PyModule_AddIntConstant(m
, "IPPROTO_IPIP", IPPROTO_IPIP
);
4888 PyModule_AddIntConstant(m
, "IPPROTO_TCP", IPPROTO_TCP
);
4890 PyModule_AddIntConstant(m
, "IPPROTO_TCP", 6);
4893 PyModule_AddIntConstant(m
, "IPPROTO_EGP", IPPROTO_EGP
);
4896 PyModule_AddIntConstant(m
, "IPPROTO_PUP", IPPROTO_PUP
);
4899 PyModule_AddIntConstant(m
, "IPPROTO_UDP", IPPROTO_UDP
);
4901 PyModule_AddIntConstant(m
, "IPPROTO_UDP", 17);
4904 PyModule_AddIntConstant(m
, "IPPROTO_IDP", IPPROTO_IDP
);
4906 #ifdef IPPROTO_HELLO
4907 PyModule_AddIntConstant(m
, "IPPROTO_HELLO", IPPROTO_HELLO
);
4910 PyModule_AddIntConstant(m
, "IPPROTO_ND", IPPROTO_ND
);
4913 PyModule_AddIntConstant(m
, "IPPROTO_TP", IPPROTO_TP
);
4916 PyModule_AddIntConstant(m
, "IPPROTO_IPV6", IPPROTO_IPV6
);
4918 #ifdef IPPROTO_ROUTING
4919 PyModule_AddIntConstant(m
, "IPPROTO_ROUTING", IPPROTO_ROUTING
);
4921 #ifdef IPPROTO_FRAGMENT
4922 PyModule_AddIntConstant(m
, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT
);
4925 PyModule_AddIntConstant(m
, "IPPROTO_RSVP", IPPROTO_RSVP
);
4928 PyModule_AddIntConstant(m
, "IPPROTO_GRE", IPPROTO_GRE
);
4931 PyModule_AddIntConstant(m
, "IPPROTO_ESP", IPPROTO_ESP
);
4934 PyModule_AddIntConstant(m
, "IPPROTO_AH", IPPROTO_AH
);
4936 #ifdef IPPROTO_MOBILE
4937 PyModule_AddIntConstant(m
, "IPPROTO_MOBILE", IPPROTO_MOBILE
);
4939 #ifdef IPPROTO_ICMPV6
4940 PyModule_AddIntConstant(m
, "IPPROTO_ICMPV6", IPPROTO_ICMPV6
);
4943 PyModule_AddIntConstant(m
, "IPPROTO_NONE", IPPROTO_NONE
);
4945 #ifdef IPPROTO_DSTOPTS
4946 PyModule_AddIntConstant(m
, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS
);
4949 PyModule_AddIntConstant(m
, "IPPROTO_XTP", IPPROTO_XTP
);
4952 PyModule_AddIntConstant(m
, "IPPROTO_EON", IPPROTO_EON
);
4955 PyModule_AddIntConstant(m
, "IPPROTO_PIM", IPPROTO_PIM
);
4957 #ifdef IPPROTO_IPCOMP
4958 PyModule_AddIntConstant(m
, "IPPROTO_IPCOMP", IPPROTO_IPCOMP
);
4961 PyModule_AddIntConstant(m
, "IPPROTO_VRRP", IPPROTO_VRRP
);
4964 PyModule_AddIntConstant(m
, "IPPROTO_BIP", IPPROTO_BIP
);
4968 PyModule_AddIntConstant(m
, "IPPROTO_RAW", IPPROTO_RAW
);
4970 PyModule_AddIntConstant(m
, "IPPROTO_RAW", 255);
4973 PyModule_AddIntConstant(m
, "IPPROTO_MAX", IPPROTO_MAX
);
4976 /* Some port configuration */
4977 #ifdef IPPORT_RESERVED
4978 PyModule_AddIntConstant(m
, "IPPORT_RESERVED", IPPORT_RESERVED
);
4980 PyModule_AddIntConstant(m
, "IPPORT_RESERVED", 1024);
4982 #ifdef IPPORT_USERRESERVED
4983 PyModule_AddIntConstant(m
, "IPPORT_USERRESERVED", IPPORT_USERRESERVED
);
4985 PyModule_AddIntConstant(m
, "IPPORT_USERRESERVED", 5000);
4988 /* Some reserved IP v.4 addresses */
4990 PyModule_AddIntConstant(m
, "INADDR_ANY", INADDR_ANY
);
4992 PyModule_AddIntConstant(m
, "INADDR_ANY", 0x00000000);
4994 #ifdef INADDR_BROADCAST
4995 PyModule_AddIntConstant(m
, "INADDR_BROADCAST", INADDR_BROADCAST
);
4997 PyModule_AddIntConstant(m
, "INADDR_BROADCAST", 0xffffffff);
4999 #ifdef INADDR_LOOPBACK
5000 PyModule_AddIntConstant(m
, "INADDR_LOOPBACK", INADDR_LOOPBACK
);
5002 PyModule_AddIntConstant(m
, "INADDR_LOOPBACK", 0x7F000001);
5004 #ifdef INADDR_UNSPEC_GROUP
5005 PyModule_AddIntConstant(m
, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP
);
5007 PyModule_AddIntConstant(m
, "INADDR_UNSPEC_GROUP", 0xe0000000);
5009 #ifdef INADDR_ALLHOSTS_GROUP
5010 PyModule_AddIntConstant(m
, "INADDR_ALLHOSTS_GROUP",
5011 INADDR_ALLHOSTS_GROUP
);
5013 PyModule_AddIntConstant(m
, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
5015 #ifdef INADDR_MAX_LOCAL_GROUP
5016 PyModule_AddIntConstant(m
, "INADDR_MAX_LOCAL_GROUP",
5017 INADDR_MAX_LOCAL_GROUP
);
5019 PyModule_AddIntConstant(m
, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
5022 PyModule_AddIntConstant(m
, "INADDR_NONE", INADDR_NONE
);
5024 PyModule_AddIntConstant(m
, "INADDR_NONE", 0xffffffff);
5027 /* IPv4 [gs]etsockopt options */
5029 PyModule_AddIntConstant(m
, "IP_OPTIONS", IP_OPTIONS
);
5032 PyModule_AddIntConstant(m
, "IP_HDRINCL", IP_HDRINCL
);
5035 PyModule_AddIntConstant(m
, "IP_TOS", IP_TOS
);
5038 PyModule_AddIntConstant(m
, "IP_TTL", IP_TTL
);
5041 PyModule_AddIntConstant(m
, "IP_RECVOPTS", IP_RECVOPTS
);
5043 #ifdef IP_RECVRETOPTS
5044 PyModule_AddIntConstant(m
, "IP_RECVRETOPTS", IP_RECVRETOPTS
);
5046 #ifdef IP_RECVDSTADDR
5047 PyModule_AddIntConstant(m
, "IP_RECVDSTADDR", IP_RECVDSTADDR
);
5050 PyModule_AddIntConstant(m
, "IP_RETOPTS", IP_RETOPTS
);
5052 #ifdef IP_MULTICAST_IF
5053 PyModule_AddIntConstant(m
, "IP_MULTICAST_IF", IP_MULTICAST_IF
);
5055 #ifdef IP_MULTICAST_TTL
5056 PyModule_AddIntConstant(m
, "IP_MULTICAST_TTL", IP_MULTICAST_TTL
);
5058 #ifdef IP_MULTICAST_LOOP
5059 PyModule_AddIntConstant(m
, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP
);
5061 #ifdef IP_ADD_MEMBERSHIP
5062 PyModule_AddIntConstant(m
, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP
);
5064 #ifdef IP_DROP_MEMBERSHIP
5065 PyModule_AddIntConstant(m
, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP
);
5067 #ifdef IP_DEFAULT_MULTICAST_TTL
5068 PyModule_AddIntConstant(m
, "IP_DEFAULT_MULTICAST_TTL",
5069 IP_DEFAULT_MULTICAST_TTL
);
5071 #ifdef IP_DEFAULT_MULTICAST_LOOP
5072 PyModule_AddIntConstant(m
, "IP_DEFAULT_MULTICAST_LOOP",
5073 IP_DEFAULT_MULTICAST_LOOP
);
5075 #ifdef IP_MAX_MEMBERSHIPS
5076 PyModule_AddIntConstant(m
, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS
);
5079 /* IPv6 [gs]etsockopt options, defined in RFC2553 */
5080 #ifdef IPV6_JOIN_GROUP
5081 PyModule_AddIntConstant(m
, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP
);
5083 #ifdef IPV6_LEAVE_GROUP
5084 PyModule_AddIntConstant(m
, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP
);
5086 #ifdef IPV6_MULTICAST_HOPS
5087 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS
);
5089 #ifdef IPV6_MULTICAST_IF
5090 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF
);
5092 #ifdef IPV6_MULTICAST_LOOP
5093 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP
);
5095 #ifdef IPV6_UNICAST_HOPS
5096 PyModule_AddIntConstant(m
, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS
);
5098 /* Additional IPV6 socket options, defined in RFC 3493 */
5100 PyModule_AddIntConstant(m
, "IPV6_V6ONLY", IPV6_V6ONLY
);
5102 /* Advanced IPV6 socket options, from RFC 3542 */
5103 #ifdef IPV6_CHECKSUM
5104 PyModule_AddIntConstant(m
, "IPV6_CHECKSUM", IPV6_CHECKSUM
);
5106 #ifdef IPV6_DONTFRAG
5107 PyModule_AddIntConstant(m
, "IPV6_DONTFRAG", IPV6_DONTFRAG
);
5110 PyModule_AddIntConstant(m
, "IPV6_DSTOPTS", IPV6_DSTOPTS
);
5112 #ifdef IPV6_HOPLIMIT
5113 PyModule_AddIntConstant(m
, "IPV6_HOPLIMIT", IPV6_HOPLIMIT
);
5116 PyModule_AddIntConstant(m
, "IPV6_HOPOPTS", IPV6_HOPOPTS
);
5119 PyModule_AddIntConstant(m
, "IPV6_NEXTHOP", IPV6_NEXTHOP
);
5122 PyModule_AddIntConstant(m
, "IPV6_PATHMTU", IPV6_PATHMTU
);
5125 PyModule_AddIntConstant(m
, "IPV6_PKTINFO", IPV6_PKTINFO
);
5127 #ifdef IPV6_RECVDSTOPTS
5128 PyModule_AddIntConstant(m
, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS
);
5130 #ifdef IPV6_RECVHOPLIMIT
5131 PyModule_AddIntConstant(m
, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT
);
5133 #ifdef IPV6_RECVHOPOPTS
5134 PyModule_AddIntConstant(m
, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS
);
5136 #ifdef IPV6_RECVPKTINFO
5137 PyModule_AddIntConstant(m
, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO
);
5139 #ifdef IPV6_RECVRTHDR
5140 PyModule_AddIntConstant(m
, "IPV6_RECVRTHDR", IPV6_RECVRTHDR
);
5142 #ifdef IPV6_RECVTCLASS
5143 PyModule_AddIntConstant(m
, "IPV6_RECVTCLASS", IPV6_RECVTCLASS
);
5146 PyModule_AddIntConstant(m
, "IPV6_RTHDR", IPV6_RTHDR
);
5148 #ifdef IPV6_RTHDRDSTOPTS
5149 PyModule_AddIntConstant(m
, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS
);
5151 #ifdef IPV6_RTHDR_TYPE_0
5152 PyModule_AddIntConstant(m
, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0
);
5154 #ifdef IPV6_RECVPATHMTU
5155 PyModule_AddIntConstant(m
, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU
);
5158 PyModule_AddIntConstant(m
, "IPV6_TCLASS", IPV6_TCLASS
);
5160 #ifdef IPV6_USE_MIN_MTU
5161 PyModule_AddIntConstant(m
, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU
);
5166 PyModule_AddIntConstant(m
, "TCP_NODELAY", TCP_NODELAY
);
5169 PyModule_AddIntConstant(m
, "TCP_MAXSEG", TCP_MAXSEG
);
5172 PyModule_AddIntConstant(m
, "TCP_CORK", TCP_CORK
);
5175 PyModule_AddIntConstant(m
, "TCP_KEEPIDLE", TCP_KEEPIDLE
);
5177 #ifdef TCP_KEEPINTVL
5178 PyModule_AddIntConstant(m
, "TCP_KEEPINTVL", TCP_KEEPINTVL
);
5181 PyModule_AddIntConstant(m
, "TCP_KEEPCNT", TCP_KEEPCNT
);
5184 PyModule_AddIntConstant(m
, "TCP_SYNCNT", TCP_SYNCNT
);
5187 PyModule_AddIntConstant(m
, "TCP_LINGER2", TCP_LINGER2
);
5189 #ifdef TCP_DEFER_ACCEPT
5190 PyModule_AddIntConstant(m
, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT
);
5192 #ifdef TCP_WINDOW_CLAMP
5193 PyModule_AddIntConstant(m
, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP
);
5196 PyModule_AddIntConstant(m
, "TCP_INFO", TCP_INFO
);
5199 PyModule_AddIntConstant(m
, "TCP_QUICKACK", TCP_QUICKACK
);
5205 PyModule_AddIntConstant(m
, "IPX_TYPE", IPX_TYPE
);
5208 /* get{addr,name}info parameters */
5209 #ifdef EAI_ADDRFAMILY
5210 PyModule_AddIntConstant(m
, "EAI_ADDRFAMILY", EAI_ADDRFAMILY
);
5213 PyModule_AddIntConstant(m
, "EAI_AGAIN", EAI_AGAIN
);
5216 PyModule_AddIntConstant(m
, "EAI_BADFLAGS", EAI_BADFLAGS
);
5219 PyModule_AddIntConstant(m
, "EAI_FAIL", EAI_FAIL
);
5222 PyModule_AddIntConstant(m
, "EAI_FAMILY", EAI_FAMILY
);
5225 PyModule_AddIntConstant(m
, "EAI_MEMORY", EAI_MEMORY
);
5228 PyModule_AddIntConstant(m
, "EAI_NODATA", EAI_NODATA
);
5231 PyModule_AddIntConstant(m
, "EAI_NONAME", EAI_NONAME
);
5234 PyModule_AddIntConstant(m
, "EAI_OVERFLOW", EAI_OVERFLOW
);
5237 PyModule_AddIntConstant(m
, "EAI_SERVICE", EAI_SERVICE
);
5240 PyModule_AddIntConstant(m
, "EAI_SOCKTYPE", EAI_SOCKTYPE
);
5243 PyModule_AddIntConstant(m
, "EAI_SYSTEM", EAI_SYSTEM
);
5246 PyModule_AddIntConstant(m
, "EAI_BADHINTS", EAI_BADHINTS
);
5249 PyModule_AddIntConstant(m
, "EAI_PROTOCOL", EAI_PROTOCOL
);
5252 PyModule_AddIntConstant(m
, "EAI_MAX", EAI_MAX
);
5255 PyModule_AddIntConstant(m
, "AI_PASSIVE", AI_PASSIVE
);
5258 PyModule_AddIntConstant(m
, "AI_CANONNAME", AI_CANONNAME
);
5260 #ifdef AI_NUMERICHOST
5261 PyModule_AddIntConstant(m
, "AI_NUMERICHOST", AI_NUMERICHOST
);
5263 #ifdef AI_NUMERICSERV
5264 PyModule_AddIntConstant(m
, "AI_NUMERICSERV", AI_NUMERICSERV
);
5267 PyModule_AddIntConstant(m
, "AI_MASK", AI_MASK
);
5270 PyModule_AddIntConstant(m
, "AI_ALL", AI_ALL
);
5272 #ifdef AI_V4MAPPED_CFG
5273 PyModule_AddIntConstant(m
, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG
);
5275 #ifdef AI_ADDRCONFIG
5276 PyModule_AddIntConstant(m
, "AI_ADDRCONFIG", AI_ADDRCONFIG
);
5279 PyModule_AddIntConstant(m
, "AI_V4MAPPED", AI_V4MAPPED
);
5282 PyModule_AddIntConstant(m
, "AI_DEFAULT", AI_DEFAULT
);
5285 PyModule_AddIntConstant(m
, "NI_MAXHOST", NI_MAXHOST
);
5288 PyModule_AddIntConstant(m
, "NI_MAXSERV", NI_MAXSERV
);
5291 PyModule_AddIntConstant(m
, "NI_NOFQDN", NI_NOFQDN
);
5293 #ifdef NI_NUMERICHOST
5294 PyModule_AddIntConstant(m
, "NI_NUMERICHOST", NI_NUMERICHOST
);
5297 PyModule_AddIntConstant(m
, "NI_NAMEREQD", NI_NAMEREQD
);
5299 #ifdef NI_NUMERICSERV
5300 PyModule_AddIntConstant(m
, "NI_NUMERICSERV", NI_NUMERICSERV
);
5303 PyModule_AddIntConstant(m
, "NI_DGRAM", NI_DGRAM
);
5306 /* shutdown() parameters */
5308 PyModule_AddIntConstant(m
, "SHUT_RD", SHUT_RD
);
5309 #elif defined(SD_RECEIVE)
5310 PyModule_AddIntConstant(m
, "SHUT_RD", SD_RECEIVE
);
5312 PyModule_AddIntConstant(m
, "SHUT_RD", 0);
5315 PyModule_AddIntConstant(m
, "SHUT_WR", SHUT_WR
);
5316 #elif defined(SD_SEND)
5317 PyModule_AddIntConstant(m
, "SHUT_WR", SD_SEND
);
5319 PyModule_AddIntConstant(m
, "SHUT_WR", 1);
5322 PyModule_AddIntConstant(m
, "SHUT_RDWR", SHUT_RDWR
);
5323 #elif defined(SD_BOTH)
5324 PyModule_AddIntConstant(m
, "SHUT_RDWR", SD_BOTH
);
5326 PyModule_AddIntConstant(m
, "SHUT_RDWR", 2);
5331 DWORD codes
[] = {SIO_RCVALL
, SIO_KEEPALIVE_VALS
};
5332 const char *names
[] = {"SIO_RCVALL", "SIO_KEEPALIVE_VALS"};
5334 for(i
= 0; i
<sizeof(codes
)/sizeof(*codes
); ++i
) {
5336 tmp
= PyLong_FromUnsignedLong(codes
[i
]);
5339 PyModule_AddObject(m
, names
[i
], tmp
);
5342 PyModule_AddIntConstant(m
, "RCVALL_OFF", RCVALL_OFF
);
5343 PyModule_AddIntConstant(m
, "RCVALL_ON", RCVALL_ON
);
5344 PyModule_AddIntConstant(m
, "RCVALL_SOCKETLEVELONLY", RCVALL_SOCKETLEVELONLY
);
5345 #ifdef RCVALL_IPLEVEL
5346 PyModule_AddIntConstant(m
, "RCVALL_IPLEVEL", RCVALL_IPLEVEL
);
5349 PyModule_AddIntConstant(m
, "RCVALL_MAX", RCVALL_MAX
);
5351 #endif /* _MSTCPIP_ */
5353 /* Initialize gethostbyname lock */
5354 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
5355 netdb_lock
= PyThread_allocate_lock();
5360 #ifndef HAVE_INET_PTON
5361 #if !defined(NTDDI_VERSION) || (NTDDI_VERSION < NTDDI_LONGHORN)
5363 /* Simplistic emulation code for inet_pton that only works for IPv4 */
5364 /* These are not exposed because they do not set errno properly */
5367 inet_pton(int af
, const char *src
, void *dst
)
5369 if (af
== AF_INET
) {
5370 #if (SIZEOF_INT != 4)
5371 #error "Not sure if in_addr_t exists and int is not 32-bits."
5373 unsigned int packed_addr
;
5374 packed_addr
= inet_addr(src
);
5375 if (packed_addr
== INADDR_NONE
)
5377 memcpy(dst
, &packed_addr
, 4);
5380 /* Should set errno to EAFNOSUPPORT */
5385 inet_ntop(int af
, const void *src
, char *dst
, socklen_t size
)
5387 if (af
== AF_INET
) {
5388 struct in_addr packed_addr
;
5390 /* Should set errno to ENOSPC. */
5392 memcpy(&packed_addr
, src
, sizeof(packed_addr
));
5393 return strncpy(dst
, inet_ntoa(packed_addr
), size
);
5395 /* Should set errno to EAFNOSUPPORT */