5 This module provides an interface to Berkeley socket IPC.
9 - Only AF_INET, AF_INET6 and AF_UNIX address families are supported in a
10 portable manner, though AF_PACKET, AF_NETLINK and AF_TIPC are supported
12 - No read/write operations (use sendall/recv or makefile instead).
13 - Additional restrictions apply on some non-Unix platforms (compensated
18 - socket.error: exception raised for socket specific errors
19 - socket.gaierror: exception raised for getaddrinfo/getnameinfo errors,
20 a subclass of socket.error
21 - socket.herror: exception raised for gethostby* errors,
22 a subclass of socket.error
23 - socket.fromfd(fd, family, type[, proto]) --> new socket object (created
24 from an existing file descriptor)
25 - socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')
26 - socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])
27 - socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com')
28 - socket.getprotobyname(protocolname) --> protocol number
29 - socket.getservbyname(servicename[, protocolname]) --> port number
30 - socket.getservbyport(portnumber[, protocolname]) --> service name
31 - socket.socket([family[, type [, proto]]]) --> new socket object
32 - socket.socketpair([family[, type [, proto]]]) --> (socket, socket)
33 - socket.ntohs(16 bit value) --> new int object
34 - socket.ntohl(32 bit value) --> new int object
35 - socket.htons(16 bit value) --> new int object
36 - socket.htonl(32 bit value) --> new int object
37 - socket.getaddrinfo(host, port [, family, socktype, proto, flags])
38 --> List of (family, socktype, proto, canonname, sockaddr)
39 - socket.getnameinfo(sockaddr, flags) --> (host, port)
40 - socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
41 - socket.has_ipv6: boolean value indicating if IPv6 is supported
42 - socket.inet_aton(IP address) -> 32-bit packed IP representation
43 - socket.inet_ntoa(packed IP) -> IP address string
44 - socket.getdefaulttimeout() -> None | float
45 - socket.setdefaulttimeout(None | float)
46 - an Internet socket address is a pair (hostname, port)
47 where hostname can be anything recognized by gethostbyname()
48 (including the dd.dd.dd.dd notation) and port is in host byte order
49 - where a hostname is returned, the dd.dd.dd.dd notation is used
50 - a UNIX domain socket address is a string specifying the pathname
51 - an AF_PACKET socket address is a tuple containing a string
52 specifying the ethernet interface and an integer specifying
53 the Ethernet protocol number to be received. For example:
54 ("eth0",0x1234). Optional 3rd,4th,5th elements in the tuple
55 specify packet-type and ha-type/addr.
56 - an AF_TIPC socket address is expressed as
57 (addr_type, v1, v2, v3 [, scope]); where addr_type can be one of:
58 TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, and TIPC_ADDR_ID;
59 and scope can be one of:
60 TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and TIPC_NODE_SCOPE.
61 The meaning of v1, v2 and v3 depends on the value of addr_type:
62 if addr_type is TIPC_ADDR_NAME:
64 v2 is the port identifier
66 if addr_type is TIPC_ADDR_NAMESEQ:
68 v2 is the lower port number
69 v3 is the upper port number
70 if addr_type is TIPC_ADDR_ID:
76 Local naming conventions:
78 - names starting with sock_ are socket object methods
79 - names starting with socket_ are module-level functions
80 - names starting with PySocket are exported through socketmodule.h
86 * inet_aton is not available on OSX 10.3, yet we want to use a binary
87 * that was build on 10.4 or later to work on that release, weak linking
88 * comes to the rescue.
90 # pragma weak inet_aton
94 #include "structmember.h"
97 #define MAX(x, y) ((x) < (y) ? (y) : (x))
99 /* Socket object documentation */
100 PyDoc_STRVAR(sock_doc,
101 "socket([family[, type[, proto]]]) -> socket object\n\
103 Open a socket of the given type. The family argument specifies the\n\
104 address family; it defaults to AF_INET. The type argument specifies\n\
105 whether this is a stream (SOCK_STREAM, this is the default)\n\
106 or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0,\n\
107 specifying the default protocol. Keyword arguments are accepted.\n\
109 A socket object represents one endpoint of a network connection.\n\
111 Methods of socket objects (keyword arguments not allowed):\n\
113 accept() -- accept a connection, returning new socket and client address\n\
114 bind(addr) -- bind the socket to a local address\n\
115 close() -- close the socket\n\
116 connect(addr) -- connect the socket to a remote address\n\
117 connect_ex(addr) -- connect, return an error code instead of an exception\n\
118 dup() -- return a new socket object identical to the current one [*]\n\
119 fileno() -- return underlying file descriptor\n\
120 getpeername() -- return remote address [*]\n\
121 getsockname() -- return local address\n\
122 getsockopt(level, optname[, buflen]) -- get socket options\n\
123 gettimeout() -- return timeout or None\n\
124 listen(n) -- start listening for incoming connections\n\
125 makefile([mode, [bufsize]]) -- return a file object for the socket [*]\n\
126 recv(buflen[, flags]) -- receive data\n\
127 recv_into(buffer[, nbytes[, flags]]) -- receive data (into a buffer)\n\
128 recvfrom(buflen[, flags]) -- receive data and sender\'s address\n\
129 recvfrom_into(buffer[, nbytes, [, flags])\n\
130 -- receive data and sender\'s address (into a buffer)\n\
131 sendall(data[, flags]) -- send all data\n\
132 send(data[, flags]) -- send data, may not send all of it\n\
133 sendto(data[, flags], addr) -- send data to a given address\n\
134 setblocking(0 | 1) -- set or clear the blocking I/O flag\n\
135 setsockopt(level, optname, value) -- set socket options\n\
136 settimeout(None | float) -- set or clear the timeout\n\
137 shutdown(how) -- shut down traffic in one or both directions\n\
139 [*] not available on all platforms!");
141 /* XXX This is a terrible mess of platform-dependent preprocessor hacks.
142 I hope some day someone can clean this up please... */
144 /* Hacks for gethostbyname_r(). On some non-Linux platforms, the configure
145 script doesn't get this right, so we hardcode some platform checks below.
146 On the other hand, not all Linux versions agree, so there the settings
147 computed by the configure script are needed! */
150 # undef HAVE_GETHOSTBYNAME_R_3_ARG
151 # undef HAVE_GETHOSTBYNAME_R_5_ARG
152 # undef HAVE_GETHOSTBYNAME_R_6_ARG
156 # undef HAVE_GETHOSTBYNAME_R
159 #ifdef HAVE_GETHOSTBYNAME_R
160 # if defined(_AIX) || defined(__osf__)
161 # define HAVE_GETHOSTBYNAME_R_3_ARG
162 # elif defined(__sun) || defined(__sgi)
163 # define HAVE_GETHOSTBYNAME_R_5_ARG
164 # elif defined(linux)
165 /* Rely on the configure script */
167 # undef HAVE_GETHOSTBYNAME_R
171 #if !defined(HAVE_GETHOSTBYNAME_R) && defined(WITH_THREAD) && \
173 # define USE_GETHOSTBYNAME_LOCK
176 /* To use __FreeBSD_version */
177 #ifdef HAVE_SYS_PARAM_H
178 #include <sys/param.h>
180 /* On systems on which getaddrinfo() is believed to not be thread-safe,
181 (this includes the getaddrinfo emulation) protect access with a lock. */
182 #if defined(WITH_THREAD) && (defined(__APPLE__) || \
183 (defined(__FreeBSD__) && __FreeBSD_version+0 < 503000) || \
184 defined(__OpenBSD__) || defined(__NetBSD__) || \
185 defined(__VMS) || !defined(HAVE_GETADDRINFO))
186 #define USE_GETADDRINFO_LOCK
189 #ifdef USE_GETADDRINFO_LOCK
190 #define ACQUIRE_GETADDRINFO_LOCK PyThread_acquire_lock(netdb_lock, 1);
191 #define RELEASE_GETADDRINFO_LOCK PyThread_release_lock(netdb_lock);
193 #define ACQUIRE_GETADDRINFO_LOCK
194 #define RELEASE_GETADDRINFO_LOCK
197 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
198 # include "pythread.h"
201 #if defined(PYCC_VACPP)
204 # include <sys/ioctl.h>
213 #if defined(PYOS_OS2)
215 # define INCL_DOSERRORS
216 # define INCL_NOPMAPI
220 #if defined(__sgi) && _COMPILER_VERSION>700 && !_SGIAPI
221 /* make sure that the reentrant (gethostbyaddr_r etc)
222 functions are declared correctly if compiling with
223 MIPSPro 7.x in ANSI C mode (default) */
225 /* XXX Using _SGIAPI is the wrong thing,
226 but I don't know what the right thing is. */
227 #undef _SGIAPI /* to avoid warning */
231 #include <sys/socket.h>
232 #include <sys/types.h>
233 #include <netinet/in.h>
235 #define HAVE_GETADDRINFO 1
236 #define HAVE_GETNAMEINFO 1
239 #define HAVE_INET_PTON
243 /* Irix 6.5 fails to define this variable at all. This is needed
244 for both GCC and SGI's compiler. I'd say that the SGI headers
245 are just busted. Same thing for Solaris. */
246 #if (defined(__sgi) || defined(sun)) && !defined(INET_ADDRSTRLEN)
247 #define INET_ADDRSTRLEN 16
250 /* Generic includes */
251 #ifdef HAVE_SYS_TYPES_H
252 #include <sys/types.h>
255 /* Generic socket object definitions and includes */
256 #define PySocket_BUILDING_SOCKET
257 #include "socketmodule.h"
259 /* Addressing includes */
263 /* Non-MS WINDOWS includes */
266 /* Headers needed for inet_ntoa() and inet_addr() */
268 # include <net/netdb.h>
269 # elif defined(PYOS_OS2) && defined(PYCC_VACPP)
271 typedef size_t socklen_t;
273 # include <arpa/inet.h>
279 # include <sys/ioctl.h>
280 # include <socklib.h>
282 int h_errno; /* not used */
283 # define INET_ADDRSTRLEN 16
288 /* MS_WINDOWS includes */
298 # define offsetof(type, member) ((size_t)(&((type *)0)->member))
302 # define O_NONBLOCK O_NDELAY
305 /* include Python's addrinfo.h unless it causes trouble */
306 #if defined(__sgi) && _COMPILER_VERSION>700 && defined(_SS_ALIGNSIZE)
307 /* Do not include addinfo.h on some newer IRIX versions.
308 * _SS_ALIGNSIZE is defined in sys/socket.h by 6.5.21,
309 * for example, but not by 6.5.10.
311 #elif defined(_MSC_VER) && _MSC_VER>1201
312 /* Do not include addrinfo.h for MSVC7 or greater. 'addrinfo' and
313 * EAI_* constants are defined in (the already included) ws2tcpip.h.
316 # include "addrinfo.h"
319 #ifndef HAVE_INET_PTON
320 #if !defined(NTDDI_VERSION) || (NTDDI_VERSION < NTDDI_LONGHORN)
321 int inet_pton(int af, const char *src, void *dst);
322 const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
327 /* On OS X, getaddrinfo returns no error indication of lookup
328 failure, so we must use the emulation instead of the libinfo
329 implementation. Unfortunately, performing an autoconf test
330 for this bug would require DNS access for the machine performing
331 the configuration, which is not acceptable. Therefore, we
332 determine the bug just by checking for __APPLE__. If this bug
333 gets ever fixed, perhaps checking for sys/version.h would be
334 appropriate, which is 10/0 on the system with the bug. */
335 #ifndef HAVE_GETNAMEINFO
336 /* This bug seems to be fixed in Jaguar. Ths easiest way I could
337 Find to check for Jaguar is that it has getnameinfo(), which
338 older releases don't have */
339 #undef HAVE_GETADDRINFO
342 #ifdef HAVE_INET_ATON
343 #define USE_INET_ATON_WEAKLINK
348 /* I know this is a bad practice, but it is the easiest... */
349 #if !defined(HAVE_GETADDRINFO)
350 /* avoid clashes with the C library definition of the symbol. */
351 #define getaddrinfo fake_getaddrinfo
352 #define gai_strerror fake_gai_strerror
353 #define freeaddrinfo fake_freeaddrinfo
354 #include "getaddrinfo.c"
356 #if !defined(HAVE_GETNAMEINFO)
357 #define getnameinfo fake_getnameinfo
358 #include "getnameinfo.c"
361 #if defined(MS_WINDOWS) || defined(__BEOS__)
362 /* BeOS suffers from the same socket dichotomy as Win32... - [cjh] */
363 /* seem to be a few differences in the API */
364 #define SOCKETCLOSE closesocket
365 #define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */
369 #define EAFNOSUPPORT WSAEAFNOSUPPORT
370 #define snprintf _snprintf
373 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
374 #define SOCKETCLOSE soclose
375 #define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
379 #define SOCKETCLOSE close
382 #if (defined(HAVE_BLUETOOTH_H) || defined(HAVE_BLUETOOTH_BLUETOOTH_H)) && !defined(__NetBSD__) && !defined(__DragonFly__)
383 #define USE_BLUETOOTH 1
384 #if defined(__FreeBSD__)
385 #define BTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP
386 #define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM
387 #define BTPROTO_HCI BLUETOOTH_PROTO_HCI
388 #define SOL_HCI SOL_HCI_RAW
389 #define HCI_FILTER SO_HCI_RAW_FILTER
390 #define sockaddr_l2 sockaddr_l2cap
391 #define sockaddr_rc sockaddr_rfcomm
392 #define hci_dev hci_node
393 #define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb)
394 #define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)
395 #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
396 #elif defined(__NetBSD__) || defined(__DragonFly__)
397 #define sockaddr_l2 sockaddr_bt
398 #define sockaddr_rc sockaddr_bt
399 #define sockaddr_hci sockaddr_bt
400 #define sockaddr_sco sockaddr_bt
401 #define SOL_HCI BTPROTO_HCI
402 #define HCI_DATA_DIR SO_HCI_DIRECTION
403 #define _BT_L2_MEMB(sa, memb) ((sa)->bt_##memb)
404 #define _BT_RC_MEMB(sa, memb) ((sa)->bt_##memb)
405 #define _BT_HCI_MEMB(sa, memb) ((sa)->bt_##memb)
406 #define _BT_SCO_MEMB(sa, memb) ((sa)->bt_##memb)
408 #define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb)
409 #define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb)
410 #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
411 #define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)
416 /* TCP/IP Services for VMS uses a maximum send/recv buffer length */
417 #define SEGMENT_SIZE (32 * 1024 -1)
420 #define SAS2SA(x) ((struct sockaddr *)(x))
423 * Constants for getnameinfo()
425 #if !defined(NI_MAXHOST)
426 #define NI_MAXHOST 1025
428 #if !defined(NI_MAXSERV)
429 #define NI_MAXSERV 32
432 /* XXX There's a problem here: *static* functions are not supposed to have
433 a Py prefix (or use CapitalizedWords). Later... */
435 /* Global variable holding the exception type for errors detected
436 by this module (but not argument type or memory errors, etc.). */
437 static PyObject *socket_error;
438 static PyObject *socket_herror;
439 static PyObject *socket_gaierror;
440 static PyObject *socket_timeout;
443 /* Global variable which is !=0 if Python is running in a RISC OS taskwindow */
444 static int taskwindow;
447 /* A forward reference to the socket type object.
448 The sock_type variable contains pointers to various functions,
449 some of which call new_sockobject(), which uses sock_type, so
450 there has to be a circular reference. */
451 static PyTypeObject sock_type;
453 #if defined(HAVE_POLL_H)
455 #elif defined(HAVE_SYS_POLL_H)
456 #include <sys/poll.h>
460 /* Instead of select(), we'll use poll() since poll() works on any fd. */
461 #define IS_SELECTABLE(s) 1
462 /* Can we call select() with this socket without a buffer overrun? */
464 /* If there's no timeout left, we don't have to call select, so it's a safe,
465 * little white lie. */
466 #define IS_SELECTABLE(s) (_PyIsSelectable_fd((s)->sock_fd) || (s)->sock_timeout <= 0.0)
472 PyErr_SetString(socket_error, "unable to select on socket");
476 /* Convenience function to raise an error according to errno
477 and return a NULL pointer from a function. */
483 int err_no = WSAGetLastError();
484 /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which
485 recognizes the error codes used by both GetLastError() and
488 return PyErr_SetExcFromWindowsErr(socket_error, err_no);
491 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
492 if (sock_errno() != NO_ERROR) {
496 int myerrorcode = sock_errno();
498 /* Retrieve socket-related error message from MPTN.MSG file */
499 rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf),
500 myerrorcode - SOCBASEERR + 26,
503 if (rc == NO_ERROR) {
506 /* OS/2 doesn't guarantee a terminator */
507 outbuf[msglen] = '\0';
508 if (strlen(outbuf) > 0) {
509 /* If non-empty msg, trim CRLF */
510 char *lastc = &outbuf[ strlen(outbuf)-1 ];
511 while (lastc > outbuf &&
512 isspace(Py_CHARMASK(*lastc))) {
513 /* Trim trailing whitespace (CRLF) */
517 v = Py_BuildValue("(is)", myerrorcode, outbuf);
519 PyErr_SetObject(socket_error, v);
528 if (_inet_error.errnum != NULL) {
530 v = Py_BuildValue("(is)", errno, _inet_err());
532 PyErr_SetObject(socket_error, v);
539 return PyErr_SetFromErrno(socket_error);
544 set_herror(int h_error)
548 #ifdef HAVE_HSTRERROR
549 v = Py_BuildValue("(is)", h_error, (char *)hstrerror(h_error));
551 v = Py_BuildValue("(is)", h_error, "host not found");
554 PyErr_SetObject(socket_herror, v);
563 set_gaierror(int error)
568 /* EAI_SYSTEM is not available on Windows XP. */
569 if (error == EAI_SYSTEM)
573 #ifdef HAVE_GAI_STRERROR
574 v = Py_BuildValue("(is)", error, gai_strerror(error));
576 v = Py_BuildValue("(is)", error, "getaddrinfo failed");
579 PyErr_SetObject(socket_gaierror, v);
587 /* Function to send in segments */
589 sendsegmented(int sock_fd, char *buf, int len, int flags)
594 while (remaining > 0) {
595 unsigned int segment;
597 segment = (remaining >= SEGMENT_SIZE ? SEGMENT_SIZE : remaining);
598 n = send(sock_fd, buf, segment, flags);
602 remaining -= segment;
610 /* Function to perform the setting of socket blocking mode
611 internally. block = (1 | 0). */
613 internal_setblocking(PySocketSockObject *s, int block)
621 Py_BEGIN_ALLOW_THREADS
624 setsockopt(s->sock_fd, SOL_SOCKET, SO_NONBLOCK,
625 (void *)(&block), sizeof(int));
629 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
631 ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block));
634 ioctl(s->sock_fd, FIONBIO, (unsigned int *)&block);
635 #else /* !PYOS_OS2 && !__VMS */
636 delay_flag = fcntl(s->sock_fd, F_GETFL, 0);
638 delay_flag &= (~O_NONBLOCK);
640 delay_flag |= O_NONBLOCK;
641 fcntl(s->sock_fd, F_SETFL, delay_flag);
642 #endif /* !PYOS_OS2 */
643 #else /* MS_WINDOWS */
645 ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
646 #endif /* MS_WINDOWS */
649 socketioctl(s->sock_fd, FIONBIO, (u_long*)&block);
651 #endif /* __BEOS__ */
654 /* Since these don't return anything */
658 /* Do a select()/poll() on the socket, if necessary (sock_timeout > 0).
659 The argument writing indicates the direction.
660 This does not raise an exception; we'll let our caller do that
661 after they've reacquired the interpreter lock.
662 Returns 1 on timeout, -1 on error, 0 otherwise. */
664 internal_select(PySocketSockObject *s, int writing)
668 /* Nothing to do unless we're in timeout mode (not non-blocking) */
669 if (s->sock_timeout <= 0.0)
672 /* Guard against closed socket */
676 /* Prefer poll, if available, since you can poll() any fd
677 * which can't be done with select(). */
680 struct pollfd pollfd;
683 pollfd.fd = s->sock_fd;
684 pollfd.events = writing ? POLLOUT : POLLIN;
686 /* s->sock_timeout is in seconds, timeout in ms */
687 timeout = (int)(s->sock_timeout * 1000 + 0.5);
688 n = poll(&pollfd, 1, timeout);
692 /* Construct the arguments to select */
695 tv.tv_sec = (int)s->sock_timeout;
696 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
698 FD_SET(s->sock_fd, &fds);
700 /* See if the socket is ready */
702 n = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
704 n = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
715 /* Initialize a new socket object. */
717 static double defaulttimeout = -1.0; /* Default timeout for new sockets */
720 init_sockobject(PySocketSockObject *s,
721 SOCKET_T fd, int family, int type, int proto)
727 s->sock_family = family;
729 s->sock_proto = proto;
730 s->sock_timeout = defaulttimeout;
732 s->errorhandler = &set_error;
734 if (defaulttimeout >= 0.0)
735 internal_setblocking(s, 0);
739 socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
744 /* Create a new socket object.
745 This just creates the object and initializes it.
746 If the creation fails, return NULL and set an exception (implicit
749 static PySocketSockObject *
750 new_sockobject(SOCKET_T fd, int family, int type, int proto)
752 PySocketSockObject *s;
753 s = (PySocketSockObject *)
754 PyType_GenericNew(&sock_type, NULL, NULL);
756 init_sockobject(s, fd, family, type, proto);
761 /* Lock to allow python interpreter to continue, but only allow one
762 thread to be in gethostbyname or getaddrinfo */
763 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
764 PyThread_type_lock netdb_lock;
768 /* Convert a string specifying a host name or one of a few symbolic
769 names to a numeric IP address. This usually calls gethostbyname()
770 to do the work; the names "" and "<broadcast>" are special.
771 Return the length (IPv4 should be 4 bytes), or negative if
772 an error occurred; then an exception is raised. */
775 setipaddr(char *name, struct sockaddr *addr_ret, size_t addr_ret_size, int af)
777 struct addrinfo hints, *res;
782 memset((void *) addr_ret, '\0', sizeof(*addr_ret));
783 if (name[0] == '\0') {
785 memset(&hints, 0, sizeof(hints));
786 hints.ai_family = af;
787 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
788 hints.ai_flags = AI_PASSIVE;
789 Py_BEGIN_ALLOW_THREADS
790 ACQUIRE_GETADDRINFO_LOCK
791 error = getaddrinfo(NULL, "0", &hints, &res);
793 /* We assume that those thread-unsafe getaddrinfo() versions
794 *are* safe regarding their return value, ie. that a
795 subsequent call to getaddrinfo() does not destroy the
796 outcome of the first call. */
797 RELEASE_GETADDRINFO_LOCK
802 switch (res->ai_family) {
813 PyErr_SetString(socket_error,
814 "unsupported address family");
819 PyErr_SetString(socket_error,
820 "wildcard resolved to multiple address");
823 if (res->ai_addrlen < addr_ret_size)
824 addr_ret_size = res->ai_addrlen;
825 memcpy(addr_ret, res->ai_addr, addr_ret_size);
829 if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
830 struct sockaddr_in *sin;
831 if (af != AF_INET && af != AF_UNSPEC) {
832 PyErr_SetString(socket_error,
833 "address family mismatched");
836 sin = (struct sockaddr_in *)addr_ret;
837 memset((void *) sin, '\0', sizeof(*sin));
838 sin->sin_family = AF_INET;
839 #ifdef HAVE_SOCKADDR_SA_LEN
840 sin->sin_len = sizeof(*sin);
842 sin->sin_addr.s_addr = INADDR_BROADCAST;
843 return sizeof(sin->sin_addr);
845 if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 &&
846 0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 &&
847 0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) {
848 struct sockaddr_in *sin;
849 sin = (struct sockaddr_in *)addr_ret;
850 sin->sin_addr.s_addr = htonl(
851 ((long) d1 << 24) | ((long) d2 << 16) |
852 ((long) d3 << 8) | ((long) d4 << 0));
853 sin->sin_family = AF_INET;
854 #ifdef HAVE_SOCKADDR_SA_LEN
855 sin->sin_len = sizeof(*sin);
859 memset(&hints, 0, sizeof(hints));
860 hints.ai_family = af;
861 Py_BEGIN_ALLOW_THREADS
862 ACQUIRE_GETADDRINFO_LOCK
863 error = getaddrinfo(name, NULL, &hints, &res);
864 #if defined(__digital__) && defined(__unix__)
865 if (error == EAI_NONAME && af == AF_UNSPEC) {
866 /* On Tru64 V5.1, numeric-to-addr conversion fails
867 if no address family is given. Assume IPv4 for now.*/
868 hints.ai_family = AF_INET;
869 error = getaddrinfo(name, NULL, &hints, &res);
873 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
878 if (res->ai_addrlen < addr_ret_size)
879 addr_ret_size = res->ai_addrlen;
880 memcpy((char *) addr_ret, res->ai_addr, addr_ret_size);
882 switch (addr_ret->sa_family) {
890 PyErr_SetString(socket_error, "unknown address family");
896 /* Create a string object representing an IP address.
897 This is always a string of the form 'dd.dd.dd.dd' (with variable
901 makeipaddr(struct sockaddr *addr, int addrlen)
903 char buf[NI_MAXHOST];
906 error = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0,
912 return PyString_FromString(buf);
917 /* Convert a string representation of a Bluetooth address into a numeric
918 address. Returns the length (6), or raises an exception and returns -1 if
919 an error occurred. */
922 setbdaddr(char *name, bdaddr_t *bdaddr)
924 unsigned int b0, b1, b2, b3, b4, b5;
928 n = sscanf(name, "%X:%X:%X:%X:%X:%X%c",
929 &b5, &b4, &b3, &b2, &b1, &b0, &ch);
930 if (n == 6 && (b0 | b1 | b2 | b3 | b4 | b5) < 256) {
939 PyErr_SetString(socket_error, "bad bluetooth address");
944 /* Create a string representation of the Bluetooth address. This is always a
945 string of the form 'XX:XX:XX:XX:XX:XX' where XX is a two digit hexadecimal
946 value (zero padded if necessary). */
949 makebdaddr(bdaddr_t *bdaddr)
951 char buf[(6 * 2) + 5 + 1];
953 sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
954 bdaddr->b[5], bdaddr->b[4], bdaddr->b[3],
955 bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]);
956 return PyString_FromString(buf);
961 /* Create an object representing the given socket address,
962 suitable for passing it back to bind(), connect() etc.
963 The family field of the sockaddr structure is inspected
964 to determine what kind of address it really is. */
968 makesockaddr(int sockfd, struct sockaddr *addr, int addrlen, int proto)
971 /* No address -- may be recvfrom() from known socket */
977 /* XXX: BeOS version of accept() doesn't set family correctly */
978 addr->sa_family = AF_INET;
981 switch (addr->sa_family) {
985 struct sockaddr_in *a;
986 PyObject *addrobj = makeipaddr(addr, sizeof(*a));
987 PyObject *ret = NULL;
989 a = (struct sockaddr_in *)addr;
990 ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
999 struct sockaddr_un *a = (struct sockaddr_un *) addr;
1001 if (a->sun_path[0] == 0) { /* Linux abstract namespace */
1002 addrlen -= offsetof(struct sockaddr_un, sun_path);
1003 return PyString_FromStringAndSize(a->sun_path,
1009 /* regular NULL-terminated string */
1010 return PyString_FromString(a->sun_path);
1013 #endif /* AF_UNIX */
1015 #if defined(AF_NETLINK)
1018 struct sockaddr_nl *a = (struct sockaddr_nl *) addr;
1019 return Py_BuildValue("II", a->nl_pid, a->nl_groups);
1021 #endif /* AF_NETLINK */
1026 struct sockaddr_in6 *a;
1027 PyObject *addrobj = makeipaddr(addr, sizeof(*a));
1028 PyObject *ret = NULL;
1030 a = (struct sockaddr_in6 *)addr;
1031 ret = Py_BuildValue("OiII",
1033 ntohs(a->sin6_port),
1034 ntohl(a->sin6_flowinfo),
1042 #ifdef USE_BLUETOOTH
1048 struct sockaddr_l2 *a = (struct sockaddr_l2 *) addr;
1049 PyObject *addrobj = makebdaddr(&_BT_L2_MEMB(a, bdaddr));
1050 PyObject *ret = NULL;
1052 ret = Py_BuildValue("Oi",
1054 _BT_L2_MEMB(a, psm));
1060 case BTPROTO_RFCOMM:
1062 struct sockaddr_rc *a = (struct sockaddr_rc *) addr;
1063 PyObject *addrobj = makebdaddr(&_BT_RC_MEMB(a, bdaddr));
1064 PyObject *ret = NULL;
1066 ret = Py_BuildValue("Oi",
1068 _BT_RC_MEMB(a, channel));
1076 struct sockaddr_hci *a = (struct sockaddr_hci *) addr;
1077 #if defined(__NetBSD__) || defined(__DragonFly__)
1078 return makebdaddr(&_BT_HCI_MEMB(a, bdaddr));
1080 PyObject *ret = NULL;
1081 ret = Py_BuildValue("i", _BT_HCI_MEMB(a, dev));
1086 #if !defined(__FreeBSD__)
1089 struct sockaddr_sco *a = (struct sockaddr_sco *) addr;
1090 return makebdaddr(&_BT_SCO_MEMB(a, bdaddr));
1095 PyErr_SetString(PyExc_ValueError,
1096 "Unknown Bluetooth protocol");
1101 #if defined(HAVE_NETPACKET_PACKET_H) && defined(SIOCGIFNAME)
1104 struct sockaddr_ll *a = (struct sockaddr_ll *)addr;
1107 /* need to look up interface name give index */
1108 if (a->sll_ifindex) {
1109 ifr.ifr_ifindex = a->sll_ifindex;
1110 if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0)
1111 ifname = ifr.ifr_name;
1113 return Py_BuildValue("shbhs#",
1115 ntohs(a->sll_protocol),
1123 #ifdef HAVE_LINUX_TIPC_H
1126 struct sockaddr_tipc *a = (struct sockaddr_tipc *) addr;
1127 if (a->addrtype == TIPC_ADDR_NAMESEQ) {
1128 return Py_BuildValue("IIIII",
1130 a->addr.nameseq.type,
1131 a->addr.nameseq.lower,
1132 a->addr.nameseq.upper,
1134 } else if (a->addrtype == TIPC_ADDR_NAME) {
1135 return Py_BuildValue("IIIII",
1137 a->addr.name.name.type,
1138 a->addr.name.name.instance,
1139 a->addr.name.name.instance,
1141 } else if (a->addrtype == TIPC_ADDR_ID) {
1142 return Py_BuildValue("IIIII",
1149 PyErr_SetString(PyExc_ValueError,
1150 "Invalid address type");
1156 /* More cases here... */
1159 /* If we don't know the address family, don't raise an
1160 exception -- return it as a tuple. */
1161 return Py_BuildValue("is#",
1164 sizeof(addr->sa_data));
1170 /* Parse a socket address argument according to the socket object's
1171 address family. Return 1 if the address was in the proper format,
1172 0 of not. The address is returned through addr_ret, its length
1176 getsockaddrarg(PySocketSockObject *s, PyObject *args,
1177 struct sockaddr *addr_ret, int *len_ret)
1179 switch (s->sock_family) {
1181 #if defined(AF_UNIX)
1184 struct sockaddr_un* addr;
1187 if (!PyArg_Parse(args, "t#", &path, &len))
1190 addr = (struct sockaddr_un*)addr_ret;
1192 if (len > 0 && path[0] == 0) {
1193 /* Linux abstract namespace extension */
1194 if (len > sizeof addr->sun_path) {
1195 PyErr_SetString(socket_error,
1196 "AF_UNIX path too long");
1203 /* regular NULL-terminated string */
1204 if (len >= sizeof addr->sun_path) {
1205 PyErr_SetString(socket_error,
1206 "AF_UNIX path too long");
1209 addr->sun_path[len] = 0;
1211 addr->sun_family = s->sock_family;
1212 memcpy(addr->sun_path, path, len);
1213 #if defined(PYOS_OS2)
1214 *len_ret = sizeof(*addr);
1216 *len_ret = len + offsetof(struct sockaddr_un, sun_path);
1220 #endif /* AF_UNIX */
1222 #if defined(AF_NETLINK)
1225 struct sockaddr_nl* addr;
1227 addr = (struct sockaddr_nl *)addr_ret;
1228 if (!PyTuple_Check(args)) {
1232 "AF_NETLINK address must be tuple, not %.500s",
1233 Py_TYPE(args)->tp_name);
1236 if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &pid, &groups))
1238 addr->nl_family = AF_NETLINK;
1240 addr->nl_groups = groups;
1241 *len_ret = sizeof(*addr);
1248 struct sockaddr_in* addr;
1251 if (!PyTuple_Check(args)) {
1255 "AF_INET address must be tuple, not %.500s",
1256 Py_TYPE(args)->tp_name);
1259 if (!PyArg_ParseTuple(args, "eti:getsockaddrarg",
1260 "idna", &host, &port))
1262 addr=(struct sockaddr_in*)addr_ret;
1263 result = setipaddr(host, (struct sockaddr *)addr,
1264 sizeof(*addr), AF_INET);
1268 if (port < 0 || port > 0xffff) {
1270 PyExc_OverflowError,
1271 "getsockaddrarg: port must be 0-65535.");
1274 addr->sin_family = AF_INET;
1275 addr->sin_port = htons((short)port);
1276 *len_ret = sizeof *addr;
1283 struct sockaddr_in6* addr;
1286 unsigned int flowinfo, scope_id;
1287 flowinfo = scope_id = 0;
1288 if (!PyTuple_Check(args)) {
1292 "AF_INET6 address must be tuple, not %.500s",
1293 Py_TYPE(args)->tp_name);
1296 if (!PyArg_ParseTuple(args, "eti|II",
1297 "idna", &host, &port, &flowinfo,
1301 addr = (struct sockaddr_in6*)addr_ret;
1302 result = setipaddr(host, (struct sockaddr *)addr,
1303 sizeof(*addr), AF_INET6);
1307 if (port < 0 || port > 0xffff) {
1309 PyExc_OverflowError,
1310 "getsockaddrarg: port must be 0-65535.");
1313 if (flowinfo < 0 || flowinfo > 0xfffff) {
1315 PyExc_OverflowError,
1316 "getsockaddrarg: flowinfo must be 0-1048575.");
1319 addr->sin6_family = s->sock_family;
1320 addr->sin6_port = htons((short)port);
1321 addr->sin6_flowinfo = htonl(flowinfo);
1322 addr->sin6_scope_id = scope_id;
1323 *len_ret = sizeof *addr;
1328 #ifdef USE_BLUETOOTH
1331 switch (s->sock_proto) {
1334 struct sockaddr_l2 *addr;
1337 addr = (struct sockaddr_l2 *)addr_ret;
1338 memset(addr, 0, sizeof(struct sockaddr_l2));
1339 _BT_L2_MEMB(addr, family) = AF_BLUETOOTH;
1340 if (!PyArg_ParseTuple(args, "si", &straddr,
1341 &_BT_L2_MEMB(addr, psm))) {
1342 PyErr_SetString(socket_error, "getsockaddrarg: "
1346 if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0)
1349 *len_ret = sizeof *addr;
1352 case BTPROTO_RFCOMM:
1354 struct sockaddr_rc *addr;
1357 addr = (struct sockaddr_rc *)addr_ret;
1358 _BT_RC_MEMB(addr, family) = AF_BLUETOOTH;
1359 if (!PyArg_ParseTuple(args, "si", &straddr,
1360 &_BT_RC_MEMB(addr, channel))) {
1361 PyErr_SetString(socket_error, "getsockaddrarg: "
1365 if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0)
1368 *len_ret = sizeof *addr;
1373 struct sockaddr_hci *addr = (struct sockaddr_hci *)addr_ret;
1374 #if defined(__NetBSD__) || defined(__DragonFly__)
1375 char *straddr = PyBytes_AS_STRING(args);
1377 _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH;
1378 if (straddr == NULL) {
1379 PyErr_SetString(socket_error, "getsockaddrarg: "
1383 if (setbdaddr(straddr, &_BT_HCI_MEMB(addr, bdaddr)) < 0)
1386 _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH;
1387 if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) {
1388 PyErr_SetString(socket_error, "getsockaddrarg: "
1393 *len_ret = sizeof *addr;
1396 #if !defined(__FreeBSD__)
1399 struct sockaddr_sco *addr;
1402 addr = (struct sockaddr_sco *)addr_ret;
1403 _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH;
1404 straddr = PyString_AsString(args);
1405 if (straddr == NULL) {
1406 PyErr_SetString(socket_error, "getsockaddrarg: "
1410 if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0)
1413 *len_ret = sizeof *addr;
1418 PyErr_SetString(socket_error, "getsockaddrarg: unknown Bluetooth protocol");
1424 #if defined(HAVE_NETPACKET_PACKET_H) && defined(SIOCGIFINDEX)
1427 struct sockaddr_ll* addr;
1429 char *interfaceName;
1434 unsigned int halen = 0;
1436 if (!PyTuple_Check(args)) {
1440 "AF_PACKET address must be tuple, not %.500s",
1441 Py_TYPE(args)->tp_name);
1444 if (!PyArg_ParseTuple(args, "si|iis#", &interfaceName,
1445 &protoNumber, &pkttype, &hatype,
1448 strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name));
1449 ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
1450 if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
1455 PyErr_SetString(PyExc_ValueError,
1456 "Hardware address must be 8 bytes or less");
1459 if (protoNumber < 0 || protoNumber > 0xffff) {
1461 PyExc_OverflowError,
1462 "getsockaddrarg: protoNumber must be 0-65535.");
1465 addr = (struct sockaddr_ll*)addr_ret;
1466 addr->sll_family = AF_PACKET;
1467 addr->sll_protocol = htons((short)protoNumber);
1468 addr->sll_ifindex = ifr.ifr_ifindex;
1469 addr->sll_pkttype = pkttype;
1470 addr->sll_hatype = hatype;
1472 memcpy(&addr->sll_addr, haddr, halen);
1474 addr->sll_halen = halen;
1475 *len_ret = sizeof *addr;
1480 #ifdef HAVE_LINUX_TIPC_H
1483 unsigned int atype, v1, v2, v3;
1484 unsigned int scope = TIPC_CLUSTER_SCOPE;
1485 struct sockaddr_tipc *addr;
1487 if (!PyTuple_Check(args)) {
1491 "AF_TIPC address must be tuple, not %.500s",
1492 Py_TYPE(args)->tp_name);
1496 if (!PyArg_ParseTuple(args,
1497 "IIII|I;Invalid TIPC address format",
1498 &atype, &v1, &v2, &v3, &scope))
1501 addr = (struct sockaddr_tipc *) addr_ret;
1502 memset(addr, 0, sizeof(struct sockaddr_tipc));
1504 addr->family = AF_TIPC;
1505 addr->scope = scope;
1506 addr->addrtype = atype;
1508 if (atype == TIPC_ADDR_NAMESEQ) {
1509 addr->addr.nameseq.type = v1;
1510 addr->addr.nameseq.lower = v2;
1511 addr->addr.nameseq.upper = v3;
1512 } else if (atype == TIPC_ADDR_NAME) {
1513 addr->addr.name.name.type = v1;
1514 addr->addr.name.name.instance = v2;
1515 } else if (atype == TIPC_ADDR_ID) {
1516 addr->addr.id.node = v1;
1517 addr->addr.id.ref = v2;
1519 /* Shouldn't happen */
1520 PyErr_SetString(PyExc_TypeError, "Invalid address type");
1524 *len_ret = sizeof(*addr);
1530 /* More cases here... */
1533 PyErr_SetString(socket_error, "getsockaddrarg: bad family");
1540 /* Get the address length according to the socket object's address family.
1541 Return 1 if the family is known, 0 otherwise. The length is returned
1545 getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
1547 switch (s->sock_family) {
1549 #if defined(AF_UNIX)
1552 *len_ret = sizeof (struct sockaddr_un);
1555 #endif /* AF_UNIX */
1556 #if defined(AF_NETLINK)
1559 *len_ret = sizeof (struct sockaddr_nl);
1566 *len_ret = sizeof (struct sockaddr_in);
1573 *len_ret = sizeof (struct sockaddr_in6);
1578 #ifdef USE_BLUETOOTH
1581 switch(s->sock_proto)
1585 *len_ret = sizeof (struct sockaddr_l2);
1587 case BTPROTO_RFCOMM:
1588 *len_ret = sizeof (struct sockaddr_rc);
1591 *len_ret = sizeof (struct sockaddr_hci);
1593 #if !defined(__FreeBSD__)
1595 *len_ret = sizeof (struct sockaddr_sco);
1599 PyErr_SetString(socket_error, "getsockaddrlen: "
1600 "unknown BT protocol");
1607 #ifdef HAVE_NETPACKET_PACKET_H
1610 *len_ret = sizeof (struct sockaddr_ll);
1615 #ifdef HAVE_LINUX_TIPC_H
1618 *len_ret = sizeof (struct sockaddr_tipc);
1623 /* More cases here... */
1626 PyErr_SetString(socket_error, "getsockaddrlen: bad family");
1633 /* s.accept() method */
1636 sock_accept(PySocketSockObject *s)
1638 sock_addr_t addrbuf;
1641 PyObject *sock = NULL;
1642 PyObject *addr = NULL;
1643 PyObject *res = NULL;
1646 if (!getsockaddrlen(s, &addrlen))
1648 memset(&addrbuf, 0, addrlen);
1651 newfd = INVALID_SOCKET;
1656 if (!IS_SELECTABLE(s))
1657 return select_error();
1659 Py_BEGIN_ALLOW_THREADS
1660 timeout = internal_select(s, 0);
1662 newfd = accept(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
1663 Py_END_ALLOW_THREADS
1666 PyErr_SetString(socket_timeout, "timed out");
1671 if (newfd == INVALID_SOCKET)
1675 return s->errorhandler();
1677 /* Create the new object with unspecified family,
1678 to avoid calls to bind() etc. on it. */
1679 sock = (PyObject *) new_sockobject(newfd,
1688 addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
1689 addrlen, s->sock_proto);
1693 res = PyTuple_Pack(2, sock, addr);
1701 PyDoc_STRVAR(accept_doc,
1702 "accept() -> (socket object, address info)\n\
1704 Wait for an incoming connection. Return a new socket representing the\n\
1705 connection, and the address of the client. For IP sockets, the address\n\
1706 info is a pair (hostaddr, port).");
1708 /* s.setblocking(flag) method. Argument:
1709 False -- non-blocking mode; same as settimeout(0)
1710 True -- blocking mode; same as settimeout(None)
1714 sock_setblocking(PySocketSockObject *s, PyObject *arg)
1718 block = PyInt_AsLong(arg);
1719 if (block == -1 && PyErr_Occurred())
1722 s->sock_timeout = block ? -1.0 : 0.0;
1723 internal_setblocking(s, block);
1729 PyDoc_STRVAR(setblocking_doc,
1730 "setblocking(flag)\n\
1732 Set the socket to blocking (flag is true) or non-blocking (false).\n\
1733 setblocking(True) is equivalent to settimeout(None);\n\
1734 setblocking(False) is equivalent to settimeout(0.0).");
1736 /* s.settimeout(timeout) method. Argument:
1737 None -- no timeout, blocking mode; same as setblocking(True)
1738 0.0 -- non-blocking mode; same as setblocking(False)
1739 > 0 -- timeout mode; operations time out after timeout seconds
1740 < 0 -- illegal; raises an exception
1743 sock_settimeout(PySocketSockObject *s, PyObject *arg)
1750 timeout = PyFloat_AsDouble(arg);
1751 if (timeout < 0.0) {
1752 if (!PyErr_Occurred())
1753 PyErr_SetString(PyExc_ValueError,
1754 "Timeout value out of range");
1759 s->sock_timeout = timeout;
1760 internal_setblocking(s, timeout < 0.0);
1766 PyDoc_STRVAR(settimeout_doc,
1767 "settimeout(timeout)\n\
1769 Set a timeout on socket operations. 'timeout' can be a float,\n\
1770 giving in seconds, or None. Setting a timeout of None disables\n\
1771 the timeout feature and is equivalent to setblocking(1).\n\
1772 Setting a timeout of zero is the same as setblocking(0).");
1774 /* s.gettimeout() method.
1775 Returns the timeout associated with a socket. */
1777 sock_gettimeout(PySocketSockObject *s)
1779 if (s->sock_timeout < 0.0) {
1784 return PyFloat_FromDouble(s->sock_timeout);
1787 PyDoc_STRVAR(gettimeout_doc,
1788 "gettimeout() -> timeout\n\
1790 Returns the timeout in seconds (float) associated with socket \n\
1791 operations. A timeout of None indicates that timeouts on socket \n\
1792 operations are disabled.");
1795 /* s.sleeptaskw(1 | 0) method */
1798 sock_sleeptaskw(PySocketSockObject *s,PyObject *arg)
1801 block = PyInt_AsLong(arg);
1802 if (block == -1 && PyErr_Occurred())
1804 Py_BEGIN_ALLOW_THREADS
1805 socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
1806 Py_END_ALLOW_THREADS
1811 PyDoc_STRVAR(sleeptaskw_doc,
1812 "sleeptaskw(flag)\n\
1814 Allow sleeps in taskwindows.");
1818 /* s.setsockopt() method.
1819 With an integer third argument, sets an integer option.
1820 With a string third argument, sets an option from a buffer;
1821 use optional built-in module 'struct' to encode the string. */
1824 sock_setsockopt(PySocketSockObject *s, PyObject *args)
1833 if (PyArg_ParseTuple(args, "iii:setsockopt",
1834 &level, &optname, &flag)) {
1835 buf = (char *) &flag;
1836 buflen = sizeof flag;
1840 if (!PyArg_ParseTuple(args, "iis#:setsockopt",
1841 &level, &optname, &buf, &buflen))
1844 res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen);
1846 return s->errorhandler();
1851 PyDoc_STRVAR(setsockopt_doc,
1852 "setsockopt(level, option, value)\n\
1854 Set a socket option. See the Unix manual for level and option.\n\
1855 The value argument can either be an integer or a string.");
1858 /* s.getsockopt() method.
1859 With two arguments, retrieves an integer option.
1860 With a third integer argument, retrieves a string buffer of that size;
1861 use optional built-in module 'struct' to decode the string. */
1864 sock_getsockopt(PySocketSockObject *s, PyObject *args)
1870 socklen_t buflen = 0;
1873 /* We have incomplete socket support. */
1874 PyErr_SetString(socket_error, "getsockopt not supported");
1878 if (!PyArg_ParseTuple(args, "ii|i:getsockopt",
1879 &level, &optname, &buflen))
1884 socklen_t flagsize = sizeof flag;
1885 res = getsockopt(s->sock_fd, level, optname,
1886 (void *)&flag, &flagsize);
1888 return s->errorhandler();
1889 return PyInt_FromLong(flag);
1892 /* socklen_t is unsigned so no negative test is needed,
1893 test buflen == 0 is previously done */
1894 if (buflen > 1024) {
1896 if (buflen <= 0 || buflen > 1024) {
1898 PyErr_SetString(socket_error,
1899 "getsockopt buflen out of range");
1902 buf = PyString_FromStringAndSize((char *)NULL, buflen);
1905 res = getsockopt(s->sock_fd, level, optname,
1906 (void *)PyString_AS_STRING(buf), &buflen);
1909 return s->errorhandler();
1911 _PyString_Resize(&buf, buflen);
1913 #endif /* __BEOS__ */
1916 PyDoc_STRVAR(getsockopt_doc,
1917 "getsockopt(level, option[, buffersize]) -> value\n\
1919 Get a socket option. See the Unix manual for level and option.\n\
1920 If a nonzero buffersize argument is given, the return value is a\n\
1921 string of that length; otherwise it is an integer.");
1924 /* s.bind(sockaddr) method */
1927 sock_bind(PySocketSockObject *s, PyObject *addro)
1929 sock_addr_t addrbuf;
1933 if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
1935 Py_BEGIN_ALLOW_THREADS
1936 res = bind(s->sock_fd, SAS2SA(&addrbuf), addrlen);
1937 Py_END_ALLOW_THREADS
1939 return s->errorhandler();
1944 PyDoc_STRVAR(bind_doc,
1947 Bind the socket to a local address. For IP sockets, the address is a\n\
1948 pair (host, port); the host must refer to the local host. For raw packet\n\
1949 sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");
1952 /* s.close() method.
1953 Set the file descriptor to -1 so operations tried subsequently
1954 will surely fail. */
1957 sock_close(PySocketSockObject *s)
1961 if ((fd = s->sock_fd) != -1) {
1963 Py_BEGIN_ALLOW_THREADS
1964 (void) SOCKETCLOSE(fd);
1965 Py_END_ALLOW_THREADS
1971 PyDoc_STRVAR(close_doc,
1974 Close the socket. It cannot be used after this call.");
1977 internal_connect(PySocketSockObject *s, struct sockaddr *addr, int addrlen,
1983 res = connect(s->sock_fd, addr, addrlen);
1987 if (s->sock_timeout > 0.0) {
1988 if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK &&
1990 /* This is a mess. Best solution: trust select */
1994 tv.tv_sec = (int)s->sock_timeout;
1995 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1997 FD_SET(s->sock_fd, &fds);
1999 FD_SET(s->sock_fd, &fds_exc);
2000 res = select(s->sock_fd+1, NULL, &fds, &fds_exc, &tv);
2002 res = WSAEWOULDBLOCK;
2004 } else if (res > 0) {
2005 if (FD_ISSET(s->sock_fd, &fds))
2006 /* The socket is in the writeable set - this
2010 /* As per MS docs, we need to call getsockopt()
2011 to get the underlying error */
2012 int res_size = sizeof res;
2013 /* It must be in the exception set */
2014 assert(FD_ISSET(s->sock_fd, &fds_exc));
2015 if (0 == getsockopt(s->sock_fd, SOL_SOCKET, SO_ERROR,
2016 (char *)&res, &res_size))
2017 /* getsockopt also clears WSAGetLastError,
2018 so reset it back. */
2019 WSASetLastError(res);
2021 res = WSAGetLastError();
2024 /* else if (res < 0) an error occurred */
2029 res = WSAGetLastError();
2033 if (s->sock_timeout > 0.0) {
2034 if (res < 0 && errno == EINPROGRESS && IS_SELECTABLE(s)) {
2035 timeout = internal_select(s, 1);
2037 /* Bug #1019808: in case of an EINPROGRESS,
2038 use getsockopt(SO_ERROR) to get the real
2040 socklen_t res_size = sizeof res;
2041 (void)getsockopt(s->sock_fd, SOL_SOCKET,
2042 SO_ERROR, &res, &res_size);
2047 else if (timeout == -1) {
2048 res = errno; /* had error */
2051 res = EWOULDBLOCK; /* timed out */
2059 *timeoutp = timeout;
2064 /* s.connect(sockaddr) method */
2067 sock_connect(PySocketSockObject *s, PyObject *addro)
2069 sock_addr_t addrbuf;
2074 if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
2077 Py_BEGIN_ALLOW_THREADS
2078 res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
2079 Py_END_ALLOW_THREADS
2082 PyErr_SetString(socket_timeout, "timed out");
2086 return s->errorhandler();
2091 PyDoc_STRVAR(connect_doc,
2092 "connect(address)\n\
2094 Connect the socket to a remote address. For IP sockets, the address\n\
2095 is a pair (host, port).");
2098 /* s.connect_ex(sockaddr) method */
2101 sock_connect_ex(PySocketSockObject *s, PyObject *addro)
2103 sock_addr_t addrbuf;
2108 if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
2111 Py_BEGIN_ALLOW_THREADS
2112 res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
2113 Py_END_ALLOW_THREADS
2115 /* Signals are not errors (though they may raise exceptions). Adapted
2116 from PyErr_SetFromErrnoWithFilenameObject(). */
2118 if (res == EINTR && PyErr_CheckSignals())
2122 return PyInt_FromLong((long) res);
2125 PyDoc_STRVAR(connect_ex_doc,
2126 "connect_ex(address) -> errno\n\
2128 This is like connect(address), but returns an error code (the errno value)\n\
2129 instead of raising an exception when an error occurs.");
2132 /* s.fileno() method */
2135 sock_fileno(PySocketSockObject *s)
2137 #if SIZEOF_SOCKET_T <= SIZEOF_LONG
2138 return PyInt_FromLong((long) s->sock_fd);
2140 return PyLong_FromLongLong((PY_LONG_LONG)s->sock_fd);
2144 PyDoc_STRVAR(fileno_doc,
2145 "fileno() -> integer\n\
2147 Return the integer file descriptor of the socket.");
2151 /* s.dup() method */
2154 sock_dup(PySocketSockObject *s)
2159 newfd = dup(s->sock_fd);
2161 return s->errorhandler();
2162 sock = (PyObject *) new_sockobject(newfd,
2171 PyDoc_STRVAR(dup_doc,
2172 "dup() -> socket object\n\
2174 Return a new socket object connected to the same system resource.");
2179 /* s.getsockname() method */
2182 sock_getsockname(PySocketSockObject *s)
2184 sock_addr_t addrbuf;
2188 if (!getsockaddrlen(s, &addrlen))
2190 memset(&addrbuf, 0, addrlen);
2191 Py_BEGIN_ALLOW_THREADS
2192 res = getsockname(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
2193 Py_END_ALLOW_THREADS
2195 return s->errorhandler();
2196 return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
2200 PyDoc_STRVAR(getsockname_doc,
2201 "getsockname() -> address info\n\
2203 Return the address of the local endpoint. For IP sockets, the address\n\
2204 info is a pair (hostaddr, port).");
2207 #ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
2208 /* s.getpeername() method */
2211 sock_getpeername(PySocketSockObject *s)
2213 sock_addr_t addrbuf;
2217 if (!getsockaddrlen(s, &addrlen))
2219 memset(&addrbuf, 0, addrlen);
2220 Py_BEGIN_ALLOW_THREADS
2221 res = getpeername(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
2222 Py_END_ALLOW_THREADS
2224 return s->errorhandler();
2225 return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
2229 PyDoc_STRVAR(getpeername_doc,
2230 "getpeername() -> address info\n\
2232 Return the address of the remote endpoint. For IP sockets, the address\n\
2233 info is a pair (hostaddr, port).");
2235 #endif /* HAVE_GETPEERNAME */
2238 /* s.listen(n) method */
2241 sock_listen(PySocketSockObject *s, PyObject *arg)
2246 backlog = PyInt_AsLong(arg);
2247 if (backlog == -1 && PyErr_Occurred())
2249 Py_BEGIN_ALLOW_THREADS
2250 /* To avoid problems on systems that don't allow a negative backlog
2251 * (which doesn't make sense anyway) we force a minimum value of 0. */
2254 res = listen(s->sock_fd, backlog);
2255 Py_END_ALLOW_THREADS
2257 return s->errorhandler();
2262 PyDoc_STRVAR(listen_doc,
2265 Enable a server to accept connections. The backlog argument must be at\n\
2266 least 0 (if it is lower, it is set to 0); it specifies the number of\n\
2267 unaccepted connections that the system will allow before refusing new\n\
2272 /* s.makefile(mode) method.
2273 Create a new open file object referring to a dupped version of
2274 the socket's file descriptor. (The dup() call is necessary so
2275 that the open file and socket objects may be closed independent
2277 The mode argument specifies 'r' or 'w' passed to fdopen(). */
2280 sock_makefile(PySocketSockObject *s, PyObject *args)
2282 extern int fclose(FILE *);
2297 if (!PyArg_ParseTuple(args, "|si:makefile", &mode, &bufsize))
2300 if (strcmp(mode,"rb") == 0) {
2304 if (strcmp(mode,"wb") == 0) {
2310 if (((fd = _open_osfhandle(s->sock_fd, _O_BINARY)) < 0) ||
2311 ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL))
2313 if ((fd = dup(s->sock_fd)) < 0 || (fp = fdopen(fd, mode)) == NULL)
2318 return s->errorhandler();
2320 f = PyFile_FromFile(fp, "<socket>", mode, fclose);
2322 PyFile_SetBufSize(f, bufsize);
2326 PyDoc_STRVAR(makefile_doc,
2327 "makefile([mode[, buffersize]]) -> file object\n\
2329 Return a regular file object corresponding to the socket.\n\
2330 The mode and buffersize arguments are as for the built-in open() function.");
2335 * This is the guts of the recv() and recv_into() methods, which reads into a
2336 * char buffer. If you have any inc/dec ref to do to the objects that contain
2337 * the buffer, do it in the caller. This function returns the number of bytes
2338 * successfully read. If there was an error, it returns -1. Note that it is
2339 * also possible that we return a number of bytes smaller than the request
2343 sock_recv_guts(PySocketSockObject *s, char* cbuf, int len, int flags)
2345 ssize_t outlen = -1;
2352 if (!IS_SELECTABLE(s)) {
2358 Py_BEGIN_ALLOW_THREADS
2359 timeout = internal_select(s, 0);
2361 outlen = recv(s->sock_fd, cbuf, len, flags);
2362 Py_END_ALLOW_THREADS
2365 PyErr_SetString(socket_timeout, "timed out");
2369 /* Note: the call to errorhandler() ALWAYS indirectly returned
2370 NULL, so ignore its return value */
2377 while (remaining != 0) {
2378 unsigned int segment;
2381 segment = remaining /SEGMENT_SIZE;
2383 segment = SEGMENT_SIZE;
2386 segment = remaining;
2389 Py_BEGIN_ALLOW_THREADS
2390 timeout = internal_select(s, 0);
2392 nread = recv(s->sock_fd, read_buf, segment, flags);
2393 Py_END_ALLOW_THREADS
2396 PyErr_SetString(socket_timeout, "timed out");
2403 if (nread != remaining) {
2408 remaining -= segment;
2409 read_buf += segment;
2411 outlen = read_buf - cbuf;
2418 /* s.recv(nbytes [,flags]) method */
2421 sock_recv(PySocketSockObject *s, PyObject *args)
2423 int recvlen, flags = 0;
2427 if (!PyArg_ParseTuple(args, "i|i:recv", &recvlen, &flags))
2431 PyErr_SetString(PyExc_ValueError,
2432 "negative buffersize in recv");
2436 /* Allocate a new string. */
2437 buf = PyString_FromStringAndSize((char *) 0, recvlen);
2442 outlen = sock_recv_guts(s, PyString_AS_STRING(buf), recvlen, flags);
2444 /* An error occurred, release the string and return an
2449 if (outlen != recvlen) {
2450 /* We did not read as many bytes as we anticipated, resize the
2451 string if possible and be successful. */
2452 if (_PyString_Resize(&buf, outlen) < 0)
2453 /* Oopsy, not so successful after all. */
2460 PyDoc_STRVAR(recv_doc,
2461 "recv(buffersize[, flags]) -> data\n\
2463 Receive up to buffersize bytes from the socket. For the optional flags\n\
2464 argument, see the Unix manual. When no data is available, block until\n\
2465 at least one byte is available or until the remote end is closed. When\n\
2466 the remote end is closed and all data is read, return the empty string.");
2469 /* s.recv_into(buffer, [nbytes [,flags]]) method */
2472 sock_recv_into(PySocketSockObject *s, PyObject *args, PyObject *kwds)
2474 static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
2476 int recvlen = 0, flags = 0;
2481 /* Get the buffer's memory */
2482 if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recv_into", kwlist,
2483 &buf, &recvlen, &flags))
2486 assert(buf.buf != 0 && buflen > 0);
2489 PyErr_SetString(PyExc_ValueError,
2490 "negative buffersize in recv_into");
2494 /* If nbytes was not specified, use the buffer's length */
2498 /* Check if the buffer is large enough */
2499 if (buflen < recvlen) {
2500 PyErr_SetString(PyExc_ValueError,
2501 "buffer too small for requested bytes");
2506 readlen = sock_recv_guts(s, buf.buf, recvlen, flags);
2508 /* Return an error. */
2512 PyBuffer_Release(&buf);
2513 /* Return the number of bytes read. Note that we do not do anything
2514 special here in the case that readlen < recvlen. */
2515 return PyInt_FromSsize_t(readlen);
2518 PyBuffer_Release(&buf);
2522 PyDoc_STRVAR(recv_into_doc,
2523 "recv_into(buffer, [nbytes[, flags]]) -> nbytes_read\n\
2525 A version of recv() that stores its data into a buffer rather than creating \n\
2526 a new string. Receive up to buffersize bytes from the socket. If buffersize \n\
2527 is not specified (or 0), receive up to the size available in the given buffer.\n\
2529 See recv() for documentation about the flags.");
2533 * This is the guts of the recvfrom() and recvfrom_into() methods, which reads
2534 * into a char buffer. If you have any inc/def ref to do to the objects that
2535 * contain the buffer, do it in the caller. This function returns the number
2536 * of bytes successfully read. If there was an error, it returns -1. Note
2537 * that it is also possible that we return a number of bytes smaller than the
2540 * 'addr' is a return value for the address object. Note that you must decref
2544 sock_recvfrom_guts(PySocketSockObject *s, char* cbuf, int len, int flags,
2547 sock_addr_t addrbuf;
2554 if (!getsockaddrlen(s, &addrlen))
2557 if (!IS_SELECTABLE(s)) {
2562 Py_BEGIN_ALLOW_THREADS
2563 memset(&addrbuf, 0, addrlen);
2564 timeout = internal_select(s, 0);
2567 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
2568 n = recvfrom(s->sock_fd, cbuf, len, flags,
2569 SAS2SA(&addrbuf), &addrlen);
2571 n = recvfrom(s->sock_fd, cbuf, len, flags,
2572 (void *) &addrbuf, &addrlen);
2575 n = recvfrom(s->sock_fd, cbuf, len, flags,
2576 SAS2SA(&addrbuf), &addrlen);
2579 Py_END_ALLOW_THREADS
2582 PyErr_SetString(socket_timeout, "timed out");
2590 if (!(*addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
2591 addrlen, s->sock_proto)))
2597 /* s.recvfrom(nbytes [,flags]) method */
2600 sock_recvfrom(PySocketSockObject *s, PyObject *args)
2602 PyObject *buf = NULL;
2603 PyObject *addr = NULL;
2604 PyObject *ret = NULL;
2605 int recvlen, flags = 0;
2608 if (!PyArg_ParseTuple(args, "i|i:recvfrom", &recvlen, &flags))
2612 PyErr_SetString(PyExc_ValueError,
2613 "negative buffersize in recvfrom");
2617 buf = PyString_FromStringAndSize((char *) 0, recvlen);
2621 outlen = sock_recvfrom_guts(s, PyString_AS_STRING(buf),
2622 recvlen, flags, &addr);
2627 if (outlen != recvlen) {
2628 /* We did not read as many bytes as we anticipated, resize the
2629 string if possible and be successful. */
2630 if (_PyString_Resize(&buf, outlen) < 0)
2631 /* Oopsy, not so successful after all. */
2635 ret = PyTuple_Pack(2, buf, addr);
2643 PyDoc_STRVAR(recvfrom_doc,
2644 "recvfrom(buffersize[, flags]) -> (data, address info)\n\
2646 Like recv(buffersize, flags) but also return the sender's address info.");
2649 /* s.recvfrom_into(buffer[, nbytes [,flags]]) method */
2652 sock_recvfrom_into(PySocketSockObject *s, PyObject *args, PyObject* kwds)
2654 static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
2656 int recvlen = 0, flags = 0;
2661 PyObject *addr = NULL;
2663 if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recvfrom_into",
2668 assert(buf.buf != 0 && buflen > 0);
2671 PyErr_SetString(PyExc_ValueError,
2672 "negative buffersize in recvfrom_into");
2676 /* If nbytes was not specified, use the buffer's length */
2680 readlen = sock_recvfrom_guts(s, buf.buf, recvlen, flags, &addr);
2682 /* Return an error */
2686 PyBuffer_Release(&buf);
2687 /* Return the number of bytes read and the address. Note that we do
2688 not do anything special here in the case that readlen < recvlen. */
2689 return Py_BuildValue("lN", readlen, addr);
2693 PyBuffer_Release(&buf);
2697 PyDoc_STRVAR(recvfrom_into_doc,
2698 "recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)\n\
2700 Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.");
2703 /* s.send(data [,flags]) method */
2706 sock_send(PySocketSockObject *s, PyObject *args)
2709 int len, n = -1, flags = 0, timeout;
2712 if (!PyArg_ParseTuple(args, "s*|i:send", &pbuf, &flags))
2715 if (!IS_SELECTABLE(s)) {
2716 PyBuffer_Release(&pbuf);
2717 return select_error();
2722 Py_BEGIN_ALLOW_THREADS
2723 timeout = internal_select(s, 1);
2726 n = sendsegmented(s->sock_fd, buf, len, flags);
2728 n = send(s->sock_fd, buf, len, flags);
2730 Py_END_ALLOW_THREADS
2732 PyBuffer_Release(&pbuf);
2735 PyErr_SetString(socket_timeout, "timed out");
2739 return s->errorhandler();
2740 return PyInt_FromLong((long)n);
2743 PyDoc_STRVAR(send_doc,
2744 "send(data[, flags]) -> count\n\
2746 Send a data string to the socket. For the optional flags\n\
2747 argument, see the Unix manual. Return the number of bytes\n\
2748 sent; this may be less than len(data) if the network is busy.");
2751 /* s.sendall(data [,flags]) method */
2754 sock_sendall(PySocketSockObject *s, PyObject *args)
2757 int len, n = -1, flags = 0, timeout, saved_errno;
2760 if (!PyArg_ParseTuple(args, "s*|i:sendall", &pbuf, &flags))
2765 if (!IS_SELECTABLE(s)) {
2766 PyBuffer_Release(&pbuf);
2767 return select_error();
2771 Py_BEGIN_ALLOW_THREADS
2772 timeout = internal_select(s, 1);
2776 n = sendsegmented(s->sock_fd, buf, len, flags);
2778 n = send(s->sock_fd, buf, len, flags);
2781 Py_END_ALLOW_THREADS
2783 PyBuffer_Release(&pbuf);
2784 PyErr_SetString(socket_timeout, "timed out");
2787 /* PyErr_CheckSignals() might change errno */
2788 saved_errno = errno;
2789 /* We must run our signal handlers before looping again.
2790 send() can return a successful partial write when it is
2791 interrupted, so we can't restrict ourselves to EINTR. */
2792 if (PyErr_CheckSignals()) {
2793 PyBuffer_Release(&pbuf);
2797 /* If interrupted, try again */
2798 if (saved_errno == EINTR)
2806 PyBuffer_Release(&pbuf);
2809 return s->errorhandler();
2815 PyDoc_STRVAR(sendall_doc,
2816 "sendall(data[, flags])\n\
2818 Send a data string to the socket. For the optional flags\n\
2819 argument, see the Unix manual. This calls send() repeatedly\n\
2820 until all data is sent. If an error occurs, it's impossible\n\
2821 to tell how much data has been sent.");
2824 /* s.sendto(data, [flags,] sockaddr) method */
2827 sock_sendto(PySocketSockObject *s, PyObject *args)
2833 sock_addr_t addrbuf;
2834 int addrlen, n = -1, flags, timeout;
2838 arglen = PyTuple_Size(args);
2841 PyArg_ParseTuple(args, "s*O:sendto", &pbuf, &addro);
2844 PyArg_ParseTuple(args, "s*iO:sendto", &pbuf, &flags, &addro);
2847 PyErr_Format(PyExc_TypeError, "sendto() takes 2 or 3"
2848 " arguments (%d given)", arglen);
2850 if (PyErr_Occurred())
2856 if (!IS_SELECTABLE(s)) {
2857 PyBuffer_Release(&pbuf);
2858 return select_error();
2861 if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) {
2862 PyBuffer_Release(&pbuf);
2866 Py_BEGIN_ALLOW_THREADS
2867 timeout = internal_select(s, 1);
2869 n = sendto(s->sock_fd, buf, len, flags, SAS2SA(&addrbuf), addrlen);
2870 Py_END_ALLOW_THREADS
2872 PyBuffer_Release(&pbuf);
2874 PyErr_SetString(socket_timeout, "timed out");
2878 return s->errorhandler();
2879 return PyInt_FromLong((long)n);
2882 PyDoc_STRVAR(sendto_doc,
2883 "sendto(data[, flags], address) -> count\n\
2885 Like send(data, flags) but allows specifying the destination address.\n\
2886 For IP sockets, the address is a pair (hostaddr, port).");
2889 /* s.shutdown(how) method */
2892 sock_shutdown(PySocketSockObject *s, PyObject *arg)
2897 how = PyInt_AsLong(arg);
2898 if (how == -1 && PyErr_Occurred())
2900 Py_BEGIN_ALLOW_THREADS
2901 res = shutdown(s->sock_fd, how);
2902 Py_END_ALLOW_THREADS
2904 return s->errorhandler();
2909 PyDoc_STRVAR(shutdown_doc,
2912 Shut down the reading side of the socket (flag == SHUT_RD), the writing side\n\
2913 of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).");
2915 #if defined(MS_WINDOWS) && defined(SIO_RCVALL)
2917 sock_ioctl(PySocketSockObject *s, PyObject *arg)
2919 unsigned long cmd = SIO_RCVALL;
2923 if (!PyArg_ParseTuple(arg, "kO:ioctl", &cmd, &argO))
2928 unsigned int option = RCVALL_ON;
2929 if (!PyArg_ParseTuple(arg, "kI:ioctl", &cmd, &option))
2931 if (WSAIoctl(s->sock_fd, cmd, &option, sizeof(option),
2932 NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
2935 return PyLong_FromUnsignedLong(recv); }
2936 case SIO_KEEPALIVE_VALS: {
2937 struct tcp_keepalive ka;
2938 if (!PyArg_ParseTuple(arg, "k(kkk):ioctl", &cmd,
2939 &ka.onoff, &ka.keepalivetime, &ka.keepaliveinterval))
2941 if (WSAIoctl(s->sock_fd, cmd, &ka, sizeof(ka),
2942 NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
2945 return PyLong_FromUnsignedLong(recv); }
2947 PyErr_Format(PyExc_ValueError, "invalid ioctl command %d", cmd);
2951 PyDoc_STRVAR(sock_ioctl_doc,
2952 "ioctl(cmd, option) -> long\n\
2954 Control the socket with WSAIoctl syscall. Currently supported 'cmd' values are\n\
2955 SIO_RCVALL: 'option' must be one of the socket.RCVALL_* constants.\n\
2956 SIO_KEEPALIVE_VALS: 'option' is a tuple of (onoff, timeout, interval).");
2960 /* List of methods for socket objects */
2962 static PyMethodDef sock_methods[] = {
2963 {"accept", (PyCFunction)sock_accept, METH_NOARGS,
2965 {"bind", (PyCFunction)sock_bind, METH_O,
2967 {"close", (PyCFunction)sock_close, METH_NOARGS,
2969 {"connect", (PyCFunction)sock_connect, METH_O,
2971 {"connect_ex", (PyCFunction)sock_connect_ex, METH_O,
2974 {"dup", (PyCFunction)sock_dup, METH_NOARGS,
2977 {"fileno", (PyCFunction)sock_fileno, METH_NOARGS,
2979 #ifdef HAVE_GETPEERNAME
2980 {"getpeername", (PyCFunction)sock_getpeername,
2981 METH_NOARGS, getpeername_doc},
2983 {"getsockname", (PyCFunction)sock_getsockname,
2984 METH_NOARGS, getsockname_doc},
2985 {"getsockopt", (PyCFunction)sock_getsockopt, METH_VARARGS,
2987 #if defined(MS_WINDOWS) && defined(SIO_RCVALL)
2988 {"ioctl", (PyCFunction)sock_ioctl, METH_VARARGS,
2991 {"listen", (PyCFunction)sock_listen, METH_O,
2994 {"makefile", (PyCFunction)sock_makefile, METH_VARARGS,
2997 {"recv", (PyCFunction)sock_recv, METH_VARARGS,
2999 {"recv_into", (PyCFunction)sock_recv_into, METH_VARARGS | METH_KEYWORDS,
3001 {"recvfrom", (PyCFunction)sock_recvfrom, METH_VARARGS,
3003 {"recvfrom_into", (PyCFunction)sock_recvfrom_into, METH_VARARGS | METH_KEYWORDS,
3005 {"send", (PyCFunction)sock_send, METH_VARARGS,
3007 {"sendall", (PyCFunction)sock_sendall, METH_VARARGS,
3009 {"sendto", (PyCFunction)sock_sendto, METH_VARARGS,
3011 {"setblocking", (PyCFunction)sock_setblocking, METH_O,
3013 {"settimeout", (PyCFunction)sock_settimeout, METH_O,
3015 {"gettimeout", (PyCFunction)sock_gettimeout, METH_NOARGS,
3017 {"setsockopt", (PyCFunction)sock_setsockopt, METH_VARARGS,
3019 {"shutdown", (PyCFunction)sock_shutdown, METH_O,
3022 {"sleeptaskw", (PyCFunction)sock_sleeptaskw, METH_O,
3025 {NULL, NULL} /* sentinel */
3028 /* SockObject members */
3029 static PyMemberDef sock_memberlist[] = {
3030 {"family", T_INT, offsetof(PySocketSockObject, sock_family), READONLY, "the socket family"},
3031 {"type", T_INT, offsetof(PySocketSockObject, sock_type), READONLY, "the socket type"},
3032 {"proto", T_INT, offsetof(PySocketSockObject, sock_proto), READONLY, "the socket protocol"},
3033 {"timeout", T_DOUBLE, offsetof(PySocketSockObject, sock_timeout), READONLY, "the socket timeout"},
3037 /* Deallocate a socket object in response to the last Py_DECREF().
3038 First close the file description. */
3041 sock_dealloc(PySocketSockObject *s)
3043 if (s->sock_fd != -1)
3044 (void) SOCKETCLOSE(s->sock_fd);
3045 Py_TYPE(s)->tp_free((PyObject *)s);
3050 sock_repr(PySocketSockObject *s)
3053 #if SIZEOF_SOCKET_T > SIZEOF_LONG
3054 if (s->sock_fd > LONG_MAX) {
3055 /* this can occur on Win64, and actually there is a special
3056 ugly printf formatter for decimal pointer length integer
3057 printing, only bother if necessary*/
3058 PyErr_SetString(PyExc_OverflowError,
3059 "no printf formatter to display "
3060 "the socket descriptor in decimal");
3066 "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
3067 (long)s->sock_fd, s->sock_family,
3070 return PyString_FromString(buf);
3074 /* Create a new, uninitialized socket object. */
3077 sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3081 new = type->tp_alloc(type, 0);
3083 ((PySocketSockObject *)new)->sock_fd = -1;
3084 ((PySocketSockObject *)new)->sock_timeout = -1.0;
3085 ((PySocketSockObject *)new)->errorhandler = &set_error;
3091 /* Initialize a new socket object. */
3095 sock_initobj(PyObject *self, PyObject *args, PyObject *kwds)
3097 PySocketSockObject *s = (PySocketSockObject *)self;
3099 int family = AF_INET, type = SOCK_STREAM, proto = 0;
3100 static char *keywords[] = {"family", "type", "proto", 0};
3102 if (!PyArg_ParseTupleAndKeywords(args, kwds,
3103 "|iii:socket", keywords,
3104 &family, &type, &proto))
3107 Py_BEGIN_ALLOW_THREADS
3108 fd = socket(family, type, proto);
3109 Py_END_ALLOW_THREADS
3112 if (fd == INVALID_SOCKET)
3120 init_sockobject(s, fd, family, type, proto);
3127 /* Type object for socket objects. */
3129 static PyTypeObject sock_type = {
3130 PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */
3131 "_socket.socket", /* tp_name */
3132 sizeof(PySocketSockObject), /* tp_basicsize */
3133 0, /* tp_itemsize */
3134 (destructor)sock_dealloc, /* tp_dealloc */
3139 (reprfunc)sock_repr, /* tp_repr */
3140 0, /* tp_as_number */
3141 0, /* tp_as_sequence */
3142 0, /* tp_as_mapping */
3146 PyObject_GenericGetAttr, /* tp_getattro */
3147 0, /* tp_setattro */
3148 0, /* tp_as_buffer */
3149 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3150 sock_doc, /* tp_doc */
3151 0, /* tp_traverse */
3153 0, /* tp_richcompare */
3154 0, /* tp_weaklistoffset */
3156 0, /* tp_iternext */
3157 sock_methods, /* tp_methods */
3158 sock_memberlist, /* tp_members */
3162 0, /* tp_descr_get */
3163 0, /* tp_descr_set */
3164 0, /* tp_dictoffset */
3165 sock_initobj, /* tp_init */
3166 PyType_GenericAlloc, /* tp_alloc */
3167 sock_new, /* tp_new */
3168 PyObject_Del, /* tp_free */
3172 /* Python interface to gethostname(). */
3176 socket_gethostname(PyObject *self, PyObject *unused)
3180 Py_BEGIN_ALLOW_THREADS
3181 res = gethostname(buf, (int) sizeof buf - 1);
3182 Py_END_ALLOW_THREADS
3185 buf[sizeof buf - 1] = '\0';
3186 return PyString_FromString(buf);
3189 PyDoc_STRVAR(gethostname_doc,
3190 "gethostname() -> string\n\
3192 Return the current host name.");
3195 /* Python interface to gethostbyname(name). */
3199 socket_gethostbyname(PyObject *self, PyObject *args)
3202 sock_addr_t addrbuf;
3204 if (!PyArg_ParseTuple(args, "s:gethostbyname", &name))
3206 if (setipaddr(name, SAS2SA(&addrbuf), sizeof(addrbuf), AF_INET) < 0)
3208 return makeipaddr(SAS2SA(&addrbuf), sizeof(struct sockaddr_in));
3211 PyDoc_STRVAR(gethostbyname_doc,
3212 "gethostbyname(host) -> address\n\
3214 Return the IP address (a string of the form '255.255.255.255') for a host.");
3217 /* Convenience function common to gethostbyname_ex and gethostbyaddr */
3220 gethost_common(struct hostent *h, struct sockaddr *addr, int alen, int af)
3223 PyObject *rtn_tuple = (PyObject *)NULL;
3224 PyObject *name_list = (PyObject *)NULL;
3225 PyObject *addr_list = (PyObject *)NULL;
3229 /* Let's get real error message to return */
3231 set_herror(h_errno);
3233 PyErr_SetString(socket_error, "host not found");
3238 if (h->h_addrtype != af) {
3239 /* Let's get real error message to return */
3240 PyErr_SetString(socket_error,
3241 (char *)strerror(EAFNOSUPPORT));
3249 if (alen < sizeof(struct sockaddr_in))
3255 if (alen < sizeof(struct sockaddr_in6))
3262 if ((name_list = PyList_New(0)) == NULL)
3265 if ((addr_list = PyList_New(0)) == NULL)
3268 /* SF #1511317: h_aliases can be NULL */
3270 for (pch = h->h_aliases; *pch != NULL; pch++) {
3272 tmp = PyString_FromString(*pch);
3276 status = PyList_Append(name_list, tmp);
3284 for (pch = h->h_addr_list; *pch != NULL; pch++) {
3291 struct sockaddr_in sin;
3292 memset(&sin, 0, sizeof(sin));
3293 sin.sin_family = af;
3294 #ifdef HAVE_SOCKADDR_SA_LEN
3295 sin.sin_len = sizeof(sin);
3297 memcpy(&sin.sin_addr, *pch, sizeof(sin.sin_addr));
3298 tmp = makeipaddr((struct sockaddr *)&sin, sizeof(sin));
3300 if (pch == h->h_addr_list && alen >= sizeof(sin))
3301 memcpy((char *) addr, &sin, sizeof(sin));
3308 struct sockaddr_in6 sin6;
3309 memset(&sin6, 0, sizeof(sin6));
3310 sin6.sin6_family = af;
3311 #ifdef HAVE_SOCKADDR_SA_LEN
3312 sin6.sin6_len = sizeof(sin6);
3314 memcpy(&sin6.sin6_addr, *pch, sizeof(sin6.sin6_addr));
3315 tmp = makeipaddr((struct sockaddr *)&sin6,
3318 if (pch == h->h_addr_list && alen >= sizeof(sin6))
3319 memcpy((char *) addr, &sin6, sizeof(sin6));
3324 default: /* can't happen */
3325 PyErr_SetString(socket_error,
3326 "unsupported address family");
3333 status = PyList_Append(addr_list, tmp);
3340 rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list);
3343 Py_XDECREF(name_list);
3344 Py_XDECREF(addr_list);
3349 /* Python interface to gethostbyname_ex(name). */
3353 socket_gethostbyname_ex(PyObject *self, PyObject *args)
3358 struct sockaddr_storage addr;
3360 struct sockaddr_in addr;
3362 struct sockaddr *sa;
3364 #ifdef HAVE_GETHOSTBYNAME_R
3365 struct hostent hp_allocated;
3366 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
3367 struct hostent_data data;
3370 int buf_len = (sizeof buf) - 1;
3373 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3376 #endif /* HAVE_GETHOSTBYNAME_R */
3378 if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name))
3380 if (setipaddr(name, (struct sockaddr *)&addr, sizeof(addr), AF_INET) < 0)
3382 Py_BEGIN_ALLOW_THREADS
3383 #ifdef HAVE_GETHOSTBYNAME_R
3384 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3385 result = gethostbyname_r(name, &hp_allocated, buf, buf_len,
3387 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
3388 h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
3389 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
3390 memset((void *) &data, '\0', sizeof(data));
3391 result = gethostbyname_r(name, &hp_allocated, &data);
3392 h = (result != 0) ? NULL : &hp_allocated;
3394 #else /* not HAVE_GETHOSTBYNAME_R */
3395 #ifdef USE_GETHOSTBYNAME_LOCK
3396 PyThread_acquire_lock(netdb_lock, 1);
3398 h = gethostbyname(name);
3399 #endif /* HAVE_GETHOSTBYNAME_R */
3400 Py_END_ALLOW_THREADS
3401 /* Some C libraries would require addr.__ss_family instead of
3403 Therefore, we cast the sockaddr_storage into sockaddr to
3404 access sa_family. */
3405 sa = (struct sockaddr*)&addr;
3406 ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr),
3408 #ifdef USE_GETHOSTBYNAME_LOCK
3409 PyThread_release_lock(netdb_lock);
3414 PyDoc_STRVAR(ghbn_ex_doc,
3415 "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
3417 Return the true host name, a list of aliases, and a list of IP addresses,\n\
3418 for a host. The host argument is a string giving a host name or IP number.");
3421 /* Python interface to gethostbyaddr(IP). */
3425 socket_gethostbyaddr(PyObject *self, PyObject *args)
3428 struct sockaddr_storage addr;
3430 struct sockaddr_in addr;
3432 struct sockaddr *sa = (struct sockaddr *)&addr;
3436 #ifdef HAVE_GETHOSTBYNAME_R
3437 struct hostent hp_allocated;
3438 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
3439 struct hostent_data data;
3441 /* glibcs up to 2.10 assume that the buf argument to
3442 gethostbyaddr_r is 8-byte aligned, which at least llvm-gcc
3443 does not ensure. The attribute below instructs the compiler
3444 to maintain this alignment. */
3445 char buf[16384] Py_ALIGNED(8);
3446 int buf_len = (sizeof buf) - 1;
3449 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3452 #endif /* HAVE_GETHOSTBYNAME_R */
3457 if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num))
3460 if (setipaddr(ip_num, sa, sizeof(addr), af) < 0)
3466 ap = (char *)&((struct sockaddr_in *)sa)->sin_addr;
3467 al = sizeof(((struct sockaddr_in *)sa)->sin_addr);
3471 ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr;
3472 al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr);
3476 PyErr_SetString(socket_error, "unsupported address family");
3479 Py_BEGIN_ALLOW_THREADS
3480 #ifdef HAVE_GETHOSTBYNAME_R
3481 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3482 result = gethostbyaddr_r(ap, al, af,
3483 &hp_allocated, buf, buf_len,
3485 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
3486 h = gethostbyaddr_r(ap, al, af,
3487 &hp_allocated, buf, buf_len, &errnop);
3488 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
3489 memset((void *) &data, '\0', sizeof(data));
3490 result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data);
3491 h = (result != 0) ? NULL : &hp_allocated;
3493 #else /* not HAVE_GETHOSTBYNAME_R */
3494 #ifdef USE_GETHOSTBYNAME_LOCK
3495 PyThread_acquire_lock(netdb_lock, 1);
3497 h = gethostbyaddr(ap, al, af);
3498 #endif /* HAVE_GETHOSTBYNAME_R */
3499 Py_END_ALLOW_THREADS
3500 ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), af);
3501 #ifdef USE_GETHOSTBYNAME_LOCK
3502 PyThread_release_lock(netdb_lock);
3507 PyDoc_STRVAR(gethostbyaddr_doc,
3508 "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
3510 Return the true host name, a list of aliases, and a list of IP addresses,\n\
3511 for a host. The host argument is a string giving a host name or IP number.");
3514 /* Python interface to getservbyname(name).
3515 This only returns the port number, since the other info is already
3516 known or not useful (like the list of aliases). */
3520 socket_getservbyname(PyObject *self, PyObject *args)
3522 char *name, *proto=NULL;
3524 if (!PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto))
3526 Py_BEGIN_ALLOW_THREADS
3527 sp = getservbyname(name, proto);
3528 Py_END_ALLOW_THREADS
3530 PyErr_SetString(socket_error, "service/proto not found");
3533 return PyInt_FromLong((long) ntohs(sp->s_port));
3536 PyDoc_STRVAR(getservbyname_doc,
3537 "getservbyname(servicename[, protocolname]) -> integer\n\
3539 Return a port number from a service name and protocol name.\n\
3540 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3541 otherwise any protocol will match.");
3544 /* Python interface to getservbyport(port).
3545 This only returns the service name, since the other info is already
3546 known or not useful (like the list of aliases). */
3550 socket_getservbyport(PyObject *self, PyObject *args)
3555 if (!PyArg_ParseTuple(args, "i|s:getservbyport", &port, &proto))
3557 if (port < 0 || port > 0xffff) {
3559 PyExc_OverflowError,
3560 "getservbyport: port must be 0-65535.");
3563 Py_BEGIN_ALLOW_THREADS
3564 sp = getservbyport(htons((short)port), proto);
3565 Py_END_ALLOW_THREADS
3567 PyErr_SetString(socket_error, "port/proto not found");
3570 return PyString_FromString(sp->s_name);
3573 PyDoc_STRVAR(getservbyport_doc,
3574 "getservbyport(port[, protocolname]) -> string\n\
3576 Return the service name from a port number and protocol name.\n\
3577 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3578 otherwise any protocol will match.");
3580 /* Python interface to getprotobyname(name).
3581 This only returns the protocol number, since the other info is
3582 already known or not useful (like the list of aliases). */
3586 socket_getprotobyname(PyObject *self, PyObject *args)
3589 struct protoent *sp;
3591 /* Not available in BeOS yet. - [cjh] */
3592 PyErr_SetString(socket_error, "getprotobyname not supported");
3595 if (!PyArg_ParseTuple(args, "s:getprotobyname", &name))
3597 Py_BEGIN_ALLOW_THREADS
3598 sp = getprotobyname(name);
3599 Py_END_ALLOW_THREADS
3601 PyErr_SetString(socket_error, "protocol not found");
3604 return PyInt_FromLong((long) sp->p_proto);
3608 PyDoc_STRVAR(getprotobyname_doc,
3609 "getprotobyname(name) -> integer\n\
3611 Return the protocol number for the named protocol. (Rarely used.)");
3614 #ifdef HAVE_SOCKETPAIR
3615 /* Create a pair of sockets using the socketpair() function.
3616 Arguments as for socket() except the default family is AF_UNIX if
3617 defined on the platform; otherwise, the default is AF_INET. */
3621 socket_socketpair(PyObject *self, PyObject *args)
3623 PySocketSockObject *s0 = NULL, *s1 = NULL;
3625 int family, type = SOCK_STREAM, proto = 0;
3626 PyObject *res = NULL;
3628 #if defined(AF_UNIX)
3633 if (!PyArg_ParseTuple(args, "|iii:socketpair",
3634 &family, &type, &proto))
3636 /* Create a pair of socket fds */
3637 if (socketpair(family, type, proto, sv) < 0)
3639 s0 = new_sockobject(sv[0], family, type, proto);
3642 s1 = new_sockobject(sv[1], family, type, proto);
3645 res = PyTuple_Pack(2, s0, s1);
3659 PyDoc_STRVAR(socketpair_doc,
3660 "socketpair([family[, type[, proto]]]) -> (socket object, socket object)\n\
3662 Create a pair of socket objects from the sockets returned by the platform\n\
3663 socketpair() function.\n\
3664 The arguments are the same as for socket() except the default family is\n\
3665 AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");
3667 #endif /* HAVE_SOCKETPAIR */
3671 /* Create a socket object from a numeric file description.
3672 Useful e.g. if stdin is a socket.
3673 Additional arguments as for socket(). */
3677 socket_fromfd(PyObject *self, PyObject *args)
3679 PySocketSockObject *s;
3681 int family, type, proto = 0;
3682 if (!PyArg_ParseTuple(args, "iii|i:fromfd",
3683 &fd, &family, &type, &proto))
3685 /* Dup the fd so it and the socket can be closed independently */
3689 s = new_sockobject(fd, family, type, proto);
3690 return (PyObject *) s;
3693 PyDoc_STRVAR(fromfd_doc,
3694 "fromfd(fd, family, type[, proto]) -> socket object\n\
3696 Create a socket object from a duplicate of the given\n\
3698 The remaining arguments are the same as for socket().");
3704 socket_ntohs(PyObject *self, PyObject *args)
3708 if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) {
3712 PyErr_SetString(PyExc_OverflowError,
3713 "can't convert negative number to unsigned long");
3716 x2 = (unsigned int)ntohs((unsigned short)x1);
3717 return PyInt_FromLong(x2);
3720 PyDoc_STRVAR(ntohs_doc,
3721 "ntohs(integer) -> integer\n\
3723 Convert a 16-bit integer from network to host byte order.");
3727 socket_ntohl(PyObject *self, PyObject *arg)
3731 if (PyInt_Check(arg)) {
3732 x = PyInt_AS_LONG(arg);
3733 if (x == (unsigned long) -1 && PyErr_Occurred())
3736 PyErr_SetString(PyExc_OverflowError,
3737 "can't convert negative number to unsigned long");
3741 else if (PyLong_Check(arg)) {
3742 x = PyLong_AsUnsignedLong(arg);
3743 if (x == (unsigned long) -1 && PyErr_Occurred())
3748 /* only want the trailing 32 bits */
3749 y = x & 0xFFFFFFFFUL;
3751 return PyErr_Format(PyExc_OverflowError,
3752 "long int larger than 32 bits");
3758 return PyErr_Format(PyExc_TypeError,
3759 "expected int/long, %s found",
3760 Py_TYPE(arg)->tp_name);
3761 if (x == (unsigned long) -1 && PyErr_Occurred())
3763 return PyLong_FromUnsignedLong(ntohl(x));
3766 PyDoc_STRVAR(ntohl_doc,
3767 "ntohl(integer) -> integer\n\
3769 Convert a 32-bit integer from network to host byte order.");
3773 socket_htons(PyObject *self, PyObject *args)
3777 if (!PyArg_ParseTuple(args, "i:htons", &x1)) {
3781 PyErr_SetString(PyExc_OverflowError,
3782 "can't convert negative number to unsigned long");
3785 x2 = (unsigned int)htons((unsigned short)x1);
3786 return PyInt_FromLong(x2);
3789 PyDoc_STRVAR(htons_doc,
3790 "htons(integer) -> integer\n\
3792 Convert a 16-bit integer from host to network byte order.");
3796 socket_htonl(PyObject *self, PyObject *arg)
3800 if (PyInt_Check(arg)) {
3801 x = PyInt_AS_LONG(arg);
3802 if (x == (unsigned long) -1 && PyErr_Occurred())
3805 PyErr_SetString(PyExc_OverflowError,
3806 "can't convert negative number to unsigned long");
3810 else if (PyLong_Check(arg)) {
3811 x = PyLong_AsUnsignedLong(arg);
3812 if (x == (unsigned long) -1 && PyErr_Occurred())
3817 /* only want the trailing 32 bits */
3818 y = x & 0xFFFFFFFFUL;
3820 return PyErr_Format(PyExc_OverflowError,
3821 "long int larger than 32 bits");
3827 return PyErr_Format(PyExc_TypeError,
3828 "expected int/long, %s found",
3829 Py_TYPE(arg)->tp_name);
3830 return PyLong_FromUnsignedLong(htonl((unsigned long)x));
3833 PyDoc_STRVAR(htonl_doc,
3834 "htonl(integer) -> integer\n\
3836 Convert a 32-bit integer from host to network byte order.");
3838 /* socket.inet_aton() and socket.inet_ntoa() functions. */
3840 PyDoc_STRVAR(inet_aton_doc,
3841 "inet_aton(string) -> packed 32-bit IP representation\n\
3843 Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
3844 binary format used in low-level network functions.");
3847 socket_inet_aton(PyObject *self, PyObject *args)
3850 #define INADDR_NONE (-1)
3852 #ifdef HAVE_INET_ATON
3856 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
3857 #if (SIZEOF_INT != 4)
3858 #error "Not sure if in_addr_t exists and int is not 32-bits."
3860 /* Have to use inet_addr() instead */
3861 unsigned int packed_addr;
3865 if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr))
3869 #ifdef HAVE_INET_ATON
3871 #ifdef USE_INET_ATON_WEAKLINK
3872 if (inet_aton != NULL) {
3874 if (inet_aton(ip_addr, &buf))
3875 return PyString_FromStringAndSize((char *)(&buf),
3878 PyErr_SetString(socket_error,
3879 "illegal IP address string passed to inet_aton");
3882 #ifdef USE_INET_ATON_WEAKLINK
3888 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
3890 /* special-case this address as inet_addr might return INADDR_NONE
3892 if (strcmp(ip_addr, "255.255.255.255") == 0) {
3893 packed_addr = 0xFFFFFFFF;
3896 packed_addr = inet_addr(ip_addr);
3898 if (packed_addr == INADDR_NONE) { /* invalid address */
3899 PyErr_SetString(socket_error,
3900 "illegal IP address string passed to inet_aton");
3904 return PyString_FromStringAndSize((char *) &packed_addr,
3905 sizeof(packed_addr));
3907 #ifdef USE_INET_ATON_WEAKLINK
3914 PyDoc_STRVAR(inet_ntoa_doc,
3915 "inet_ntoa(packed_ip) -> ip_address_string\n\
3917 Convert an IP address from 32-bit packed binary format to string format");
3920 socket_inet_ntoa(PyObject *self, PyObject *args)
3924 struct in_addr packed_addr;
3926 if (!PyArg_ParseTuple(args, "s#:inet_ntoa", &packed_str, &addr_len)) {
3930 if (addr_len != sizeof(packed_addr)) {
3931 PyErr_SetString(socket_error,
3932 "packed IP wrong length for inet_ntoa");
3936 memcpy(&packed_addr, packed_str, addr_len);
3938 return PyString_FromString(inet_ntoa(packed_addr));
3941 #ifdef HAVE_INET_PTON
3943 PyDoc_STRVAR(inet_pton_doc,
3944 "inet_pton(af, ip) -> packed IP address string\n\
3946 Convert an IP address from string format to a packed string suitable\n\
3947 for use with low-level network functions.");
3950 socket_inet_pton(PyObject *self, PyObject *args)
3956 char packed[MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
3958 char packed[sizeof(struct in_addr)];
3960 if (!PyArg_ParseTuple(args, "is:inet_pton", &af, &ip)) {
3964 #if !defined(ENABLE_IPV6) && defined(AF_INET6)
3965 if(af == AF_INET6) {
3966 PyErr_SetString(socket_error,
3967 "can't use AF_INET6, IPv6 is disabled");
3972 retval = inet_pton(af, ip, packed);
3974 PyErr_SetFromErrno(socket_error);
3976 } else if (retval == 0) {
3977 PyErr_SetString(socket_error,
3978 "illegal IP address string passed to inet_pton");
3980 } else if (af == AF_INET) {
3981 return PyString_FromStringAndSize(packed,
3982 sizeof(struct in_addr));
3984 } else if (af == AF_INET6) {
3985 return PyString_FromStringAndSize(packed,
3986 sizeof(struct in6_addr));
3989 PyErr_SetString(socket_error, "unknown address family");
3994 PyDoc_STRVAR(inet_ntop_doc,
3995 "inet_ntop(af, packed_ip) -> string formatted IP address\n\
3997 Convert a packed IP address of the given family to string format.");
4000 socket_inet_ntop(PyObject *self, PyObject *args)
4007 char ip[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) + 1];
4009 char ip[INET_ADDRSTRLEN + 1];
4012 /* Guarantee NUL-termination for PyString_FromString() below */
4013 memset((void *) &ip[0], '\0', sizeof(ip));
4015 if (!PyArg_ParseTuple(args, "is#:inet_ntop", &af, &packed, &len)) {
4019 if (af == AF_INET) {
4020 if (len != sizeof(struct in_addr)) {
4021 PyErr_SetString(PyExc_ValueError,
4022 "invalid length of packed IP address string");
4026 } else if (af == AF_INET6) {
4027 if (len != sizeof(struct in6_addr)) {
4028 PyErr_SetString(PyExc_ValueError,
4029 "invalid length of packed IP address string");
4034 PyErr_Format(PyExc_ValueError,
4035 "unknown address family %d", af);
4039 retval = inet_ntop(af, packed, ip, sizeof(ip));
4041 PyErr_SetFromErrno(socket_error);
4044 return PyString_FromString(retval);
4048 PyErr_SetString(PyExc_RuntimeError, "invalid handling of inet_ntop");
4052 #endif /* HAVE_INET_PTON */
4054 /* Python interface to getaddrinfo(host, port). */
4058 socket_getaddrinfo(PyObject *self, PyObject *args)
4060 struct addrinfo hints, *res;
4061 struct addrinfo *res0 = NULL;
4062 PyObject *hobj = NULL;
4063 PyObject *pobj = (PyObject *)NULL;
4066 int family, socktype, protocol, flags;
4068 PyObject *all = (PyObject *)NULL;
4069 PyObject *single = (PyObject *)NULL;
4070 PyObject *idna = NULL;
4072 family = socktype = protocol = flags = 0;
4074 if (!PyArg_ParseTuple(args, "OO|iiii:getaddrinfo",
4075 &hobj, &pobj, &family, &socktype,
4076 &protocol, &flags)) {
4079 if (hobj == Py_None) {
4081 } else if (PyUnicode_Check(hobj)) {
4082 idna = PyObject_CallMethod(hobj, "encode", "s", "idna");
4085 hptr = PyString_AsString(idna);
4086 } else if (PyString_Check(hobj)) {
4087 hptr = PyString_AsString(hobj);
4089 PyErr_SetString(PyExc_TypeError,
4090 "getaddrinfo() argument 1 must be string or None");
4093 if (PyInt_Check(pobj)) {
4094 PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", PyInt_AsLong(pobj));
4096 } else if (PyString_Check(pobj)) {
4097 pptr = PyString_AsString(pobj);
4098 } else if (pobj == Py_None) {
4099 pptr = (char *)NULL;
4101 PyErr_SetString(socket_error, "Int or String expected");
4104 memset(&hints, 0, sizeof(hints));
4105 hints.ai_family = family;
4106 hints.ai_socktype = socktype;
4107 hints.ai_protocol = protocol;
4108 hints.ai_flags = flags;
4109 Py_BEGIN_ALLOW_THREADS
4110 ACQUIRE_GETADDRINFO_LOCK
4111 error = getaddrinfo(hptr, pptr, &hints, &res0);
4112 Py_END_ALLOW_THREADS
4113 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
4115 set_gaierror(error);
4119 if ((all = PyList_New(0)) == NULL)
4121 for (res = res0; res; res = res->ai_next) {
4123 makesockaddr(-1, res->ai_addr, res->ai_addrlen, protocol);
4126 single = Py_BuildValue("iiisO", res->ai_family,
4127 res->ai_socktype, res->ai_protocol,
4128 res->ai_canonname ? res->ai_canonname : "",
4134 if (PyList_Append(all, single))
4148 return (PyObject *)NULL;
4151 PyDoc_STRVAR(getaddrinfo_doc,
4152 "getaddrinfo(host, port [, family, socktype, proto, flags])\n\
4153 -> list of (family, socktype, proto, canonname, sockaddr)\n\
4155 Resolve host and port into addrinfo struct.");
4157 /* Python interface to getnameinfo(sa, flags). */
4161 socket_getnameinfo(PyObject *self, PyObject *args)
4163 PyObject *sa = (PyObject *)NULL;
4167 unsigned int flowinfo, scope_id;
4168 char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
4169 struct addrinfo hints, *res = NULL;
4171 PyObject *ret = (PyObject *)NULL;
4173 flags = flowinfo = scope_id = 0;
4174 if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags))
4176 if (!PyTuple_Check(sa)) {
4177 PyErr_SetString(PyExc_TypeError,
4178 "getnameinfo() argument 1 must be a tuple");
4181 if (!PyArg_ParseTuple(sa, "si|II",
4182 &hostp, &port, &flowinfo, &scope_id))
4184 if (flowinfo < 0 || flowinfo > 0xfffff) {
4185 PyErr_SetString(PyExc_OverflowError,
4186 "getsockaddrarg: flowinfo must be 0-1048575.");
4189 PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port);
4190 memset(&hints, 0, sizeof(hints));
4191 hints.ai_family = AF_UNSPEC;
4192 hints.ai_socktype = SOCK_DGRAM; /* make numeric port happy */
4193 Py_BEGIN_ALLOW_THREADS
4194 ACQUIRE_GETADDRINFO_LOCK
4195 error = getaddrinfo(hostp, pbuf, &hints, &res);
4196 Py_END_ALLOW_THREADS
4197 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
4199 set_gaierror(error);
4203 PyErr_SetString(socket_error,
4204 "sockaddr resolved to multiple addresses");
4207 switch (res->ai_family) {
4210 if (PyTuple_GET_SIZE(sa) != 2) {
4211 PyErr_SetString(socket_error,
4212 "IPv4 sockaddr must be 2 tuple");
4220 struct sockaddr_in6 *sin6;
4221 sin6 = (struct sockaddr_in6 *)res->ai_addr;
4222 sin6->sin6_flowinfo = htonl(flowinfo);
4223 sin6->sin6_scope_id = scope_id;
4228 error = getnameinfo(res->ai_addr, res->ai_addrlen,
4229 hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags);
4231 set_gaierror(error);
4234 ret = Py_BuildValue("ss", hbuf, pbuf);
4242 PyDoc_STRVAR(getnameinfo_doc,
4243 "getnameinfo(sockaddr, flags) --> (host, port)\n\
4245 Get host and port for a sockaddr.");
4248 /* Python API to getting and setting the default timeout value. */
4251 socket_getdefaulttimeout(PyObject *self)
4253 if (defaulttimeout < 0.0) {
4258 return PyFloat_FromDouble(defaulttimeout);
4261 PyDoc_STRVAR(getdefaulttimeout_doc,
4262 "getdefaulttimeout() -> timeout\n\
4264 Returns the default timeout in seconds (float) for new socket objects.\n\
4265 A value of None indicates that new socket objects have no timeout.\n\
4266 When the socket module is first imported, the default is None.");
4269 socket_setdefaulttimeout(PyObject *self, PyObject *arg)
4276 timeout = PyFloat_AsDouble(arg);
4277 if (timeout < 0.0) {
4278 if (!PyErr_Occurred())
4279 PyErr_SetString(PyExc_ValueError,
4280 "Timeout value out of range");
4285 defaulttimeout = timeout;
4291 PyDoc_STRVAR(setdefaulttimeout_doc,
4292 "setdefaulttimeout(timeout)\n\
4294 Set the default timeout in seconds (float) for new socket objects.\n\
4295 A value of None indicates that new socket objects have no timeout.\n\
4296 When the socket module is first imported, the default is None.");
4299 /* List of functions exported by this module. */
4301 static PyMethodDef socket_methods[] = {
4302 {"gethostbyname", socket_gethostbyname,
4303 METH_VARARGS, gethostbyname_doc},
4304 {"gethostbyname_ex", socket_gethostbyname_ex,
4305 METH_VARARGS, ghbn_ex_doc},
4306 {"gethostbyaddr", socket_gethostbyaddr,
4307 METH_VARARGS, gethostbyaddr_doc},
4308 {"gethostname", socket_gethostname,
4309 METH_NOARGS, gethostname_doc},
4310 {"getservbyname", socket_getservbyname,
4311 METH_VARARGS, getservbyname_doc},
4312 {"getservbyport", socket_getservbyport,
4313 METH_VARARGS, getservbyport_doc},
4314 {"getprotobyname", socket_getprotobyname,
4315 METH_VARARGS, getprotobyname_doc},
4317 {"fromfd", socket_fromfd,
4318 METH_VARARGS, fromfd_doc},
4320 #ifdef HAVE_SOCKETPAIR
4321 {"socketpair", socket_socketpair,
4322 METH_VARARGS, socketpair_doc},
4324 {"ntohs", socket_ntohs,
4325 METH_VARARGS, ntohs_doc},
4326 {"ntohl", socket_ntohl,
4328 {"htons", socket_htons,
4329 METH_VARARGS, htons_doc},
4330 {"htonl", socket_htonl,
4332 {"inet_aton", socket_inet_aton,
4333 METH_VARARGS, inet_aton_doc},
4334 {"inet_ntoa", socket_inet_ntoa,
4335 METH_VARARGS, inet_ntoa_doc},
4336 #ifdef HAVE_INET_PTON
4337 {"inet_pton", socket_inet_pton,
4338 METH_VARARGS, inet_pton_doc},
4339 {"inet_ntop", socket_inet_ntop,
4340 METH_VARARGS, inet_ntop_doc},
4342 {"getaddrinfo", socket_getaddrinfo,
4343 METH_VARARGS, getaddrinfo_doc},
4344 {"getnameinfo", socket_getnameinfo,
4345 METH_VARARGS, getnameinfo_doc},
4346 {"getdefaulttimeout", (PyCFunction)socket_getdefaulttimeout,
4347 METH_NOARGS, getdefaulttimeout_doc},
4348 {"setdefaulttimeout", socket_setdefaulttimeout,
4349 METH_O, setdefaulttimeout_doc},
4350 {NULL, NULL} /* Sentinel */
4355 #define OS_INIT_DEFINED
4363 _kernel_swi(0x43380, &r, &r);
4364 taskwindow = r.r[0];
4373 #define OS_INIT_DEFINED
4375 /* Additional initialization and cleanup for Windows */
4389 ret = WSAStartup(0x0101, &WSAData);
4391 case 0: /* No error */
4392 Py_AtExit(os_cleanup);
4393 return 1; /* Success */
4394 case WSASYSNOTREADY:
4395 PyErr_SetString(PyExc_ImportError,
4396 "WSAStartup failed: network not ready");
4398 case WSAVERNOTSUPPORTED:
4402 "WSAStartup failed: requested version not supported");
4405 PyOS_snprintf(buf, sizeof(buf),
4406 "WSAStartup failed: error code %d", ret);
4407 PyErr_SetString(PyExc_ImportError, buf);
4410 return 0; /* Failure */
4413 #endif /* MS_WINDOWS */
4417 #define OS_INIT_DEFINED
4419 /* Additional initialization for OS/2 */
4426 int rc = sock_init();
4429 return 1; /* Success */
4432 PyOS_snprintf(reason, sizeof(reason),
4433 "OS/2 TCP/IP Error# %d", sock_errno());
4434 PyErr_SetString(PyExc_ImportError, reason);
4436 return 0; /* Failure */
4438 /* No need to initialize sockets with GCC/EMX */
4439 return 1; /* Success */
4443 #endif /* PYOS_OS2 */
4446 #ifndef OS_INIT_DEFINED
4450 return 1; /* Success */
4455 /* C API table - always add new things to the end for binary
4458 PySocketModule_APIObject PySocketModuleAPI =
4465 /* Initialize the _socket module.
4467 This module is actually called "_socket", and there's a wrapper
4468 "socket.py" which implements some additional functionality. On some
4469 platforms (e.g. Windows and OS/2), socket.py also implements a
4470 wrapper for the socket type that provides missing functionality such
4471 as makefile(), dup() and fromfd(). The import of "_socket" may fail
4472 with an ImportError exception if os-specific initialization fails.
4473 On Windows, this does WINSOCK initialization. When WINSOCK is
4474 initialized successfully, a call to WSACleanup() is scheduled to be
4478 PyDoc_STRVAR(socket_doc,
4479 "Implementation module for socket operations.\n\
4481 See the socket module for documentation.");
4486 PyObject *m, *has_ipv6;
4491 Py_TYPE(&sock_type) = &PyType_Type;
4492 m = Py_InitModule3(PySocket_MODULE_NAME,
4498 socket_error = PyErr_NewException("socket.error",
4499 PyExc_IOError, NULL);
4500 if (socket_error == NULL)
4502 PySocketModuleAPI.error = socket_error;
4503 Py_INCREF(socket_error);
4504 PyModule_AddObject(m, "error", socket_error);
4505 socket_herror = PyErr_NewException("socket.herror",
4506 socket_error, NULL);
4507 if (socket_herror == NULL)
4509 Py_INCREF(socket_herror);
4510 PyModule_AddObject(m, "herror", socket_herror);
4511 socket_gaierror = PyErr_NewException("socket.gaierror", socket_error,
4513 if (socket_gaierror == NULL)
4515 Py_INCREF(socket_gaierror);
4516 PyModule_AddObject(m, "gaierror", socket_gaierror);
4517 socket_timeout = PyErr_NewException("socket.timeout",
4518 socket_error, NULL);
4519 if (socket_timeout == NULL)
4521 Py_INCREF(socket_timeout);
4522 PyModule_AddObject(m, "timeout", socket_timeout);
4523 Py_INCREF((PyObject *)&sock_type);
4524 if (PyModule_AddObject(m, "SocketType",
4525 (PyObject *)&sock_type) != 0)
4527 Py_INCREF((PyObject *)&sock_type);
4528 if (PyModule_AddObject(m, "socket",
4529 (PyObject *)&sock_type) != 0)
4535 has_ipv6 = Py_False;
4537 Py_INCREF(has_ipv6);
4538 PyModule_AddObject(m, "has_ipv6", has_ipv6);
4541 if (PyModule_AddObject(m, PySocket_CAPI_NAME,
4542 PyCapsule_New(&PySocketModuleAPI, PySocket_CAPSULE_NAME, NULL)
4546 /* Address families (we only support AF_INET and AF_UNIX) */
4548 PyModule_AddIntConstant(m, "AF_UNSPEC", AF_UNSPEC);
4550 PyModule_AddIntConstant(m, "AF_INET", AF_INET);
4552 PyModule_AddIntConstant(m, "AF_INET6", AF_INET6);
4553 #endif /* AF_INET6 */
4554 #if defined(AF_UNIX)
4555 PyModule_AddIntConstant(m, "AF_UNIX", AF_UNIX);
4556 #endif /* AF_UNIX */
4558 /* Amateur Radio AX.25 */
4559 PyModule_AddIntConstant(m, "AF_AX25", AF_AX25);
4562 PyModule_AddIntConstant(m, "AF_IPX", AF_IPX); /* Novell IPX */
4566 PyModule_AddIntConstant(m, "AF_APPLETALK", AF_APPLETALK);
4569 /* Amateur radio NetROM */
4570 PyModule_AddIntConstant(m, "AF_NETROM", AF_NETROM);
4573 /* Multiprotocol bridge */
4574 PyModule_AddIntConstant(m, "AF_BRIDGE", AF_BRIDGE);
4578 PyModule_AddIntConstant(m, "AF_ATMPVC", AF_ATMPVC);
4581 /* Reserved for Werner's ATM */
4582 PyModule_AddIntConstant(m, "AF_AAL5", AF_AAL5);
4585 /* Reserved for X.25 project */
4586 PyModule_AddIntConstant(m, "AF_X25", AF_X25);
4589 PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); /* IP version 6 */
4592 /* Amateur Radio X.25 PLP */
4593 PyModule_AddIntConstant(m, "AF_ROSE", AF_ROSE);
4596 /* Reserved for DECnet project */
4597 PyModule_AddIntConstant(m, "AF_DECnet", AF_DECnet);
4600 /* Reserved for 802.2LLC project */
4601 PyModule_AddIntConstant(m, "AF_NETBEUI", AF_NETBEUI);
4604 /* Security callback pseudo AF */
4605 PyModule_AddIntConstant(m, "AF_SECURITY", AF_SECURITY);
4608 /* PF_KEY key management API */
4609 PyModule_AddIntConstant(m, "AF_KEY", AF_KEY);
4613 PyModule_AddIntConstant(m, "AF_NETLINK", AF_NETLINK);
4614 PyModule_AddIntConstant(m, "NETLINK_ROUTE", NETLINK_ROUTE);
4616 PyModule_AddIntConstant(m, "NETLINK_SKIP", NETLINK_SKIP);
4619 PyModule_AddIntConstant(m, "NETLINK_W1", NETLINK_W1);
4621 PyModule_AddIntConstant(m, "NETLINK_USERSOCK", NETLINK_USERSOCK);
4622 PyModule_AddIntConstant(m, "NETLINK_FIREWALL", NETLINK_FIREWALL);
4623 #ifdef NETLINK_TCPDIAG
4624 PyModule_AddIntConstant(m, "NETLINK_TCPDIAG", NETLINK_TCPDIAG);
4626 #ifdef NETLINK_NFLOG
4627 PyModule_AddIntConstant(m, "NETLINK_NFLOG", NETLINK_NFLOG);
4630 PyModule_AddIntConstant(m, "NETLINK_XFRM", NETLINK_XFRM);
4633 PyModule_AddIntConstant(m, "NETLINK_ARPD", NETLINK_ARPD);
4635 #ifdef NETLINK_ROUTE6
4636 PyModule_AddIntConstant(m, "NETLINK_ROUTE6", NETLINK_ROUTE6);
4638 PyModule_AddIntConstant(m, "NETLINK_IP6_FW", NETLINK_IP6_FW);
4639 #ifdef NETLINK_DNRTMSG
4640 PyModule_AddIntConstant(m, "NETLINK_DNRTMSG", NETLINK_DNRTMSG);
4642 #ifdef NETLINK_TAPBASE
4643 PyModule_AddIntConstant(m, "NETLINK_TAPBASE", NETLINK_TAPBASE);
4645 #endif /* AF_NETLINK */
4647 /* Alias to emulate 4.4BSD */
4648 PyModule_AddIntConstant(m, "AF_ROUTE", AF_ROUTE);
4652 PyModule_AddIntConstant(m, "AF_ASH", AF_ASH);
4656 PyModule_AddIntConstant(m, "AF_ECONET", AF_ECONET);
4660 PyModule_AddIntConstant(m, "AF_ATMSVC", AF_ATMSVC);
4663 /* Linux SNA Project (nutters!) */
4664 PyModule_AddIntConstant(m, "AF_SNA", AF_SNA);
4668 PyModule_AddIntConstant(m, "AF_IRDA", AF_IRDA);
4672 PyModule_AddIntConstant(m, "AF_PPPOX", AF_PPPOX);
4675 /* Wanpipe API Sockets */
4676 PyModule_AddIntConstant(m, "AF_WANPIPE", AF_WANPIPE);
4680 PyModule_AddIntConstant(m, "AF_LLC", AF_LLC);
4683 #ifdef USE_BLUETOOTH
4684 PyModule_AddIntConstant(m, "AF_BLUETOOTH", AF_BLUETOOTH);
4685 PyModule_AddIntConstant(m, "BTPROTO_L2CAP", BTPROTO_L2CAP);
4686 PyModule_AddIntConstant(m, "BTPROTO_HCI", BTPROTO_HCI);
4687 PyModule_AddIntConstant(m, "SOL_HCI", SOL_HCI);
4688 #if !defined(__NetBSD__) && !defined(__DragonFly__)
4689 PyModule_AddIntConstant(m, "HCI_FILTER", HCI_FILTER);
4691 #if !defined(__FreeBSD__)
4692 #if !defined(__NetBSD__) && !defined(__DragonFly__)
4693 PyModule_AddIntConstant(m, "HCI_TIME_STAMP", HCI_TIME_STAMP);
4695 PyModule_AddIntConstant(m, "HCI_DATA_DIR", HCI_DATA_DIR);
4696 PyModule_AddIntConstant(m, "BTPROTO_SCO", BTPROTO_SCO);
4698 PyModule_AddIntConstant(m, "BTPROTO_RFCOMM", BTPROTO_RFCOMM);
4699 PyModule_AddStringConstant(m, "BDADDR_ANY", "00:00:00:00:00:00");
4700 PyModule_AddStringConstant(m, "BDADDR_LOCAL", "00:00:00:FF:FF:FF");
4704 PyModule_AddIntMacro(m, AF_PACKET);
4707 PyModule_AddIntMacro(m, PF_PACKET);
4710 PyModule_AddIntMacro(m, PACKET_HOST);
4712 #ifdef PACKET_BROADCAST
4713 PyModule_AddIntMacro(m, PACKET_BROADCAST);
4715 #ifdef PACKET_MULTICAST
4716 PyModule_AddIntMacro(m, PACKET_MULTICAST);
4718 #ifdef PACKET_OTHERHOST
4719 PyModule_AddIntMacro(m, PACKET_OTHERHOST);
4721 #ifdef PACKET_OUTGOING
4722 PyModule_AddIntMacro(m, PACKET_OUTGOING);
4724 #ifdef PACKET_LOOPBACK
4725 PyModule_AddIntMacro(m, PACKET_LOOPBACK);
4727 #ifdef PACKET_FASTROUTE
4728 PyModule_AddIntMacro(m, PACKET_FASTROUTE);
4731 #ifdef HAVE_LINUX_TIPC_H
4732 PyModule_AddIntConstant(m, "AF_TIPC", AF_TIPC);
4735 PyModule_AddIntConstant(m, "TIPC_ADDR_NAMESEQ", TIPC_ADDR_NAMESEQ);
4736 PyModule_AddIntConstant(m, "TIPC_ADDR_NAME", TIPC_ADDR_NAME);
4737 PyModule_AddIntConstant(m, "TIPC_ADDR_ID", TIPC_ADDR_ID);
4739 PyModule_AddIntConstant(m, "TIPC_ZONE_SCOPE", TIPC_ZONE_SCOPE);
4740 PyModule_AddIntConstant(m, "TIPC_CLUSTER_SCOPE", TIPC_CLUSTER_SCOPE);
4741 PyModule_AddIntConstant(m, "TIPC_NODE_SCOPE", TIPC_NODE_SCOPE);
4743 /* for setsockopt() */
4744 PyModule_AddIntConstant(m, "SOL_TIPC", SOL_TIPC);
4745 PyModule_AddIntConstant(m, "TIPC_IMPORTANCE", TIPC_IMPORTANCE);
4746 PyModule_AddIntConstant(m, "TIPC_SRC_DROPPABLE", TIPC_SRC_DROPPABLE);
4747 PyModule_AddIntConstant(m, "TIPC_DEST_DROPPABLE",
4748 TIPC_DEST_DROPPABLE);
4749 PyModule_AddIntConstant(m, "TIPC_CONN_TIMEOUT", TIPC_CONN_TIMEOUT);
4751 PyModule_AddIntConstant(m, "TIPC_LOW_IMPORTANCE",
4752 TIPC_LOW_IMPORTANCE);
4753 PyModule_AddIntConstant(m, "TIPC_MEDIUM_IMPORTANCE",
4754 TIPC_MEDIUM_IMPORTANCE);
4755 PyModule_AddIntConstant(m, "TIPC_HIGH_IMPORTANCE",
4756 TIPC_HIGH_IMPORTANCE);
4757 PyModule_AddIntConstant(m, "TIPC_CRITICAL_IMPORTANCE",
4758 TIPC_CRITICAL_IMPORTANCE);
4760 /* for subscriptions */
4761 PyModule_AddIntConstant(m, "TIPC_SUB_PORTS", TIPC_SUB_PORTS);
4762 PyModule_AddIntConstant(m, "TIPC_SUB_SERVICE", TIPC_SUB_SERVICE);
4763 #ifdef TIPC_SUB_CANCEL
4764 /* doesn't seem to be available everywhere */
4765 PyModule_AddIntConstant(m, "TIPC_SUB_CANCEL", TIPC_SUB_CANCEL);
4767 PyModule_AddIntConstant(m, "TIPC_WAIT_FOREVER", TIPC_WAIT_FOREVER);
4768 PyModule_AddIntConstant(m, "TIPC_PUBLISHED", TIPC_PUBLISHED);
4769 PyModule_AddIntConstant(m, "TIPC_WITHDRAWN", TIPC_WITHDRAWN);
4770 PyModule_AddIntConstant(m, "TIPC_SUBSCR_TIMEOUT", TIPC_SUBSCR_TIMEOUT);
4771 PyModule_AddIntConstant(m, "TIPC_CFG_SRV", TIPC_CFG_SRV);
4772 PyModule_AddIntConstant(m, "TIPC_TOP_SRV", TIPC_TOP_SRV);
4776 PyModule_AddIntConstant(m, "SOCK_STREAM", SOCK_STREAM);
4777 PyModule_AddIntConstant(m, "SOCK_DGRAM", SOCK_DGRAM);
4779 /* We have incomplete socket support. */
4780 PyModule_AddIntConstant(m, "SOCK_RAW", SOCK_RAW);
4781 PyModule_AddIntConstant(m, "SOCK_SEQPACKET", SOCK_SEQPACKET);
4782 #if defined(SOCK_RDM)
4783 PyModule_AddIntConstant(m, "SOCK_RDM", SOCK_RDM);
4788 PyModule_AddIntConstant(m, "SO_DEBUG", SO_DEBUG);
4790 #ifdef SO_ACCEPTCONN
4791 PyModule_AddIntConstant(m, "SO_ACCEPTCONN", SO_ACCEPTCONN);
4794 PyModule_AddIntConstant(m, "SO_REUSEADDR", SO_REUSEADDR);
4796 #ifdef SO_EXCLUSIVEADDRUSE
4797 PyModule_AddIntConstant(m, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE);
4801 PyModule_AddIntConstant(m, "SO_KEEPALIVE", SO_KEEPALIVE);
4804 PyModule_AddIntConstant(m, "SO_DONTROUTE", SO_DONTROUTE);
4807 PyModule_AddIntConstant(m, "SO_BROADCAST", SO_BROADCAST);
4809 #ifdef SO_USELOOPBACK
4810 PyModule_AddIntConstant(m, "SO_USELOOPBACK", SO_USELOOPBACK);
4813 PyModule_AddIntConstant(m, "SO_LINGER", SO_LINGER);
4816 PyModule_AddIntConstant(m, "SO_OOBINLINE", SO_OOBINLINE);
4819 PyModule_AddIntConstant(m, "SO_REUSEPORT", SO_REUSEPORT);
4822 PyModule_AddIntConstant(m, "SO_SNDBUF", SO_SNDBUF);
4825 PyModule_AddIntConstant(m, "SO_RCVBUF", SO_RCVBUF);
4828 PyModule_AddIntConstant(m, "SO_SNDLOWAT", SO_SNDLOWAT);
4831 PyModule_AddIntConstant(m, "SO_RCVLOWAT", SO_RCVLOWAT);
4834 PyModule_AddIntConstant(m, "SO_SNDTIMEO", SO_SNDTIMEO);
4837 PyModule_AddIntConstant(m, "SO_RCVTIMEO", SO_RCVTIMEO);
4840 PyModule_AddIntConstant(m, "SO_ERROR", SO_ERROR);
4843 PyModule_AddIntConstant(m, "SO_TYPE", SO_TYPE);
4846 PyModule_AddIntConstant(m, "SO_SETFIB", SO_SETFIB);
4849 /* Maximum number of connections for "listen" */
4851 PyModule_AddIntConstant(m, "SOMAXCONN", SOMAXCONN);
4853 PyModule_AddIntConstant(m, "SOMAXCONN", 5); /* Common value */
4856 /* Flags for send, recv */
4858 PyModule_AddIntConstant(m, "MSG_OOB", MSG_OOB);
4861 PyModule_AddIntConstant(m, "MSG_PEEK", MSG_PEEK);
4863 #ifdef MSG_DONTROUTE
4864 PyModule_AddIntConstant(m, "MSG_DONTROUTE", MSG_DONTROUTE);
4867 PyModule_AddIntConstant(m, "MSG_DONTWAIT", MSG_DONTWAIT);
4870 PyModule_AddIntConstant(m, "MSG_EOR", MSG_EOR);
4873 PyModule_AddIntConstant(m, "MSG_TRUNC", MSG_TRUNC);
4876 PyModule_AddIntConstant(m, "MSG_CTRUNC", MSG_CTRUNC);
4879 PyModule_AddIntConstant(m, "MSG_WAITALL", MSG_WAITALL);
4882 PyModule_AddIntConstant(m, "MSG_BTAG", MSG_BTAG);
4885 PyModule_AddIntConstant(m, "MSG_ETAG", MSG_ETAG);
4888 /* Protocol level and numbers, usable for [gs]etsockopt */
4890 PyModule_AddIntConstant(m, "SOL_SOCKET", SOL_SOCKET);
4893 PyModule_AddIntConstant(m, "SOL_IP", SOL_IP);
4895 PyModule_AddIntConstant(m, "SOL_IP", 0);
4898 PyModule_AddIntConstant(m, "SOL_IPX", SOL_IPX);
4901 PyModule_AddIntConstant(m, "SOL_AX25", SOL_AX25);
4904 PyModule_AddIntConstant(m, "SOL_ATALK", SOL_ATALK);
4907 PyModule_AddIntConstant(m, "SOL_NETROM", SOL_NETROM);
4910 PyModule_AddIntConstant(m, "SOL_ROSE", SOL_ROSE);
4913 PyModule_AddIntConstant(m, "SOL_TCP", SOL_TCP);
4915 PyModule_AddIntConstant(m, "SOL_TCP", 6);
4918 PyModule_AddIntConstant(m, "SOL_UDP", SOL_UDP);
4920 PyModule_AddIntConstant(m, "SOL_UDP", 17);
4923 PyModule_AddIntConstant(m, "IPPROTO_IP", IPPROTO_IP);
4925 PyModule_AddIntConstant(m, "IPPROTO_IP", 0);
4927 #ifdef IPPROTO_HOPOPTS
4928 PyModule_AddIntConstant(m, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS);
4931 PyModule_AddIntConstant(m, "IPPROTO_ICMP", IPPROTO_ICMP);
4933 PyModule_AddIntConstant(m, "IPPROTO_ICMP", 1);
4936 PyModule_AddIntConstant(m, "IPPROTO_IGMP", IPPROTO_IGMP);
4939 PyModule_AddIntConstant(m, "IPPROTO_GGP", IPPROTO_GGP);
4942 PyModule_AddIntConstant(m, "IPPROTO_IPV4", IPPROTO_IPV4);
4945 PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
4948 PyModule_AddIntConstant(m, "IPPROTO_IPIP", IPPROTO_IPIP);
4951 PyModule_AddIntConstant(m, "IPPROTO_TCP", IPPROTO_TCP);
4953 PyModule_AddIntConstant(m, "IPPROTO_TCP", 6);
4956 PyModule_AddIntConstant(m, "IPPROTO_EGP", IPPROTO_EGP);
4959 PyModule_AddIntConstant(m, "IPPROTO_PUP", IPPROTO_PUP);
4962 PyModule_AddIntConstant(m, "IPPROTO_UDP", IPPROTO_UDP);
4964 PyModule_AddIntConstant(m, "IPPROTO_UDP", 17);
4967 PyModule_AddIntConstant(m, "IPPROTO_IDP", IPPROTO_IDP);
4969 #ifdef IPPROTO_HELLO
4970 PyModule_AddIntConstant(m, "IPPROTO_HELLO", IPPROTO_HELLO);
4973 PyModule_AddIntConstant(m, "IPPROTO_ND", IPPROTO_ND);
4976 PyModule_AddIntConstant(m, "IPPROTO_TP", IPPROTO_TP);
4979 PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
4981 #ifdef IPPROTO_ROUTING
4982 PyModule_AddIntConstant(m, "IPPROTO_ROUTING", IPPROTO_ROUTING);
4984 #ifdef IPPROTO_FRAGMENT
4985 PyModule_AddIntConstant(m, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT);
4988 PyModule_AddIntConstant(m, "IPPROTO_RSVP", IPPROTO_RSVP);
4991 PyModule_AddIntConstant(m, "IPPROTO_GRE", IPPROTO_GRE);
4994 PyModule_AddIntConstant(m, "IPPROTO_ESP", IPPROTO_ESP);
4997 PyModule_AddIntConstant(m, "IPPROTO_AH", IPPROTO_AH);
4999 #ifdef IPPROTO_MOBILE
5000 PyModule_AddIntConstant(m, "IPPROTO_MOBILE", IPPROTO_MOBILE);
5002 #ifdef IPPROTO_ICMPV6
5003 PyModule_AddIntConstant(m, "IPPROTO_ICMPV6", IPPROTO_ICMPV6);
5006 PyModule_AddIntConstant(m, "IPPROTO_NONE", IPPROTO_NONE);
5008 #ifdef IPPROTO_DSTOPTS
5009 PyModule_AddIntConstant(m, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS);
5012 PyModule_AddIntConstant(m, "IPPROTO_XTP", IPPROTO_XTP);
5015 PyModule_AddIntConstant(m, "IPPROTO_EON", IPPROTO_EON);
5018 PyModule_AddIntConstant(m, "IPPROTO_PIM", IPPROTO_PIM);
5020 #ifdef IPPROTO_IPCOMP
5021 PyModule_AddIntConstant(m, "IPPROTO_IPCOMP", IPPROTO_IPCOMP);
5024 PyModule_AddIntConstant(m, "IPPROTO_VRRP", IPPROTO_VRRP);
5027 PyModule_AddIntConstant(m, "IPPROTO_BIP", IPPROTO_BIP);
5031 PyModule_AddIntConstant(m, "IPPROTO_RAW", IPPROTO_RAW);
5033 PyModule_AddIntConstant(m, "IPPROTO_RAW", 255);
5036 PyModule_AddIntConstant(m, "IPPROTO_MAX", IPPROTO_MAX);
5039 /* Some port configuration */
5040 #ifdef IPPORT_RESERVED
5041 PyModule_AddIntConstant(m, "IPPORT_RESERVED", IPPORT_RESERVED);
5043 PyModule_AddIntConstant(m, "IPPORT_RESERVED", 1024);
5045 #ifdef IPPORT_USERRESERVED
5046 PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", IPPORT_USERRESERVED);
5048 PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", 5000);
5051 /* Some reserved IP v.4 addresses */
5053 PyModule_AddIntConstant(m, "INADDR_ANY", INADDR_ANY);
5055 PyModule_AddIntConstant(m, "INADDR_ANY", 0x00000000);
5057 #ifdef INADDR_BROADCAST
5058 PyModule_AddIntConstant(m, "INADDR_BROADCAST", INADDR_BROADCAST);
5060 PyModule_AddIntConstant(m, "INADDR_BROADCAST", 0xffffffff);
5062 #ifdef INADDR_LOOPBACK
5063 PyModule_AddIntConstant(m, "INADDR_LOOPBACK", INADDR_LOOPBACK);
5065 PyModule_AddIntConstant(m, "INADDR_LOOPBACK", 0x7F000001);
5067 #ifdef INADDR_UNSPEC_GROUP
5068 PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
5070 PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", 0xe0000000);
5072 #ifdef INADDR_ALLHOSTS_GROUP
5073 PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP",
5074 INADDR_ALLHOSTS_GROUP);
5076 PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
5078 #ifdef INADDR_MAX_LOCAL_GROUP
5079 PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP",
5080 INADDR_MAX_LOCAL_GROUP);
5082 PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
5085 PyModule_AddIntConstant(m, "INADDR_NONE", INADDR_NONE);
5087 PyModule_AddIntConstant(m, "INADDR_NONE", 0xffffffff);
5090 /* IPv4 [gs]etsockopt options */
5092 PyModule_AddIntConstant(m, "IP_OPTIONS", IP_OPTIONS);
5095 PyModule_AddIntConstant(m, "IP_HDRINCL", IP_HDRINCL);
5098 PyModule_AddIntConstant(m, "IP_TOS", IP_TOS);
5101 PyModule_AddIntConstant(m, "IP_TTL", IP_TTL);
5104 PyModule_AddIntConstant(m, "IP_RECVOPTS", IP_RECVOPTS);
5106 #ifdef IP_RECVRETOPTS
5107 PyModule_AddIntConstant(m, "IP_RECVRETOPTS", IP_RECVRETOPTS);
5109 #ifdef IP_RECVDSTADDR
5110 PyModule_AddIntConstant(m, "IP_RECVDSTADDR", IP_RECVDSTADDR);
5113 PyModule_AddIntConstant(m, "IP_RETOPTS", IP_RETOPTS);
5115 #ifdef IP_MULTICAST_IF
5116 PyModule_AddIntConstant(m, "IP_MULTICAST_IF", IP_MULTICAST_IF);
5118 #ifdef IP_MULTICAST_TTL
5119 PyModule_AddIntConstant(m, "IP_MULTICAST_TTL", IP_MULTICAST_TTL);
5121 #ifdef IP_MULTICAST_LOOP
5122 PyModule_AddIntConstant(m, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
5124 #ifdef IP_ADD_MEMBERSHIP
5125 PyModule_AddIntConstant(m, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
5127 #ifdef IP_DROP_MEMBERSHIP
5128 PyModule_AddIntConstant(m, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
5130 #ifdef IP_DEFAULT_MULTICAST_TTL
5131 PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_TTL",
5132 IP_DEFAULT_MULTICAST_TTL);
5134 #ifdef IP_DEFAULT_MULTICAST_LOOP
5135 PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_LOOP",
5136 IP_DEFAULT_MULTICAST_LOOP);
5138 #ifdef IP_MAX_MEMBERSHIPS
5139 PyModule_AddIntConstant(m, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS);
5142 /* IPv6 [gs]etsockopt options, defined in RFC2553 */
5143 #ifdef IPV6_JOIN_GROUP
5144 PyModule_AddIntConstant(m, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP);
5146 #ifdef IPV6_LEAVE_GROUP
5147 PyModule_AddIntConstant(m, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP);
5149 #ifdef IPV6_MULTICAST_HOPS
5150 PyModule_AddIntConstant(m, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS);
5152 #ifdef IPV6_MULTICAST_IF
5153 PyModule_AddIntConstant(m, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF);
5155 #ifdef IPV6_MULTICAST_LOOP
5156 PyModule_AddIntConstant(m, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP);
5158 #ifdef IPV6_UNICAST_HOPS
5159 PyModule_AddIntConstant(m, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS);
5161 /* Additional IPV6 socket options, defined in RFC 3493 */
5163 PyModule_AddIntConstant(m, "IPV6_V6ONLY", IPV6_V6ONLY);
5165 /* Advanced IPV6 socket options, from RFC 3542 */
5166 #ifdef IPV6_CHECKSUM
5167 PyModule_AddIntConstant(m, "IPV6_CHECKSUM", IPV6_CHECKSUM);
5169 #ifdef IPV6_DONTFRAG
5170 PyModule_AddIntConstant(m, "IPV6_DONTFRAG", IPV6_DONTFRAG);
5173 PyModule_AddIntConstant(m, "IPV6_DSTOPTS", IPV6_DSTOPTS);
5175 #ifdef IPV6_HOPLIMIT
5176 PyModule_AddIntConstant(m, "IPV6_HOPLIMIT", IPV6_HOPLIMIT);
5179 PyModule_AddIntConstant(m, "IPV6_HOPOPTS", IPV6_HOPOPTS);
5182 PyModule_AddIntConstant(m, "IPV6_NEXTHOP", IPV6_NEXTHOP);
5185 PyModule_AddIntConstant(m, "IPV6_PATHMTU", IPV6_PATHMTU);
5188 PyModule_AddIntConstant(m, "IPV6_PKTINFO", IPV6_PKTINFO);
5190 #ifdef IPV6_RECVDSTOPTS
5191 PyModule_AddIntConstant(m, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS);
5193 #ifdef IPV6_RECVHOPLIMIT
5194 PyModule_AddIntConstant(m, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT);
5196 #ifdef IPV6_RECVHOPOPTS
5197 PyModule_AddIntConstant(m, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS);
5199 #ifdef IPV6_RECVPKTINFO
5200 PyModule_AddIntConstant(m, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO);
5202 #ifdef IPV6_RECVRTHDR
5203 PyModule_AddIntConstant(m, "IPV6_RECVRTHDR", IPV6_RECVRTHDR);
5205 #ifdef IPV6_RECVTCLASS
5206 PyModule_AddIntConstant(m, "IPV6_RECVTCLASS", IPV6_RECVTCLASS);
5209 PyModule_AddIntConstant(m, "IPV6_RTHDR", IPV6_RTHDR);
5211 #ifdef IPV6_RTHDRDSTOPTS
5212 PyModule_AddIntConstant(m, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS);
5214 #ifdef IPV6_RTHDR_TYPE_0
5215 PyModule_AddIntConstant(m, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0);
5217 #ifdef IPV6_RECVPATHMTU
5218 PyModule_AddIntConstant(m, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU);
5221 PyModule_AddIntConstant(m, "IPV6_TCLASS", IPV6_TCLASS);
5223 #ifdef IPV6_USE_MIN_MTU
5224 PyModule_AddIntConstant(m, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU);
5229 PyModule_AddIntConstant(m, "TCP_NODELAY", TCP_NODELAY);
5232 PyModule_AddIntConstant(m, "TCP_MAXSEG", TCP_MAXSEG);
5235 PyModule_AddIntConstant(m, "TCP_CORK", TCP_CORK);
5238 PyModule_AddIntConstant(m, "TCP_KEEPIDLE", TCP_KEEPIDLE);
5240 #ifdef TCP_KEEPINTVL
5241 PyModule_AddIntConstant(m, "TCP_KEEPINTVL", TCP_KEEPINTVL);
5244 PyModule_AddIntConstant(m, "TCP_KEEPCNT", TCP_KEEPCNT);
5247 PyModule_AddIntConstant(m, "TCP_SYNCNT", TCP_SYNCNT);
5250 PyModule_AddIntConstant(m, "TCP_LINGER2", TCP_LINGER2);
5252 #ifdef TCP_DEFER_ACCEPT
5253 PyModule_AddIntConstant(m, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT);
5255 #ifdef TCP_WINDOW_CLAMP
5256 PyModule_AddIntConstant(m, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP);
5259 PyModule_AddIntConstant(m, "TCP_INFO", TCP_INFO);
5262 PyModule_AddIntConstant(m, "TCP_QUICKACK", TCP_QUICKACK);
5268 PyModule_AddIntConstant(m, "IPX_TYPE", IPX_TYPE);
5271 /* get{addr,name}info parameters */
5272 #ifdef EAI_ADDRFAMILY
5273 PyModule_AddIntConstant(m, "EAI_ADDRFAMILY", EAI_ADDRFAMILY);
5276 PyModule_AddIntConstant(m, "EAI_AGAIN", EAI_AGAIN);
5279 PyModule_AddIntConstant(m, "EAI_BADFLAGS", EAI_BADFLAGS);
5282 PyModule_AddIntConstant(m, "EAI_FAIL", EAI_FAIL);
5285 PyModule_AddIntConstant(m, "EAI_FAMILY", EAI_FAMILY);
5288 PyModule_AddIntConstant(m, "EAI_MEMORY", EAI_MEMORY);
5291 PyModule_AddIntConstant(m, "EAI_NODATA", EAI_NODATA);
5294 PyModule_AddIntConstant(m, "EAI_NONAME", EAI_NONAME);
5297 PyModule_AddIntConstant(m, "EAI_OVERFLOW", EAI_OVERFLOW);
5300 PyModule_AddIntConstant(m, "EAI_SERVICE", EAI_SERVICE);
5303 PyModule_AddIntConstant(m, "EAI_SOCKTYPE", EAI_SOCKTYPE);
5306 PyModule_AddIntConstant(m, "EAI_SYSTEM", EAI_SYSTEM);
5309 PyModule_AddIntConstant(m, "EAI_BADHINTS", EAI_BADHINTS);
5312 PyModule_AddIntConstant(m, "EAI_PROTOCOL", EAI_PROTOCOL);
5315 PyModule_AddIntConstant(m, "EAI_MAX", EAI_MAX);
5318 PyModule_AddIntConstant(m, "AI_PASSIVE", AI_PASSIVE);
5321 PyModule_AddIntConstant(m, "AI_CANONNAME", AI_CANONNAME);
5323 #ifdef AI_NUMERICHOST
5324 PyModule_AddIntConstant(m, "AI_NUMERICHOST", AI_NUMERICHOST);
5326 #ifdef AI_NUMERICSERV
5327 PyModule_AddIntConstant(m, "AI_NUMERICSERV", AI_NUMERICSERV);
5330 PyModule_AddIntConstant(m, "AI_MASK", AI_MASK);
5333 PyModule_AddIntConstant(m, "AI_ALL", AI_ALL);
5335 #ifdef AI_V4MAPPED_CFG
5336 PyModule_AddIntConstant(m, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG);
5338 #ifdef AI_ADDRCONFIG
5339 PyModule_AddIntConstant(m, "AI_ADDRCONFIG", AI_ADDRCONFIG);
5342 PyModule_AddIntConstant(m, "AI_V4MAPPED", AI_V4MAPPED);
5345 PyModule_AddIntConstant(m, "AI_DEFAULT", AI_DEFAULT);
5348 PyModule_AddIntConstant(m, "NI_MAXHOST", NI_MAXHOST);
5351 PyModule_AddIntConstant(m, "NI_MAXSERV", NI_MAXSERV);
5354 PyModule_AddIntConstant(m, "NI_NOFQDN", NI_NOFQDN);
5356 #ifdef NI_NUMERICHOST
5357 PyModule_AddIntConstant(m, "NI_NUMERICHOST", NI_NUMERICHOST);
5360 PyModule_AddIntConstant(m, "NI_NAMEREQD", NI_NAMEREQD);
5362 #ifdef NI_NUMERICSERV
5363 PyModule_AddIntConstant(m, "NI_NUMERICSERV", NI_NUMERICSERV);
5366 PyModule_AddIntConstant(m, "NI_DGRAM", NI_DGRAM);
5369 /* shutdown() parameters */
5371 PyModule_AddIntConstant(m, "SHUT_RD", SHUT_RD);
5372 #elif defined(SD_RECEIVE)
5373 PyModule_AddIntConstant(m, "SHUT_RD", SD_RECEIVE);
5375 PyModule_AddIntConstant(m, "SHUT_RD", 0);
5378 PyModule_AddIntConstant(m, "SHUT_WR", SHUT_WR);
5379 #elif defined(SD_SEND)
5380 PyModule_AddIntConstant(m, "SHUT_WR", SD_SEND);
5382 PyModule_AddIntConstant(m, "SHUT_WR", 1);
5385 PyModule_AddIntConstant(m, "SHUT_RDWR", SHUT_RDWR);
5386 #elif defined(SD_BOTH)
5387 PyModule_AddIntConstant(m, "SHUT_RDWR", SD_BOTH);
5389 PyModule_AddIntConstant(m, "SHUT_RDWR", 2);
5394 DWORD codes[] = {SIO_RCVALL, SIO_KEEPALIVE_VALS};
5395 const char *names[] = {"SIO_RCVALL", "SIO_KEEPALIVE_VALS"};
5397 for(i = 0; i<sizeof(codes)/sizeof(*codes); ++i) {
5399 tmp = PyLong_FromUnsignedLong(codes[i]);
5402 PyModule_AddObject(m, names[i], tmp);
5405 PyModule_AddIntConstant(m, "RCVALL_OFF", RCVALL_OFF);
5406 PyModule_AddIntConstant(m, "RCVALL_ON", RCVALL_ON);
5407 PyModule_AddIntConstant(m, "RCVALL_SOCKETLEVELONLY", RCVALL_SOCKETLEVELONLY);
5408 #ifdef RCVALL_IPLEVEL
5409 PyModule_AddIntConstant(m, "RCVALL_IPLEVEL", RCVALL_IPLEVEL);
5412 PyModule_AddIntConstant(m, "RCVALL_MAX", RCVALL_MAX);
5414 #endif /* _MSTCPIP_ */
5416 /* Initialize gethostbyname lock */
5417 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
5418 netdb_lock = PyThread_allocate_lock();
5423 #ifndef HAVE_INET_PTON
5424 #if !defined(NTDDI_VERSION) || (NTDDI_VERSION < NTDDI_LONGHORN)
5426 /* Simplistic emulation code for inet_pton that only works for IPv4 */
5427 /* These are not exposed because they do not set errno properly */
5430 inet_pton(int af, const char *src, void *dst)
5432 if (af == AF_INET) {
5433 #if (SIZEOF_INT != 4)
5434 #error "Not sure if in_addr_t exists and int is not 32-bits."
5436 unsigned int packed_addr;
5437 packed_addr = inet_addr(src);
5438 if (packed_addr == INADDR_NONE)
5440 memcpy(dst, &packed_addr, 4);
5443 /* Should set errno to EAFNOSUPPORT */
5448 inet_ntop(int af, const void *src, char *dst, socklen_t size)
5450 if (af == AF_INET) {
5451 struct in_addr packed_addr;
5453 /* Should set errno to ENOSPC. */
5455 memcpy(&packed_addr, src, sizeof(packed_addr));
5456 return strncpy(dst, inet_ntoa(packed_addr), size);
5458 /* Should set errno to EAFNOSUPPORT */