issue5063: Fixes for building RPM on CentOS plus misc .spec file enhancements.
[python.git] / Modules / socketmodule.c
blob396a43deca6e0b84d24548fea527d4a5974d0d44
1 /* Socket module */
3 /*
5 This module provides an interface to Berkeley socket IPC.
7 Limitations:
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
11 under Linux.
12 - No read/write operations (use sendall/recv or makefile instead).
13 - Additional restrictions apply on some non-Unix platforms (compensated
14 for by socket.py).
16 Module interface:
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:
63 v1 is the server type
64 v2 is the port identifier
65 v3 is ignored
66 if addr_type is TIPC_ADDR_NAMESEQ:
67 v1 is the server type
68 v2 is the lower port number
69 v3 is the upper port number
70 if addr_type is TIPC_ADDR_ID:
71 v1 is the node
72 v2 is the ref
73 v3 is ignored
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
84 #ifdef __APPLE__
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
91 #endif
93 #include "Python.h"
94 #include "structmember.h"
96 #undef MAX
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! */
149 #ifndef linux
150 # undef HAVE_GETHOSTBYNAME_R_3_ARG
151 # undef HAVE_GETHOSTBYNAME_R_5_ARG
152 # undef HAVE_GETHOSTBYNAME_R_6_ARG
153 #endif
155 #ifndef WITH_THREAD
156 # undef HAVE_GETHOSTBYNAME_R
157 #endif
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 */
166 # else
167 # undef HAVE_GETHOSTBYNAME_R
168 # endif
169 #endif
171 #if !defined(HAVE_GETHOSTBYNAME_R) && defined(WITH_THREAD) && \
172 !defined(MS_WINDOWS)
173 # define USE_GETHOSTBYNAME_LOCK
174 #endif
176 /* To use __FreeBSD_version */
177 #ifdef HAVE_SYS_PARAM_H
178 #include <sys/param.h>
179 #endif
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
187 #endif
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);
192 #else
193 #define ACQUIRE_GETADDRINFO_LOCK
194 #define RELEASE_GETADDRINFO_LOCK
195 #endif
197 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
198 # include "pythread.h"
199 #endif
201 #if defined(PYCC_VACPP)
202 # include <types.h>
203 # include <io.h>
204 # include <sys/ioctl.h>
205 # include <utils.h>
206 # include <ctype.h>
207 #endif
209 #if defined(__VMS)
210 # include <ioctl.h>
211 #endif
213 #if defined(PYOS_OS2)
214 # define INCL_DOS
215 # define INCL_DOSERRORS
216 # define INCL_NOPMAPI
217 # include <os2.h>
218 #endif
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 */
228 #define _SGIAPI 1
230 #undef _XOPEN_SOURCE
231 #include <sys/socket.h>
232 #include <sys/types.h>
233 #include <netinet/in.h>
234 #ifdef _SS_ALIGNSIZE
235 #define HAVE_GETADDRINFO 1
236 #define HAVE_GETNAMEINFO 1
237 #endif
239 #define HAVE_INET_PTON
240 #include <netdb.h>
241 #endif
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
248 #endif
250 /* Generic includes */
251 #ifdef HAVE_SYS_TYPES_H
252 #include <sys/types.h>
253 #endif
255 /* Generic socket object definitions and includes */
256 #define PySocket_BUILDING_SOCKET
257 #include "socketmodule.h"
259 /* Addressing includes */
261 #ifndef MS_WINDOWS
263 /* Non-MS WINDOWS includes */
264 # include <netdb.h>
266 /* Headers needed for inet_ntoa() and inet_addr() */
267 # ifdef __BEOS__
268 # include <net/netdb.h>
269 # elif defined(PYOS_OS2) && defined(PYCC_VACPP)
270 # include <netdb.h>
271 typedef size_t socklen_t;
272 # else
273 # include <arpa/inet.h>
274 # endif
276 # ifndef RISCOS
277 # include <fcntl.h>
278 # else
279 # include <sys/ioctl.h>
280 # include <socklib.h>
281 # define NO_DUP
282 int h_errno; /* not used */
283 # define INET_ADDRSTRLEN 16
284 # endif
286 #else
288 /* MS_WINDOWS includes */
289 # ifdef HAVE_FCNTL_H
290 # include <fcntl.h>
291 # endif
293 #endif
295 #include <stddef.h>
297 #ifndef offsetof
298 # define offsetof(type, member) ((size_t)(&((type *)0)->member))
299 #endif
301 #ifndef O_NONBLOCK
302 # define O_NONBLOCK O_NDELAY
303 #endif
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.
315 #else
316 # include "addrinfo.h"
317 #endif
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);
323 #endif
324 #endif
326 #ifdef __APPLE__
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
340 #endif
342 #ifdef HAVE_INET_ATON
343 #define USE_INET_ATON_WEAKLINK
344 #endif
346 #endif
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"
355 #endif
356 #if !defined(HAVE_GETNAMEINFO)
357 #define getnameinfo fake_getnameinfo
358 #include "getnameinfo.c"
359 #endif
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... */
366 #endif
368 #ifdef MS_WIN32
369 #define EAFNOSUPPORT WSAEAFNOSUPPORT
370 #define snprintf _snprintf
371 #endif
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 */
376 #endif
378 #ifndef SOCKETCLOSE
379 #define SOCKETCLOSE close
380 #endif
382 #if defined(HAVE_BLUETOOTH_H) || defined(HAVE_BLUETOOTH_BLUETOOTH_H) && !defined(__NetBSD__)
383 #define USE_BLUETOOTH 1
384 #if defined(__FreeBSD__)
385 #define BTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP
386 #define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM
387 #define BTPROTO_HCI BLUETOOTH_PROTO_HCI
388 #define SOL_HCI SOL_HCI_RAW
389 #define HCI_FILTER SO_HCI_RAW_FILTER
390 #define sockaddr_l2 sockaddr_l2cap
391 #define sockaddr_rc sockaddr_rfcomm
392 #define hci_dev hci_node
393 #define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb)
394 #define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)
395 #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
396 #elif defined(__NetBSD__)
397 #define sockaddr_l2 sockaddr_bt
398 #define sockaddr_rc sockaddr_bt
399 #define sockaddr_hci sockaddr_bt
400 #define sockaddr_sco sockaddr_bt
401 #define _BT_L2_MEMB(sa, memb) ((sa)->bt_##memb)
402 #define _BT_RC_MEMB(sa, memb) ((sa)->bt_##memb)
403 #define _BT_HCI_MEMB(sa, memb) ((sa)->bt_##memb)
404 #define _BT_SCO_MEMB(sa, memb) ((sa)->bt_##memb)
405 #else
406 #define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb)
407 #define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb)
408 #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
409 #define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)
410 #endif
411 #endif
413 #ifdef __VMS
414 /* TCP/IP Services for VMS uses a maximum send/recv buffer length */
415 #define SEGMENT_SIZE (32 * 1024 -1)
416 #endif
418 #define SAS2SA(x) ((struct sockaddr *)(x))
421 * Constants for getnameinfo()
423 #if !defined(NI_MAXHOST)
424 #define NI_MAXHOST 1025
425 #endif
426 #if !defined(NI_MAXSERV)
427 #define NI_MAXSERV 32
428 #endif
430 /* XXX There's a problem here: *static* functions are not supposed to have
431 a Py prefix (or use CapitalizedWords). Later... */
433 /* Global variable holding the exception type for errors detected
434 by this module (but not argument type or memory errors, etc.). */
435 static PyObject *socket_error;
436 static PyObject *socket_herror;
437 static PyObject *socket_gaierror;
438 static PyObject *socket_timeout;
440 #ifdef RISCOS
441 /* Global variable which is !=0 if Python is running in a RISC OS taskwindow */
442 static int taskwindow;
443 #endif
445 /* A forward reference to the socket type object.
446 The sock_type variable contains pointers to various functions,
447 some of which call new_sockobject(), which uses sock_type, so
448 there has to be a circular reference. */
449 static PyTypeObject sock_type;
451 #if defined(HAVE_POLL_H)
452 #include <poll.h>
453 #elif defined(HAVE_SYS_POLL_H)
454 #include <sys/poll.h>
455 #endif
457 #ifdef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
458 /* Platform can select file descriptors beyond FD_SETSIZE */
459 #define IS_SELECTABLE(s) 1
460 #elif defined(HAVE_POLL)
461 /* Instead of select(), we'll use poll() since poll() works on any fd. */
462 #define IS_SELECTABLE(s) 1
463 /* Can we call select() with this socket without a buffer overrun? */
464 #else
465 /* POSIX says selecting file descriptors beyond FD_SETSIZE
466 has undefined behaviour. If there's no timeout left, we don't have to
467 call select, so it's a safe, little white lie. */
468 #define IS_SELECTABLE(s) ((s)->sock_fd < FD_SETSIZE || s->sock_timeout <= 0.0)
469 #endif
471 static PyObject*
472 select_error(void)
474 PyErr_SetString(socket_error, "unable to select on socket");
475 return NULL;
478 /* Convenience function to raise an error according to errno
479 and return a NULL pointer from a function. */
481 static PyObject *
482 set_error(void)
484 #ifdef MS_WINDOWS
485 int err_no = WSAGetLastError();
486 /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which
487 recognizes the error codes used by both GetLastError() and
488 WSAGetLastError */
489 if (err_no)
490 return PyErr_SetExcFromWindowsErr(socket_error, err_no);
491 #endif
493 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
494 if (sock_errno() != NO_ERROR) {
495 APIRET rc;
496 ULONG msglen;
497 char outbuf[100];
498 int myerrorcode = sock_errno();
500 /* Retrieve socket-related error message from MPTN.MSG file */
501 rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf),
502 myerrorcode - SOCBASEERR + 26,
503 "mptn.msg",
504 &msglen);
505 if (rc == NO_ERROR) {
506 PyObject *v;
508 /* OS/2 doesn't guarantee a terminator */
509 outbuf[msglen] = '\0';
510 if (strlen(outbuf) > 0) {
511 /* If non-empty msg, trim CRLF */
512 char *lastc = &outbuf[ strlen(outbuf)-1 ];
513 while (lastc > outbuf &&
514 isspace(Py_CHARMASK(*lastc))) {
515 /* Trim trailing whitespace (CRLF) */
516 *lastc-- = '\0';
519 v = Py_BuildValue("(is)", myerrorcode, outbuf);
520 if (v != NULL) {
521 PyErr_SetObject(socket_error, v);
522 Py_DECREF(v);
524 return NULL;
527 #endif
529 #if defined(RISCOS)
530 if (_inet_error.errnum != NULL) {
531 PyObject *v;
532 v = Py_BuildValue("(is)", errno, _inet_err());
533 if (v != NULL) {
534 PyErr_SetObject(socket_error, v);
535 Py_DECREF(v);
537 return NULL;
539 #endif
541 return PyErr_SetFromErrno(socket_error);
545 static PyObject *
546 set_herror(int h_error)
548 PyObject *v;
550 #ifdef HAVE_HSTRERROR
551 v = Py_BuildValue("(is)", h_error, (char *)hstrerror(h_error));
552 #else
553 v = Py_BuildValue("(is)", h_error, "host not found");
554 #endif
555 if (v != NULL) {
556 PyErr_SetObject(socket_herror, v);
557 Py_DECREF(v);
560 return NULL;
564 static PyObject *
565 set_gaierror(int error)
567 PyObject *v;
569 #ifdef EAI_SYSTEM
570 /* EAI_SYSTEM is not available on Windows XP. */
571 if (error == EAI_SYSTEM)
572 return set_error();
573 #endif
575 #ifdef HAVE_GAI_STRERROR
576 v = Py_BuildValue("(is)", error, gai_strerror(error));
577 #else
578 v = Py_BuildValue("(is)", error, "getaddrinfo failed");
579 #endif
580 if (v != NULL) {
581 PyErr_SetObject(socket_gaierror, v);
582 Py_DECREF(v);
585 return NULL;
588 #ifdef __VMS
589 /* Function to send in segments */
590 static int
591 sendsegmented(int sock_fd, char *buf, int len, int flags)
593 int n = 0;
594 int remaining = len;
596 while (remaining > 0) {
597 unsigned int segment;
599 segment = (remaining >= SEGMENT_SIZE ? SEGMENT_SIZE : remaining);
600 n = send(sock_fd, buf, segment, flags);
601 if (n < 0) {
602 return n;
604 remaining -= segment;
605 buf += segment;
606 } /* end while */
608 return len;
610 #endif
612 /* Function to perform the setting of socket blocking mode
613 internally. block = (1 | 0). */
614 static int
615 internal_setblocking(PySocketSockObject *s, int block)
617 #ifndef RISCOS
618 #ifndef MS_WINDOWS
619 int delay_flag;
620 #endif
621 #endif
623 Py_BEGIN_ALLOW_THREADS
624 #ifdef __BEOS__
625 block = !block;
626 setsockopt(s->sock_fd, SOL_SOCKET, SO_NONBLOCK,
627 (void *)(&block), sizeof(int));
628 #else
629 #ifndef RISCOS
630 #ifndef MS_WINDOWS
631 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
632 block = !block;
633 ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block));
634 #elif defined(__VMS)
635 block = !block;
636 ioctl(s->sock_fd, FIONBIO, (unsigned int *)&block);
637 #else /* !PYOS_OS2 && !__VMS */
638 delay_flag = fcntl(s->sock_fd, F_GETFL, 0);
639 if (block)
640 delay_flag &= (~O_NONBLOCK);
641 else
642 delay_flag |= O_NONBLOCK;
643 fcntl(s->sock_fd, F_SETFL, delay_flag);
644 #endif /* !PYOS_OS2 */
645 #else /* MS_WINDOWS */
646 block = !block;
647 ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
648 #endif /* MS_WINDOWS */
649 #else /* RISCOS */
650 block = !block;
651 socketioctl(s->sock_fd, FIONBIO, (u_long*)&block);
652 #endif /* RISCOS */
653 #endif /* __BEOS__ */
654 Py_END_ALLOW_THREADS
656 /* Since these don't return anything */
657 return 1;
660 /* Do a select()/poll() on the socket, if necessary (sock_timeout > 0).
661 The argument writing indicates the direction.
662 This does not raise an exception; we'll let our caller do that
663 after they've reacquired the interpreter lock.
664 Returns 1 on timeout, -1 on error, 0 otherwise. */
665 static int
666 internal_select(PySocketSockObject *s, int writing)
668 int n;
670 /* Nothing to do unless we're in timeout mode (not non-blocking) */
671 if (s->sock_timeout <= 0.0)
672 return 0;
674 /* Guard against closed socket */
675 if (s->sock_fd < 0)
676 return 0;
678 /* Prefer poll, if available, since you can poll() any fd
679 * which can't be done with select(). */
680 #ifdef HAVE_POLL
682 struct pollfd pollfd;
683 int timeout;
685 pollfd.fd = s->sock_fd;
686 pollfd.events = writing ? POLLOUT : POLLIN;
688 /* s->sock_timeout is in seconds, timeout in ms */
689 timeout = (int)(s->sock_timeout * 1000 + 0.5);
690 n = poll(&pollfd, 1, timeout);
692 #else
694 /* Construct the arguments to select */
695 fd_set fds;
696 struct timeval tv;
697 tv.tv_sec = (int)s->sock_timeout;
698 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
699 FD_ZERO(&fds);
700 FD_SET(s->sock_fd, &fds);
702 /* See if the socket is ready */
703 if (writing)
704 n = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
705 else
706 n = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
708 #endif
710 if (n < 0)
711 return -1;
712 if (n == 0)
713 return 1;
714 return 0;
717 /* Initialize a new socket object. */
719 static double defaulttimeout = -1.0; /* Default timeout for new sockets */
721 PyMODINIT_FUNC
722 init_sockobject(PySocketSockObject *s,
723 SOCKET_T fd, int family, int type, int proto)
725 #ifdef RISCOS
726 int block = 1;
727 #endif
728 s->sock_fd = fd;
729 s->sock_family = family;
730 s->sock_type = type;
731 s->sock_proto = proto;
732 s->sock_timeout = defaulttimeout;
734 s->errorhandler = &set_error;
736 if (defaulttimeout >= 0.0)
737 internal_setblocking(s, 0);
739 #ifdef RISCOS
740 if (taskwindow)
741 socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
742 #endif
746 /* Create a new socket object.
747 This just creates the object and initializes it.
748 If the creation fails, return NULL and set an exception (implicit
749 in NEWOBJ()). */
751 static PySocketSockObject *
752 new_sockobject(SOCKET_T fd, int family, int type, int proto)
754 PySocketSockObject *s;
755 s = (PySocketSockObject *)
756 PyType_GenericNew(&sock_type, NULL, NULL);
757 if (s != NULL)
758 init_sockobject(s, fd, family, type, proto);
759 return s;
763 /* Lock to allow python interpreter to continue, but only allow one
764 thread to be in gethostbyname or getaddrinfo */
765 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
766 PyThread_type_lock netdb_lock;
767 #endif
770 /* Convert a string specifying a host name or one of a few symbolic
771 names to a numeric IP address. This usually calls gethostbyname()
772 to do the work; the names "" and "<broadcast>" are special.
773 Return the length (IPv4 should be 4 bytes), or negative if
774 an error occurred; then an exception is raised. */
776 static int
777 setipaddr(char *name, struct sockaddr *addr_ret, size_t addr_ret_size, int af)
779 struct addrinfo hints, *res;
780 int error;
781 int d1, d2, d3, d4;
782 char ch;
784 memset((void *) addr_ret, '\0', sizeof(*addr_ret));
785 if (name[0] == '\0') {
786 int siz;
787 memset(&hints, 0, sizeof(hints));
788 hints.ai_family = af;
789 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
790 hints.ai_flags = AI_PASSIVE;
791 Py_BEGIN_ALLOW_THREADS
792 ACQUIRE_GETADDRINFO_LOCK
793 error = getaddrinfo(NULL, "0", &hints, &res);
794 Py_END_ALLOW_THREADS
795 /* We assume that those thread-unsafe getaddrinfo() versions
796 *are* safe regarding their return value, ie. that a
797 subsequent call to getaddrinfo() does not destroy the
798 outcome of the first call. */
799 RELEASE_GETADDRINFO_LOCK
800 if (error) {
801 set_gaierror(error);
802 return -1;
804 switch (res->ai_family) {
805 case AF_INET:
806 siz = 4;
807 break;
808 #ifdef ENABLE_IPV6
809 case AF_INET6:
810 siz = 16;
811 break;
812 #endif
813 default:
814 freeaddrinfo(res);
815 PyErr_SetString(socket_error,
816 "unsupported address family");
817 return -1;
819 if (res->ai_next) {
820 freeaddrinfo(res);
821 PyErr_SetString(socket_error,
822 "wildcard resolved to multiple address");
823 return -1;
825 if (res->ai_addrlen < addr_ret_size)
826 addr_ret_size = res->ai_addrlen;
827 memcpy(addr_ret, res->ai_addr, addr_ret_size);
828 freeaddrinfo(res);
829 return siz;
831 if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
832 struct sockaddr_in *sin;
833 if (af != AF_INET && af != AF_UNSPEC) {
834 PyErr_SetString(socket_error,
835 "address family mismatched");
836 return -1;
838 sin = (struct sockaddr_in *)addr_ret;
839 memset((void *) sin, '\0', sizeof(*sin));
840 sin->sin_family = AF_INET;
841 #ifdef HAVE_SOCKADDR_SA_LEN
842 sin->sin_len = sizeof(*sin);
843 #endif
844 sin->sin_addr.s_addr = INADDR_BROADCAST;
845 return sizeof(sin->sin_addr);
847 if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 &&
848 0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 &&
849 0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) {
850 struct sockaddr_in *sin;
851 sin = (struct sockaddr_in *)addr_ret;
852 sin->sin_addr.s_addr = htonl(
853 ((long) d1 << 24) | ((long) d2 << 16) |
854 ((long) d3 << 8) | ((long) d4 << 0));
855 sin->sin_family = AF_INET;
856 #ifdef HAVE_SOCKADDR_SA_LEN
857 sin->sin_len = sizeof(*sin);
858 #endif
859 return 4;
861 memset(&hints, 0, sizeof(hints));
862 hints.ai_family = af;
863 Py_BEGIN_ALLOW_THREADS
864 ACQUIRE_GETADDRINFO_LOCK
865 error = getaddrinfo(name, NULL, &hints, &res);
866 #if defined(__digital__) && defined(__unix__)
867 if (error == EAI_NONAME && af == AF_UNSPEC) {
868 /* On Tru64 V5.1, numeric-to-addr conversion fails
869 if no address family is given. Assume IPv4 for now.*/
870 hints.ai_family = AF_INET;
871 error = getaddrinfo(name, NULL, &hints, &res);
873 #endif
874 Py_END_ALLOW_THREADS
875 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
876 if (error) {
877 set_gaierror(error);
878 return -1;
880 if (res->ai_addrlen < addr_ret_size)
881 addr_ret_size = res->ai_addrlen;
882 memcpy((char *) addr_ret, res->ai_addr, addr_ret_size);
883 freeaddrinfo(res);
884 switch (addr_ret->sa_family) {
885 case AF_INET:
886 return 4;
887 #ifdef ENABLE_IPV6
888 case AF_INET6:
889 return 16;
890 #endif
891 default:
892 PyErr_SetString(socket_error, "unknown address family");
893 return -1;
898 /* Create a string object representing an IP address.
899 This is always a string of the form 'dd.dd.dd.dd' (with variable
900 size numbers). */
902 static PyObject *
903 makeipaddr(struct sockaddr *addr, int addrlen)
905 char buf[NI_MAXHOST];
906 int error;
908 error = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0,
909 NI_NUMERICHOST);
910 if (error) {
911 set_gaierror(error);
912 return NULL;
914 return PyString_FromString(buf);
918 #ifdef USE_BLUETOOTH
919 /* Convert a string representation of a Bluetooth address into a numeric
920 address. Returns the length (6), or raises an exception and returns -1 if
921 an error occurred. */
923 static int
924 setbdaddr(char *name, bdaddr_t *bdaddr)
926 unsigned int b0, b1, b2, b3, b4, b5;
927 char ch;
928 int n;
930 n = sscanf(name, "%X:%X:%X:%X:%X:%X%c",
931 &b5, &b4, &b3, &b2, &b1, &b0, &ch);
932 if (n == 6 && (b0 | b1 | b2 | b3 | b4 | b5) < 256) {
933 bdaddr->b[0] = b0;
934 bdaddr->b[1] = b1;
935 bdaddr->b[2] = b2;
936 bdaddr->b[3] = b3;
937 bdaddr->b[4] = b4;
938 bdaddr->b[5] = b5;
939 return 6;
940 } else {
941 PyErr_SetString(socket_error, "bad bluetooth address");
942 return -1;
946 /* Create a string representation of the Bluetooth address. This is always a
947 string of the form 'XX:XX:XX:XX:XX:XX' where XX is a two digit hexadecimal
948 value (zero padded if necessary). */
950 static PyObject *
951 makebdaddr(bdaddr_t *bdaddr)
953 char buf[(6 * 2) + 5 + 1];
955 sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
956 bdaddr->b[5], bdaddr->b[4], bdaddr->b[3],
957 bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]);
958 return PyString_FromString(buf);
960 #endif
963 /* Create an object representing the given socket address,
964 suitable for passing it back to bind(), connect() etc.
965 The family field of the sockaddr structure is inspected
966 to determine what kind of address it really is. */
968 /*ARGSUSED*/
969 static PyObject *
970 makesockaddr(int sockfd, struct sockaddr *addr, int addrlen, int proto)
972 if (addrlen == 0) {
973 /* No address -- may be recvfrom() from known socket */
974 Py_INCREF(Py_None);
975 return Py_None;
978 #ifdef __BEOS__
979 /* XXX: BeOS version of accept() doesn't set family correctly */
980 addr->sa_family = AF_INET;
981 #endif
983 switch (addr->sa_family) {
985 case AF_INET:
987 struct sockaddr_in *a;
988 PyObject *addrobj = makeipaddr(addr, sizeof(*a));
989 PyObject *ret = NULL;
990 if (addrobj) {
991 a = (struct sockaddr_in *)addr;
992 ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
993 Py_DECREF(addrobj);
995 return ret;
998 #if defined(AF_UNIX)
999 case AF_UNIX:
1001 struct sockaddr_un *a = (struct sockaddr_un *) addr;
1002 #ifdef linux
1003 if (a->sun_path[0] == 0) { /* Linux abstract namespace */
1004 addrlen -= offsetof(struct sockaddr_un, sun_path);
1005 return PyString_FromStringAndSize(a->sun_path,
1006 addrlen);
1008 else
1009 #endif /* linux */
1011 /* regular NULL-terminated string */
1012 return PyString_FromString(a->sun_path);
1015 #endif /* AF_UNIX */
1017 #if defined(AF_NETLINK)
1018 case AF_NETLINK:
1020 struct sockaddr_nl *a = (struct sockaddr_nl *) addr;
1021 return Py_BuildValue("II", a->nl_pid, a->nl_groups);
1023 #endif /* AF_NETLINK */
1025 #ifdef ENABLE_IPV6
1026 case AF_INET6:
1028 struct sockaddr_in6 *a;
1029 PyObject *addrobj = makeipaddr(addr, sizeof(*a));
1030 PyObject *ret = NULL;
1031 if (addrobj) {
1032 a = (struct sockaddr_in6 *)addr;
1033 ret = Py_BuildValue("Oiii",
1034 addrobj,
1035 ntohs(a->sin6_port),
1036 a->sin6_flowinfo,
1037 a->sin6_scope_id);
1038 Py_DECREF(addrobj);
1040 return ret;
1042 #endif
1044 #ifdef USE_BLUETOOTH
1045 case AF_BLUETOOTH:
1046 switch (proto) {
1048 case BTPROTO_L2CAP:
1050 struct sockaddr_l2 *a = (struct sockaddr_l2 *) addr;
1051 PyObject *addrobj = makebdaddr(&_BT_L2_MEMB(a, bdaddr));
1052 PyObject *ret = NULL;
1053 if (addrobj) {
1054 ret = Py_BuildValue("Oi",
1055 addrobj,
1056 _BT_L2_MEMB(a, psm));
1057 Py_DECREF(addrobj);
1059 return ret;
1062 case BTPROTO_RFCOMM:
1064 struct sockaddr_rc *a = (struct sockaddr_rc *) addr;
1065 PyObject *addrobj = makebdaddr(&_BT_RC_MEMB(a, bdaddr));
1066 PyObject *ret = NULL;
1067 if (addrobj) {
1068 ret = Py_BuildValue("Oi",
1069 addrobj,
1070 _BT_RC_MEMB(a, channel));
1071 Py_DECREF(addrobj);
1073 return ret;
1076 case BTPROTO_HCI:
1078 struct sockaddr_hci *a = (struct sockaddr_hci *) addr;
1079 PyObject *ret = NULL;
1080 ret = Py_BuildValue("i", _BT_HCI_MEMB(a, dev));
1081 return ret;
1084 #if !defined(__FreeBSD__)
1085 case BTPROTO_SCO:
1087 struct sockaddr_sco *a = (struct sockaddr_sco *) addr;
1088 return makebdaddr(&_BT_SCO_MEMB(a, bdaddr));
1090 #endif
1093 #endif
1095 #ifdef HAVE_NETPACKET_PACKET_H
1096 case AF_PACKET:
1098 struct sockaddr_ll *a = (struct sockaddr_ll *)addr;
1099 char *ifname = "";
1100 struct ifreq ifr;
1101 /* need to look up interface name give index */
1102 if (a->sll_ifindex) {
1103 ifr.ifr_ifindex = a->sll_ifindex;
1104 if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0)
1105 ifname = ifr.ifr_name;
1107 return Py_BuildValue("shbhs#",
1108 ifname,
1109 ntohs(a->sll_protocol),
1110 a->sll_pkttype,
1111 a->sll_hatype,
1112 a->sll_addr,
1113 a->sll_halen);
1115 #endif
1117 #ifdef HAVE_LINUX_TIPC_H
1118 case AF_TIPC:
1120 struct sockaddr_tipc *a = (struct sockaddr_tipc *) addr;
1121 if (a->addrtype == TIPC_ADDR_NAMESEQ) {
1122 return Py_BuildValue("IIIII",
1123 a->addrtype,
1124 a->addr.nameseq.type,
1125 a->addr.nameseq.lower,
1126 a->addr.nameseq.upper,
1127 a->scope);
1128 } else if (a->addrtype == TIPC_ADDR_NAME) {
1129 return Py_BuildValue("IIIII",
1130 a->addrtype,
1131 a->addr.name.name.type,
1132 a->addr.name.name.instance,
1133 a->addr.name.name.instance,
1134 a->scope);
1135 } else if (a->addrtype == TIPC_ADDR_ID) {
1136 return Py_BuildValue("IIIII",
1137 a->addrtype,
1138 a->addr.id.node,
1139 a->addr.id.ref,
1141 a->scope);
1142 } else {
1143 PyErr_SetString(PyExc_TypeError,
1144 "Invalid address type");
1145 return NULL;
1148 #endif
1150 /* More cases here... */
1152 default:
1153 /* If we don't know the address family, don't raise an
1154 exception -- return it as a tuple. */
1155 return Py_BuildValue("is#",
1156 addr->sa_family,
1157 addr->sa_data,
1158 sizeof(addr->sa_data));
1164 /* Parse a socket address argument according to the socket object's
1165 address family. Return 1 if the address was in the proper format,
1166 0 of not. The address is returned through addr_ret, its length
1167 through len_ret. */
1169 static int
1170 getsockaddrarg(PySocketSockObject *s, PyObject *args,
1171 struct sockaddr *addr_ret, int *len_ret)
1173 switch (s->sock_family) {
1175 #if defined(AF_UNIX)
1176 case AF_UNIX:
1178 struct sockaddr_un* addr;
1179 char *path;
1180 int len;
1181 if (!PyArg_Parse(args, "t#", &path, &len))
1182 return 0;
1184 addr = (struct sockaddr_un*)addr_ret;
1185 #ifdef linux
1186 if (len > 0 && path[0] == 0) {
1187 /* Linux abstract namespace extension */
1188 if (len > sizeof addr->sun_path) {
1189 PyErr_SetString(socket_error,
1190 "AF_UNIX path too long");
1191 return 0;
1194 else
1195 #endif /* linux */
1197 /* regular NULL-terminated string */
1198 if (len >= sizeof addr->sun_path) {
1199 PyErr_SetString(socket_error,
1200 "AF_UNIX path too long");
1201 return 0;
1203 addr->sun_path[len] = 0;
1205 addr->sun_family = s->sock_family;
1206 memcpy(addr->sun_path, path, len);
1207 #if defined(PYOS_OS2)
1208 *len_ret = sizeof(*addr);
1209 #else
1210 *len_ret = len + offsetof(struct sockaddr_un, sun_path);
1211 #endif
1212 return 1;
1214 #endif /* AF_UNIX */
1216 #if defined(AF_NETLINK)
1217 case AF_NETLINK:
1219 struct sockaddr_nl* addr;
1220 int pid, groups;
1221 addr = (struct sockaddr_nl *)addr_ret;
1222 if (!PyTuple_Check(args)) {
1223 PyErr_Format(
1224 PyExc_TypeError,
1225 "getsockaddrarg: "
1226 "AF_NETLINK address must be tuple, not %.500s",
1227 Py_TYPE(args)->tp_name);
1228 return 0;
1230 if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &pid, &groups))
1231 return 0;
1232 addr->nl_family = AF_NETLINK;
1233 addr->nl_pid = pid;
1234 addr->nl_groups = groups;
1235 *len_ret = sizeof(*addr);
1236 return 1;
1238 #endif
1240 case AF_INET:
1242 struct sockaddr_in* addr;
1243 char *host;
1244 int port, result;
1245 if (!PyTuple_Check(args)) {
1246 PyErr_Format(
1247 PyExc_TypeError,
1248 "getsockaddrarg: "
1249 "AF_INET address must be tuple, not %.500s",
1250 Py_TYPE(args)->tp_name);
1251 return 0;
1253 if (!PyArg_ParseTuple(args, "eti:getsockaddrarg",
1254 "idna", &host, &port))
1255 return 0;
1256 addr=(struct sockaddr_in*)addr_ret;
1257 result = setipaddr(host, (struct sockaddr *)addr,
1258 sizeof(*addr), AF_INET);
1259 PyMem_Free(host);
1260 if (result < 0)
1261 return 0;
1262 if (port < 0 || port > 0xffff) {
1263 PyErr_SetString(
1264 PyExc_OverflowError,
1265 "getsockaddrarg: port must be 0-65535.");
1266 return 0;
1268 addr->sin_family = AF_INET;
1269 addr->sin_port = htons((short)port);
1270 *len_ret = sizeof *addr;
1271 return 1;
1274 #ifdef ENABLE_IPV6
1275 case AF_INET6:
1277 struct sockaddr_in6* addr;
1278 char *host;
1279 int port, flowinfo, scope_id, result;
1280 flowinfo = scope_id = 0;
1281 if (!PyTuple_Check(args)) {
1282 PyErr_Format(
1283 PyExc_TypeError,
1284 "getsockaddrarg: "
1285 "AF_INET6 address must be tuple, not %.500s",
1286 Py_TYPE(args)->tp_name);
1287 return 0;
1289 if (!PyArg_ParseTuple(args, "eti|ii",
1290 "idna", &host, &port, &flowinfo,
1291 &scope_id)) {
1292 return 0;
1294 addr = (struct sockaddr_in6*)addr_ret;
1295 result = setipaddr(host, (struct sockaddr *)addr,
1296 sizeof(*addr), AF_INET6);
1297 PyMem_Free(host);
1298 if (result < 0)
1299 return 0;
1300 if (port < 0 || port > 0xffff) {
1301 PyErr_SetString(
1302 PyExc_OverflowError,
1303 "getsockaddrarg: port must be 0-65535.");
1304 return 0;
1306 addr->sin6_family = s->sock_family;
1307 addr->sin6_port = htons((short)port);
1308 addr->sin6_flowinfo = flowinfo;
1309 addr->sin6_scope_id = scope_id;
1310 *len_ret = sizeof *addr;
1311 return 1;
1313 #endif
1315 #ifdef USE_BLUETOOTH
1316 case AF_BLUETOOTH:
1318 switch (s->sock_proto) {
1319 case BTPROTO_L2CAP:
1321 struct sockaddr_l2 *addr;
1322 char *straddr;
1324 addr = (struct sockaddr_l2 *)addr_ret;
1325 _BT_L2_MEMB(addr, family) = AF_BLUETOOTH;
1326 if (!PyArg_ParseTuple(args, "si", &straddr,
1327 &_BT_L2_MEMB(addr, psm))) {
1328 PyErr_SetString(socket_error, "getsockaddrarg: "
1329 "wrong format");
1330 return 0;
1332 if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0)
1333 return 0;
1335 *len_ret = sizeof *addr;
1336 return 1;
1338 case BTPROTO_RFCOMM:
1340 struct sockaddr_rc *addr;
1341 char *straddr;
1343 addr = (struct sockaddr_rc *)addr_ret;
1344 _BT_RC_MEMB(addr, family) = AF_BLUETOOTH;
1345 if (!PyArg_ParseTuple(args, "si", &straddr,
1346 &_BT_RC_MEMB(addr, channel))) {
1347 PyErr_SetString(socket_error, "getsockaddrarg: "
1348 "wrong format");
1349 return 0;
1351 if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0)
1352 return 0;
1354 *len_ret = sizeof *addr;
1355 return 1;
1357 case BTPROTO_HCI:
1359 struct sockaddr_hci *addr = (struct sockaddr_hci *)addr_ret;
1360 _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH;
1361 if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) {
1362 PyErr_SetString(socket_error, "getsockaddrarg: "
1363 "wrong format");
1364 return 0;
1366 *len_ret = sizeof *addr;
1367 return 1;
1369 #if !defined(__FreeBSD__)
1370 case BTPROTO_SCO:
1372 struct sockaddr_sco *addr;
1373 char *straddr;
1375 addr = (struct sockaddr_sco *)addr_ret;
1376 _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH;
1377 straddr = PyString_AsString(args);
1378 if (straddr == NULL) {
1379 PyErr_SetString(socket_error, "getsockaddrarg: "
1380 "wrong format");
1381 return 0;
1383 if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0)
1384 return 0;
1386 *len_ret = sizeof *addr;
1387 return 1;
1389 #endif
1390 default:
1391 PyErr_SetString(socket_error, "getsockaddrarg: unknown Bluetooth protocol");
1392 return 0;
1395 #endif
1397 #ifdef HAVE_NETPACKET_PACKET_H
1398 case AF_PACKET:
1400 struct sockaddr_ll* addr;
1401 struct ifreq ifr;
1402 char *interfaceName;
1403 int protoNumber;
1404 int hatype = 0;
1405 int pkttype = 0;
1406 char *haddr = NULL;
1407 unsigned int halen = 0;
1409 if (!PyTuple_Check(args)) {
1410 PyErr_Format(
1411 PyExc_TypeError,
1412 "getsockaddrarg: "
1413 "AF_PACKET address must be tuple, not %.500s",
1414 Py_TYPE(args)->tp_name);
1415 return 0;
1417 if (!PyArg_ParseTuple(args, "si|iis#", &interfaceName,
1418 &protoNumber, &pkttype, &hatype,
1419 &haddr, &halen))
1420 return 0;
1421 strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name));
1422 ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
1423 if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
1424 s->errorhandler();
1425 return 0;
1427 if (halen > 8) {
1428 PyErr_SetString(PyExc_ValueError,
1429 "Hardware address must be 8 bytes or less");
1430 return 0;
1432 if (protoNumber < 0 || protoNumber > 0xffff) {
1433 PyErr_SetString(
1434 PyExc_OverflowError,
1435 "getsockaddrarg: protoNumber must be 0-65535.");
1436 return 0;
1438 addr = (struct sockaddr_ll*)addr_ret;
1439 addr->sll_family = AF_PACKET;
1440 addr->sll_protocol = htons((short)protoNumber);
1441 addr->sll_ifindex = ifr.ifr_ifindex;
1442 addr->sll_pkttype = pkttype;
1443 addr->sll_hatype = hatype;
1444 if (halen != 0) {
1445 memcpy(&addr->sll_addr, haddr, halen);
1447 addr->sll_halen = halen;
1448 *len_ret = sizeof *addr;
1449 return 1;
1451 #endif
1453 #ifdef HAVE_LINUX_TIPC_H
1454 case AF_TIPC:
1456 unsigned int atype, v1, v2, v3;
1457 unsigned int scope = TIPC_CLUSTER_SCOPE;
1458 struct sockaddr_tipc *addr;
1460 if (!PyTuple_Check(args)) {
1461 PyErr_Format(
1462 PyExc_TypeError,
1463 "getsockaddrarg: "
1464 "AF_TIPC address must be tuple, not %.500s",
1465 Py_TYPE(args)->tp_name);
1466 return 0;
1469 if (!PyArg_ParseTuple(args,
1470 "IIII|I;Invalid TIPC address format",
1471 &atype, &v1, &v2, &v3, &scope))
1472 return 0;
1474 addr = (struct sockaddr_tipc *) addr_ret;
1475 memset(addr, 0, sizeof(struct sockaddr_tipc));
1477 addr->family = AF_TIPC;
1478 addr->scope = scope;
1479 addr->addrtype = atype;
1481 if (atype == TIPC_ADDR_NAMESEQ) {
1482 addr->addr.nameseq.type = v1;
1483 addr->addr.nameseq.lower = v2;
1484 addr->addr.nameseq.upper = v3;
1485 } else if (atype == TIPC_ADDR_NAME) {
1486 addr->addr.name.name.type = v1;
1487 addr->addr.name.name.instance = v2;
1488 } else if (atype == TIPC_ADDR_ID) {
1489 addr->addr.id.node = v1;
1490 addr->addr.id.ref = v2;
1491 } else {
1492 /* Shouldn't happen */
1493 PyErr_SetString(PyExc_TypeError, "Invalid address type");
1494 return 0;
1497 *len_ret = sizeof(*addr);
1499 return 1;
1501 #endif
1503 /* More cases here... */
1505 default:
1506 PyErr_SetString(socket_error, "getsockaddrarg: bad family");
1507 return 0;
1513 /* Get the address length according to the socket object's address family.
1514 Return 1 if the family is known, 0 otherwise. The length is returned
1515 through len_ret. */
1517 static int
1518 getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
1520 switch (s->sock_family) {
1522 #if defined(AF_UNIX)
1523 case AF_UNIX:
1525 *len_ret = sizeof (struct sockaddr_un);
1526 return 1;
1528 #endif /* AF_UNIX */
1529 #if defined(AF_NETLINK)
1530 case AF_NETLINK:
1532 *len_ret = sizeof (struct sockaddr_nl);
1533 return 1;
1535 #endif
1537 case AF_INET:
1539 *len_ret = sizeof (struct sockaddr_in);
1540 return 1;
1543 #ifdef ENABLE_IPV6
1544 case AF_INET6:
1546 *len_ret = sizeof (struct sockaddr_in6);
1547 return 1;
1549 #endif
1551 #ifdef USE_BLUETOOTH
1552 case AF_BLUETOOTH:
1554 switch(s->sock_proto)
1557 case BTPROTO_L2CAP:
1558 *len_ret = sizeof (struct sockaddr_l2);
1559 return 1;
1560 case BTPROTO_RFCOMM:
1561 *len_ret = sizeof (struct sockaddr_rc);
1562 return 1;
1563 case BTPROTO_HCI:
1564 *len_ret = sizeof (struct sockaddr_hci);
1565 return 1;
1566 #if !defined(__FreeBSD__)
1567 case BTPROTO_SCO:
1568 *len_ret = sizeof (struct sockaddr_sco);
1569 return 1;
1570 #endif
1571 default:
1572 PyErr_SetString(socket_error, "getsockaddrlen: "
1573 "unknown BT protocol");
1574 return 0;
1578 #endif
1580 #ifdef HAVE_NETPACKET_PACKET_H
1581 case AF_PACKET:
1583 *len_ret = sizeof (struct sockaddr_ll);
1584 return 1;
1586 #endif
1588 #ifdef HAVE_LINUX_TIPC_H
1589 case AF_TIPC:
1591 *len_ret = sizeof (struct sockaddr_tipc);
1592 return 1;
1594 #endif
1596 /* More cases here... */
1598 default:
1599 PyErr_SetString(socket_error, "getsockaddrlen: bad family");
1600 return 0;
1606 /* s.accept() method */
1608 static PyObject *
1609 sock_accept(PySocketSockObject *s)
1611 sock_addr_t addrbuf;
1612 SOCKET_T newfd;
1613 socklen_t addrlen;
1614 PyObject *sock = NULL;
1615 PyObject *addr = NULL;
1616 PyObject *res = NULL;
1617 int timeout;
1619 if (!getsockaddrlen(s, &addrlen))
1620 return NULL;
1621 memset(&addrbuf, 0, addrlen);
1623 #ifdef MS_WINDOWS
1624 newfd = INVALID_SOCKET;
1625 #else
1626 newfd = -1;
1627 #endif
1629 if (!IS_SELECTABLE(s))
1630 return select_error();
1632 Py_BEGIN_ALLOW_THREADS
1633 timeout = internal_select(s, 0);
1634 if (!timeout)
1635 newfd = accept(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
1636 Py_END_ALLOW_THREADS
1638 if (timeout == 1) {
1639 PyErr_SetString(socket_timeout, "timed out");
1640 return NULL;
1643 #ifdef MS_WINDOWS
1644 if (newfd == INVALID_SOCKET)
1645 #else
1646 if (newfd < 0)
1647 #endif
1648 return s->errorhandler();
1650 /* Create the new object with unspecified family,
1651 to avoid calls to bind() etc. on it. */
1652 sock = (PyObject *) new_sockobject(newfd,
1653 s->sock_family,
1654 s->sock_type,
1655 s->sock_proto);
1657 if (sock == NULL) {
1658 SOCKETCLOSE(newfd);
1659 goto finally;
1661 addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
1662 addrlen, s->sock_proto);
1663 if (addr == NULL)
1664 goto finally;
1666 res = PyTuple_Pack(2, sock, addr);
1668 finally:
1669 Py_XDECREF(sock);
1670 Py_XDECREF(addr);
1671 return res;
1674 PyDoc_STRVAR(accept_doc,
1675 "accept() -> (socket object, address info)\n\
1677 Wait for an incoming connection. Return a new socket representing the\n\
1678 connection, and the address of the client. For IP sockets, the address\n\
1679 info is a pair (hostaddr, port).");
1681 /* s.setblocking(flag) method. Argument:
1682 False -- non-blocking mode; same as settimeout(0)
1683 True -- blocking mode; same as settimeout(None)
1686 static PyObject *
1687 sock_setblocking(PySocketSockObject *s, PyObject *arg)
1689 int block;
1691 block = PyInt_AsLong(arg);
1692 if (block == -1 && PyErr_Occurred())
1693 return NULL;
1695 s->sock_timeout = block ? -1.0 : 0.0;
1696 internal_setblocking(s, block);
1698 Py_INCREF(Py_None);
1699 return Py_None;
1702 PyDoc_STRVAR(setblocking_doc,
1703 "setblocking(flag)\n\
1705 Set the socket to blocking (flag is true) or non-blocking (false).\n\
1706 setblocking(True) is equivalent to settimeout(None);\n\
1707 setblocking(False) is equivalent to settimeout(0.0).");
1709 /* s.settimeout(timeout) method. Argument:
1710 None -- no timeout, blocking mode; same as setblocking(True)
1711 0.0 -- non-blocking mode; same as setblocking(False)
1712 > 0 -- timeout mode; operations time out after timeout seconds
1713 < 0 -- illegal; raises an exception
1715 static PyObject *
1716 sock_settimeout(PySocketSockObject *s, PyObject *arg)
1718 double timeout;
1720 if (arg == Py_None)
1721 timeout = -1.0;
1722 else {
1723 timeout = PyFloat_AsDouble(arg);
1724 if (timeout < 0.0) {
1725 if (!PyErr_Occurred())
1726 PyErr_SetString(PyExc_ValueError,
1727 "Timeout value out of range");
1728 return NULL;
1732 s->sock_timeout = timeout;
1733 internal_setblocking(s, timeout < 0.0);
1735 Py_INCREF(Py_None);
1736 return Py_None;
1739 PyDoc_STRVAR(settimeout_doc,
1740 "settimeout(timeout)\n\
1742 Set a timeout on socket operations. 'timeout' can be a float,\n\
1743 giving in seconds, or None. Setting a timeout of None disables\n\
1744 the timeout feature and is equivalent to setblocking(1).\n\
1745 Setting a timeout of zero is the same as setblocking(0).");
1747 /* s.gettimeout() method.
1748 Returns the timeout associated with a socket. */
1749 static PyObject *
1750 sock_gettimeout(PySocketSockObject *s)
1752 if (s->sock_timeout < 0.0) {
1753 Py_INCREF(Py_None);
1754 return Py_None;
1756 else
1757 return PyFloat_FromDouble(s->sock_timeout);
1760 PyDoc_STRVAR(gettimeout_doc,
1761 "gettimeout() -> timeout\n\
1763 Returns the timeout in floating seconds associated with socket \n\
1764 operations. A timeout of None indicates that timeouts on socket \n\
1765 operations are disabled.");
1767 #ifdef RISCOS
1768 /* s.sleeptaskw(1 | 0) method */
1770 static PyObject *
1771 sock_sleeptaskw(PySocketSockObject *s,PyObject *arg)
1773 int block;
1774 block = PyInt_AsLong(arg);
1775 if (block == -1 && PyErr_Occurred())
1776 return NULL;
1777 Py_BEGIN_ALLOW_THREADS
1778 socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
1779 Py_END_ALLOW_THREADS
1781 Py_INCREF(Py_None);
1782 return Py_None;
1784 PyDoc_STRVAR(sleeptaskw_doc,
1785 "sleeptaskw(flag)\n\
1787 Allow sleeps in taskwindows.");
1788 #endif
1791 /* s.setsockopt() method.
1792 With an integer third argument, sets an integer option.
1793 With a string third argument, sets an option from a buffer;
1794 use optional built-in module 'struct' to encode the string. */
1796 static PyObject *
1797 sock_setsockopt(PySocketSockObject *s, PyObject *args)
1799 int level;
1800 int optname;
1801 int res;
1802 char *buf;
1803 int buflen;
1804 int flag;
1806 if (PyArg_ParseTuple(args, "iii:setsockopt",
1807 &level, &optname, &flag)) {
1808 buf = (char *) &flag;
1809 buflen = sizeof flag;
1811 else {
1812 PyErr_Clear();
1813 if (!PyArg_ParseTuple(args, "iis#:setsockopt",
1814 &level, &optname, &buf, &buflen))
1815 return NULL;
1817 res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen);
1818 if (res < 0)
1819 return s->errorhandler();
1820 Py_INCREF(Py_None);
1821 return Py_None;
1824 PyDoc_STRVAR(setsockopt_doc,
1825 "setsockopt(level, option, value)\n\
1827 Set a socket option. See the Unix manual for level and option.\n\
1828 The value argument can either be an integer or a string.");
1831 /* s.getsockopt() method.
1832 With two arguments, retrieves an integer option.
1833 With a third integer argument, retrieves a string buffer of that size;
1834 use optional built-in module 'struct' to decode the string. */
1836 static PyObject *
1837 sock_getsockopt(PySocketSockObject *s, PyObject *args)
1839 int level;
1840 int optname;
1841 int res;
1842 PyObject *buf;
1843 socklen_t buflen = 0;
1845 #ifdef __BEOS__
1846 /* We have incomplete socket support. */
1847 PyErr_SetString(socket_error, "getsockopt not supported");
1848 return NULL;
1849 #else
1851 if (!PyArg_ParseTuple(args, "ii|i:getsockopt",
1852 &level, &optname, &buflen))
1853 return NULL;
1855 if (buflen == 0) {
1856 int flag = 0;
1857 socklen_t flagsize = sizeof flag;
1858 res = getsockopt(s->sock_fd, level, optname,
1859 (void *)&flag, &flagsize);
1860 if (res < 0)
1861 return s->errorhandler();
1862 return PyInt_FromLong(flag);
1864 #ifdef __VMS
1865 /* socklen_t is unsigned so no negative test is needed,
1866 test buflen == 0 is previously done */
1867 if (buflen > 1024) {
1868 #else
1869 if (buflen <= 0 || buflen > 1024) {
1870 #endif
1871 PyErr_SetString(socket_error,
1872 "getsockopt buflen out of range");
1873 return NULL;
1875 buf = PyString_FromStringAndSize((char *)NULL, buflen);
1876 if (buf == NULL)
1877 return NULL;
1878 res = getsockopt(s->sock_fd, level, optname,
1879 (void *)PyString_AS_STRING(buf), &buflen);
1880 if (res < 0) {
1881 Py_DECREF(buf);
1882 return s->errorhandler();
1884 _PyString_Resize(&buf, buflen);
1885 return buf;
1886 #endif /* __BEOS__ */
1889 PyDoc_STRVAR(getsockopt_doc,
1890 "getsockopt(level, option[, buffersize]) -> value\n\
1892 Get a socket option. See the Unix manual for level and option.\n\
1893 If a nonzero buffersize argument is given, the return value is a\n\
1894 string of that length; otherwise it is an integer.");
1897 /* s.bind(sockaddr) method */
1899 static PyObject *
1900 sock_bind(PySocketSockObject *s, PyObject *addro)
1902 sock_addr_t addrbuf;
1903 int addrlen;
1904 int res;
1906 if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
1907 return NULL;
1908 Py_BEGIN_ALLOW_THREADS
1909 res = bind(s->sock_fd, SAS2SA(&addrbuf), addrlen);
1910 Py_END_ALLOW_THREADS
1911 if (res < 0)
1912 return s->errorhandler();
1913 Py_INCREF(Py_None);
1914 return Py_None;
1917 PyDoc_STRVAR(bind_doc,
1918 "bind(address)\n\
1920 Bind the socket to a local address. For IP sockets, the address is a\n\
1921 pair (host, port); the host must refer to the local host. For raw packet\n\
1922 sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");
1925 /* s.close() method.
1926 Set the file descriptor to -1 so operations tried subsequently
1927 will surely fail. */
1929 static PyObject *
1930 sock_close(PySocketSockObject *s)
1932 SOCKET_T fd;
1934 if ((fd = s->sock_fd) != -1) {
1935 s->sock_fd = -1;
1936 Py_BEGIN_ALLOW_THREADS
1937 (void) SOCKETCLOSE(fd);
1938 Py_END_ALLOW_THREADS
1940 Py_INCREF(Py_None);
1941 return Py_None;
1944 PyDoc_STRVAR(close_doc,
1945 "close()\n\
1947 Close the socket. It cannot be used after this call.");
1949 static int
1950 internal_connect(PySocketSockObject *s, struct sockaddr *addr, int addrlen,
1951 int *timeoutp)
1953 int res, timeout;
1955 timeout = 0;
1956 res = connect(s->sock_fd, addr, addrlen);
1958 #ifdef MS_WINDOWS
1960 if (s->sock_timeout > 0.0) {
1961 if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK &&
1962 IS_SELECTABLE(s)) {
1963 /* This is a mess. Best solution: trust select */
1964 fd_set fds;
1965 fd_set fds_exc;
1966 struct timeval tv;
1967 tv.tv_sec = (int)s->sock_timeout;
1968 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1969 FD_ZERO(&fds);
1970 FD_SET(s->sock_fd, &fds);
1971 FD_ZERO(&fds_exc);
1972 FD_SET(s->sock_fd, &fds_exc);
1973 res = select(s->sock_fd+1, NULL, &fds, &fds_exc, &tv);
1974 if (res == 0) {
1975 res = WSAEWOULDBLOCK;
1976 timeout = 1;
1977 } else if (res > 0) {
1978 if (FD_ISSET(s->sock_fd, &fds))
1979 /* The socket is in the writeable set - this
1980 means connected */
1981 res = 0;
1982 else {
1983 /* As per MS docs, we need to call getsockopt()
1984 to get the underlying error */
1985 int res_size = sizeof res;
1986 /* It must be in the exception set */
1987 assert(FD_ISSET(s->sock_fd, &fds_exc));
1988 if (0 == getsockopt(s->sock_fd, SOL_SOCKET, SO_ERROR,
1989 (char *)&res, &res_size))
1990 /* getsockopt also clears WSAGetLastError,
1991 so reset it back. */
1992 WSASetLastError(res);
1993 else
1994 res = WSAGetLastError();
1997 /* else if (res < 0) an error occurred */
2001 if (res < 0)
2002 res = WSAGetLastError();
2004 #else
2006 if (s->sock_timeout > 0.0) {
2007 if (res < 0 && errno == EINPROGRESS && IS_SELECTABLE(s)) {
2008 timeout = internal_select(s, 1);
2009 if (timeout == 0) {
2010 /* Bug #1019808: in case of an EINPROGRESS,
2011 use getsockopt(SO_ERROR) to get the real
2012 error. */
2013 socklen_t res_size = sizeof res;
2014 (void)getsockopt(s->sock_fd, SOL_SOCKET,
2015 SO_ERROR, &res, &res_size);
2016 if (res == EISCONN)
2017 res = 0;
2018 errno = res;
2020 else if (timeout == -1) {
2021 res = errno; /* had error */
2023 else
2024 res = EWOULDBLOCK; /* timed out */
2028 if (res < 0)
2029 res = errno;
2031 #endif
2032 *timeoutp = timeout;
2034 return res;
2037 /* s.connect(sockaddr) method */
2039 static PyObject *
2040 sock_connect(PySocketSockObject *s, PyObject *addro)
2042 sock_addr_t addrbuf;
2043 int addrlen;
2044 int res;
2045 int timeout;
2047 if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
2048 return NULL;
2050 Py_BEGIN_ALLOW_THREADS
2051 res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
2052 Py_END_ALLOW_THREADS
2054 if (timeout == 1) {
2055 PyErr_SetString(socket_timeout, "timed out");
2056 return NULL;
2058 if (res != 0)
2059 return s->errorhandler();
2060 Py_INCREF(Py_None);
2061 return Py_None;
2064 PyDoc_STRVAR(connect_doc,
2065 "connect(address)\n\
2067 Connect the socket to a remote address. For IP sockets, the address\n\
2068 is a pair (host, port).");
2071 /* s.connect_ex(sockaddr) method */
2073 static PyObject *
2074 sock_connect_ex(PySocketSockObject *s, PyObject *addro)
2076 sock_addr_t addrbuf;
2077 int addrlen;
2078 int res;
2079 int timeout;
2081 if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
2082 return NULL;
2084 Py_BEGIN_ALLOW_THREADS
2085 res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
2086 Py_END_ALLOW_THREADS
2088 /* Signals are not errors (though they may raise exceptions). Adapted
2089 from PyErr_SetFromErrnoWithFilenameObject(). */
2090 #ifdef EINTR
2091 if (res == EINTR && PyErr_CheckSignals())
2092 return NULL;
2093 #endif
2095 return PyInt_FromLong((long) res);
2098 PyDoc_STRVAR(connect_ex_doc,
2099 "connect_ex(address) -> errno\n\
2101 This is like connect(address), but returns an error code (the errno value)\n\
2102 instead of raising an exception when an error occurs.");
2105 /* s.fileno() method */
2107 static PyObject *
2108 sock_fileno(PySocketSockObject *s)
2110 #if SIZEOF_SOCKET_T <= SIZEOF_LONG
2111 return PyInt_FromLong((long) s->sock_fd);
2112 #else
2113 return PyLong_FromLongLong((PY_LONG_LONG)s->sock_fd);
2114 #endif
2117 PyDoc_STRVAR(fileno_doc,
2118 "fileno() -> integer\n\
2120 Return the integer file descriptor of the socket.");
2123 #ifndef NO_DUP
2124 /* s.dup() method */
2126 static PyObject *
2127 sock_dup(PySocketSockObject *s)
2129 SOCKET_T newfd;
2130 PyObject *sock;
2132 newfd = dup(s->sock_fd);
2133 if (newfd < 0)
2134 return s->errorhandler();
2135 sock = (PyObject *) new_sockobject(newfd,
2136 s->sock_family,
2137 s->sock_type,
2138 s->sock_proto);
2139 if (sock == NULL)
2140 SOCKETCLOSE(newfd);
2141 return sock;
2144 PyDoc_STRVAR(dup_doc,
2145 "dup() -> socket object\n\
2147 Return a new socket object connected to the same system resource.");
2149 #endif
2152 /* s.getsockname() method */
2154 static PyObject *
2155 sock_getsockname(PySocketSockObject *s)
2157 sock_addr_t addrbuf;
2158 int res;
2159 socklen_t addrlen;
2161 if (!getsockaddrlen(s, &addrlen))
2162 return NULL;
2163 memset(&addrbuf, 0, addrlen);
2164 Py_BEGIN_ALLOW_THREADS
2165 res = getsockname(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
2166 Py_END_ALLOW_THREADS
2167 if (res < 0)
2168 return s->errorhandler();
2169 return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
2170 s->sock_proto);
2173 PyDoc_STRVAR(getsockname_doc,
2174 "getsockname() -> address info\n\
2176 Return the address of the local endpoint. For IP sockets, the address\n\
2177 info is a pair (hostaddr, port).");
2180 #ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
2181 /* s.getpeername() method */
2183 static PyObject *
2184 sock_getpeername(PySocketSockObject *s)
2186 sock_addr_t addrbuf;
2187 int res;
2188 socklen_t addrlen;
2190 if (!getsockaddrlen(s, &addrlen))
2191 return NULL;
2192 memset(&addrbuf, 0, addrlen);
2193 Py_BEGIN_ALLOW_THREADS
2194 res = getpeername(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
2195 Py_END_ALLOW_THREADS
2196 if (res < 0)
2197 return s->errorhandler();
2198 return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
2199 s->sock_proto);
2202 PyDoc_STRVAR(getpeername_doc,
2203 "getpeername() -> address info\n\
2205 Return the address of the remote endpoint. For IP sockets, the address\n\
2206 info is a pair (hostaddr, port).");
2208 #endif /* HAVE_GETPEERNAME */
2211 /* s.listen(n) method */
2213 static PyObject *
2214 sock_listen(PySocketSockObject *s, PyObject *arg)
2216 int backlog;
2217 int res;
2219 backlog = PyInt_AsLong(arg);
2220 if (backlog == -1 && PyErr_Occurred())
2221 return NULL;
2222 Py_BEGIN_ALLOW_THREADS
2223 if (backlog < 1)
2224 backlog = 1;
2225 res = listen(s->sock_fd, backlog);
2226 Py_END_ALLOW_THREADS
2227 if (res < 0)
2228 return s->errorhandler();
2229 Py_INCREF(Py_None);
2230 return Py_None;
2233 PyDoc_STRVAR(listen_doc,
2234 "listen(backlog)\n\
2236 Enable a server to accept connections. The backlog argument must be at\n\
2237 least 1; it specifies the number of unaccepted connection that the system\n\
2238 will allow before refusing new connections.");
2241 #ifndef NO_DUP
2242 /* s.makefile(mode) method.
2243 Create a new open file object referring to a dupped version of
2244 the socket's file descriptor. (The dup() call is necessary so
2245 that the open file and socket objects may be closed independent
2246 of each other.)
2247 The mode argument specifies 'r' or 'w' passed to fdopen(). */
2249 static PyObject *
2250 sock_makefile(PySocketSockObject *s, PyObject *args)
2252 extern int fclose(FILE *);
2253 char *mode = "r";
2254 int bufsize = -1;
2255 #ifdef MS_WIN32
2256 Py_intptr_t fd;
2257 #else
2258 int fd;
2259 #endif
2260 FILE *fp;
2261 PyObject *f;
2262 #ifdef __VMS
2263 char *mode_r = "r";
2264 char *mode_w = "w";
2265 #endif
2267 if (!PyArg_ParseTuple(args, "|si:makefile", &mode, &bufsize))
2268 return NULL;
2269 #ifdef __VMS
2270 if (strcmp(mode,"rb") == 0) {
2271 mode = mode_r;
2273 else {
2274 if (strcmp(mode,"wb") == 0) {
2275 mode = mode_w;
2278 #endif
2279 #ifdef MS_WIN32
2280 if (((fd = _open_osfhandle(s->sock_fd, _O_BINARY)) < 0) ||
2281 ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL))
2282 #else
2283 if ((fd = dup(s->sock_fd)) < 0 || (fp = fdopen(fd, mode)) == NULL)
2284 #endif
2286 if (fd >= 0)
2287 SOCKETCLOSE(fd);
2288 return s->errorhandler();
2290 f = PyFile_FromFile(fp, "<socket>", mode, fclose);
2291 if (f != NULL)
2292 PyFile_SetBufSize(f, bufsize);
2293 return f;
2296 PyDoc_STRVAR(makefile_doc,
2297 "makefile([mode[, buffersize]]) -> file object\n\
2299 Return a regular file object corresponding to the socket.\n\
2300 The mode and buffersize arguments are as for the built-in open() function.");
2302 #endif /* NO_DUP */
2305 * This is the guts of the recv() and recv_into() methods, which reads into a
2306 * char buffer. If you have any inc/dec ref to do to the objects that contain
2307 * the buffer, do it in the caller. This function returns the number of bytes
2308 * succesfully read. If there was an error, it returns -1. Note that it is
2309 * also possible that we return a number of bytes smaller than the request
2310 * bytes.
2312 static ssize_t
2313 sock_recv_guts(PySocketSockObject *s, char* cbuf, int len, int flags)
2315 ssize_t outlen = -1;
2316 int timeout;
2317 #ifdef __VMS
2318 int remaining;
2319 char *read_buf;
2320 #endif
2322 if (!IS_SELECTABLE(s)) {
2323 select_error();
2324 return -1;
2327 #ifndef __VMS
2328 Py_BEGIN_ALLOW_THREADS
2329 timeout = internal_select(s, 0);
2330 if (!timeout)
2331 outlen = recv(s->sock_fd, cbuf, len, flags);
2332 Py_END_ALLOW_THREADS
2334 if (timeout == 1) {
2335 PyErr_SetString(socket_timeout, "timed out");
2336 return -1;
2338 if (outlen < 0) {
2339 /* Note: the call to errorhandler() ALWAYS indirectly returned
2340 NULL, so ignore its return value */
2341 s->errorhandler();
2342 return -1;
2344 #else
2345 read_buf = cbuf;
2346 remaining = len;
2347 while (remaining != 0) {
2348 unsigned int segment;
2349 int nread = -1;
2351 segment = remaining /SEGMENT_SIZE;
2352 if (segment != 0) {
2353 segment = SEGMENT_SIZE;
2355 else {
2356 segment = remaining;
2359 Py_BEGIN_ALLOW_THREADS
2360 timeout = internal_select(s, 0);
2361 if (!timeout)
2362 nread = recv(s->sock_fd, read_buf, segment, flags);
2363 Py_END_ALLOW_THREADS
2365 if (timeout == 1) {
2366 PyErr_SetString(socket_timeout, "timed out");
2367 return -1;
2369 if (nread < 0) {
2370 s->errorhandler();
2371 return -1;
2373 if (nread != remaining) {
2374 read_buf += nread;
2375 break;
2378 remaining -= segment;
2379 read_buf += segment;
2381 outlen = read_buf - cbuf;
2382 #endif /* !__VMS */
2384 return outlen;
2388 /* s.recv(nbytes [,flags]) method */
2390 static PyObject *
2391 sock_recv(PySocketSockObject *s, PyObject *args)
2393 int recvlen, flags = 0;
2394 ssize_t outlen;
2395 PyObject *buf;
2397 if (!PyArg_ParseTuple(args, "i|i:recv", &recvlen, &flags))
2398 return NULL;
2400 if (recvlen < 0) {
2401 PyErr_SetString(PyExc_ValueError,
2402 "negative buffersize in recv");
2403 return NULL;
2406 /* Allocate a new string. */
2407 buf = PyString_FromStringAndSize((char *) 0, recvlen);
2408 if (buf == NULL)
2409 return NULL;
2411 /* Call the guts */
2412 outlen = sock_recv_guts(s, PyString_AS_STRING(buf), recvlen, flags);
2413 if (outlen < 0) {
2414 /* An error occurred, release the string and return an
2415 error. */
2416 Py_DECREF(buf);
2417 return NULL;
2419 if (outlen != recvlen) {
2420 /* We did not read as many bytes as we anticipated, resize the
2421 string if possible and be succesful. */
2422 if (_PyString_Resize(&buf, outlen) < 0)
2423 /* Oopsy, not so succesful after all. */
2424 return NULL;
2427 return buf;
2430 PyDoc_STRVAR(recv_doc,
2431 "recv(buffersize[, flags]) -> data\n\
2433 Receive up to buffersize bytes from the socket. For the optional flags\n\
2434 argument, see the Unix manual. When no data is available, block until\n\
2435 at least one byte is available or until the remote end is closed. When\n\
2436 the remote end is closed and all data is read, return the empty string.");
2439 /* s.recv_into(buffer, [nbytes [,flags]]) method */
2441 static PyObject*
2442 sock_recv_into(PySocketSockObject *s, PyObject *args, PyObject *kwds)
2444 static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
2446 int recvlen = 0, flags = 0;
2447 ssize_t readlen;
2448 char *buf;
2449 int buflen;
2451 /* Get the buffer's memory */
2452 if (!PyArg_ParseTupleAndKeywords(args, kwds, "w#|ii:recv_into", kwlist,
2453 &buf, &buflen, &recvlen, &flags))
2454 return NULL;
2455 assert(buf != 0 && buflen > 0);
2457 if (recvlen < 0) {
2458 PyErr_SetString(PyExc_ValueError,
2459 "negative buffersize in recv_into");
2460 return NULL;
2462 if (recvlen == 0) {
2463 /* If nbytes was not specified, use the buffer's length */
2464 recvlen = buflen;
2467 /* Check if the buffer is large enough */
2468 if (buflen < recvlen) {
2469 PyErr_SetString(PyExc_ValueError,
2470 "buffer too small for requested bytes");
2471 return NULL;
2474 /* Call the guts */
2475 readlen = sock_recv_guts(s, buf, recvlen, flags);
2476 if (readlen < 0) {
2477 /* Return an error. */
2478 return NULL;
2481 /* Return the number of bytes read. Note that we do not do anything
2482 special here in the case that readlen < recvlen. */
2483 return PyInt_FromSsize_t(readlen);
2486 PyDoc_STRVAR(recv_into_doc,
2487 "recv_into(buffer, [nbytes[, flags]]) -> nbytes_read\n\
2489 A version of recv() that stores its data into a buffer rather than creating \n\
2490 a new string. Receive up to buffersize bytes from the socket. If buffersize \n\
2491 is not specified (or 0), receive up to the size available in the given buffer.\n\
2493 See recv() for documentation about the flags.");
2497 * This is the guts of the recvfrom() and recvfrom_into() methods, which reads
2498 * into a char buffer. If you have any inc/def ref to do to the objects that
2499 * contain the buffer, do it in the caller. This function returns the number
2500 * of bytes succesfully read. If there was an error, it returns -1. Note
2501 * that it is also possible that we return a number of bytes smaller than the
2502 * request bytes.
2504 * 'addr' is a return value for the address object. Note that you must decref
2505 * it yourself.
2507 static ssize_t
2508 sock_recvfrom_guts(PySocketSockObject *s, char* cbuf, int len, int flags,
2509 PyObject** addr)
2511 sock_addr_t addrbuf;
2512 int timeout;
2513 ssize_t n = -1;
2514 socklen_t addrlen;
2516 *addr = NULL;
2518 if (!getsockaddrlen(s, &addrlen))
2519 return -1;
2521 if (!IS_SELECTABLE(s)) {
2522 select_error();
2523 return -1;
2526 Py_BEGIN_ALLOW_THREADS
2527 memset(&addrbuf, 0, addrlen);
2528 timeout = internal_select(s, 0);
2529 if (!timeout) {
2530 #ifndef MS_WINDOWS
2531 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
2532 n = recvfrom(s->sock_fd, cbuf, len, flags,
2533 SAS2SA(&addrbuf), &addrlen);
2534 #else
2535 n = recvfrom(s->sock_fd, cbuf, len, flags,
2536 (void *) &addrbuf, &addrlen);
2537 #endif
2538 #else
2539 n = recvfrom(s->sock_fd, cbuf, len, flags,
2540 SAS2SA(&addrbuf), &addrlen);
2541 #endif
2543 Py_END_ALLOW_THREADS
2545 if (timeout == 1) {
2546 PyErr_SetString(socket_timeout, "timed out");
2547 return -1;
2549 if (n < 0) {
2550 s->errorhandler();
2551 return -1;
2554 if (!(*addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
2555 addrlen, s->sock_proto)))
2556 return -1;
2558 return n;
2561 /* s.recvfrom(nbytes [,flags]) method */
2563 static PyObject *
2564 sock_recvfrom(PySocketSockObject *s, PyObject *args)
2566 PyObject *buf = NULL;
2567 PyObject *addr = NULL;
2568 PyObject *ret = NULL;
2569 int recvlen, flags = 0;
2570 ssize_t outlen;
2572 if (!PyArg_ParseTuple(args, "i|i:recvfrom", &recvlen, &flags))
2573 return NULL;
2575 if (recvlen < 0) {
2576 PyErr_SetString(PyExc_ValueError,
2577 "negative buffersize in recvfrom");
2578 return NULL;
2581 buf = PyString_FromStringAndSize((char *) 0, recvlen);
2582 if (buf == NULL)
2583 return NULL;
2585 outlen = sock_recvfrom_guts(s, PyString_AS_STRING(buf),
2586 recvlen, flags, &addr);
2587 if (outlen < 0) {
2588 goto finally;
2591 if (outlen != recvlen) {
2592 /* We did not read as many bytes as we anticipated, resize the
2593 string if possible and be succesful. */
2594 if (_PyString_Resize(&buf, outlen) < 0)
2595 /* Oopsy, not so succesful after all. */
2596 goto finally;
2599 ret = PyTuple_Pack(2, buf, addr);
2601 finally:
2602 Py_XDECREF(buf);
2603 Py_XDECREF(addr);
2604 return ret;
2607 PyDoc_STRVAR(recvfrom_doc,
2608 "recvfrom(buffersize[, flags]) -> (data, address info)\n\
2610 Like recv(buffersize, flags) but also return the sender's address info.");
2613 /* s.recvfrom_into(buffer[, nbytes [,flags]]) method */
2615 static PyObject *
2616 sock_recvfrom_into(PySocketSockObject *s, PyObject *args, PyObject* kwds)
2618 static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
2620 int recvlen = 0, flags = 0;
2621 ssize_t readlen;
2622 char *buf;
2623 int buflen;
2625 PyObject *addr = NULL;
2627 if (!PyArg_ParseTupleAndKeywords(args, kwds, "w#|ii:recvfrom_into",
2628 kwlist, &buf, &buflen,
2629 &recvlen, &flags))
2630 return NULL;
2631 assert(buf != 0 && buflen > 0);
2633 if (recvlen < 0) {
2634 PyErr_SetString(PyExc_ValueError,
2635 "negative buffersize in recvfrom_into");
2636 return NULL;
2638 if (recvlen == 0) {
2639 /* If nbytes was not specified, use the buffer's length */
2640 recvlen = buflen;
2643 readlen = sock_recvfrom_guts(s, buf, recvlen, flags, &addr);
2644 if (readlen < 0) {
2645 /* Return an error */
2646 Py_XDECREF(addr);
2647 return NULL;
2650 /* Return the number of bytes read and the address. Note that we do
2651 not do anything special here in the case that readlen < recvlen. */
2652 return Py_BuildValue("lN", readlen, addr);
2655 PyDoc_STRVAR(recvfrom_into_doc,
2656 "recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)\n\
2658 Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.");
2661 /* s.send(data [,flags]) method */
2663 static PyObject *
2664 sock_send(PySocketSockObject *s, PyObject *args)
2666 char *buf;
2667 int len, n = -1, flags = 0, timeout;
2668 Py_buffer pbuf;
2670 if (!PyArg_ParseTuple(args, "s*|i:send", &pbuf, &flags))
2671 return NULL;
2673 if (!IS_SELECTABLE(s)) {
2674 PyBuffer_Release(&pbuf);
2675 return select_error();
2677 buf = pbuf.buf;
2678 len = pbuf.len;
2680 Py_BEGIN_ALLOW_THREADS
2681 timeout = internal_select(s, 1);
2682 if (!timeout)
2683 #ifdef __VMS
2684 n = sendsegmented(s->sock_fd, buf, len, flags);
2685 #else
2686 n = send(s->sock_fd, buf, len, flags);
2687 #endif
2688 Py_END_ALLOW_THREADS
2690 PyBuffer_Release(&pbuf);
2692 if (timeout == 1) {
2693 PyErr_SetString(socket_timeout, "timed out");
2694 return NULL;
2696 if (n < 0)
2697 return s->errorhandler();
2698 return PyInt_FromLong((long)n);
2701 PyDoc_STRVAR(send_doc,
2702 "send(data[, flags]) -> count\n\
2704 Send a data string to the socket. For the optional flags\n\
2705 argument, see the Unix manual. Return the number of bytes\n\
2706 sent; this may be less than len(data) if the network is busy.");
2709 /* s.sendall(data [,flags]) method */
2711 static PyObject *
2712 sock_sendall(PySocketSockObject *s, PyObject *args)
2714 char *buf;
2715 int len, n = -1, flags = 0, timeout;
2716 Py_buffer pbuf;
2718 if (!PyArg_ParseTuple(args, "s*|i:sendall", &pbuf, &flags))
2719 return NULL;
2720 buf = pbuf.buf;
2721 len = pbuf.len;
2723 if (!IS_SELECTABLE(s)) {
2724 PyBuffer_Release(&pbuf);
2725 return select_error();
2728 Py_BEGIN_ALLOW_THREADS
2729 do {
2730 timeout = internal_select(s, 1);
2731 n = -1;
2732 if (timeout)
2733 break;
2734 #ifdef __VMS
2735 n = sendsegmented(s->sock_fd, buf, len, flags);
2736 #else
2737 n = send(s->sock_fd, buf, len, flags);
2738 #endif
2739 if (n < 0) {
2740 #ifdef EINTR
2741 /* We must handle EINTR here as there is no way for
2742 * the caller to know how much was sent otherwise. */
2743 if (errno == EINTR) {
2744 /* Run signal handlers. If an exception was
2745 * raised, abort and leave this socket in
2746 * an unknown state. */
2747 if (PyErr_CheckSignals())
2748 return NULL;
2749 continue;
2751 #endif
2752 break;
2754 buf += n;
2755 len -= n;
2756 } while (len > 0);
2757 Py_END_ALLOW_THREADS
2758 PyBuffer_Release(&pbuf);
2760 if (timeout == 1) {
2761 PyErr_SetString(socket_timeout, "timed out");
2762 return NULL;
2764 if (n < 0)
2765 return s->errorhandler();
2767 Py_INCREF(Py_None);
2768 return Py_None;
2771 PyDoc_STRVAR(sendall_doc,
2772 "sendall(data[, flags])\n\
2774 Send a data string to the socket. For the optional flags\n\
2775 argument, see the Unix manual. This calls send() repeatedly\n\
2776 until all data is sent. If an error occurs, it's impossible\n\
2777 to tell how much data has been sent.");
2780 /* s.sendto(data, [flags,] sockaddr) method */
2782 static PyObject *
2783 sock_sendto(PySocketSockObject *s, PyObject *args)
2785 Py_buffer pbuf;
2786 PyObject *addro;
2787 char *buf;
2788 Py_ssize_t len;
2789 sock_addr_t addrbuf;
2790 int addrlen, n = -1, flags, timeout;
2792 flags = 0;
2793 if (!PyArg_ParseTuple(args, "s*O:sendto", &pbuf, &addro)) {
2794 PyErr_Clear();
2795 if (!PyArg_ParseTuple(args, "s*iO:sendto",
2796 &pbuf, &flags, &addro))
2797 return NULL;
2799 buf = pbuf.buf;
2800 len = pbuf.len;
2802 if (!IS_SELECTABLE(s)) {
2803 PyBuffer_Release(&pbuf);
2804 return select_error();
2807 if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) {
2808 PyBuffer_Release(&pbuf);
2809 return NULL;
2812 Py_BEGIN_ALLOW_THREADS
2813 timeout = internal_select(s, 1);
2814 if (!timeout)
2815 n = sendto(s->sock_fd, buf, len, flags, SAS2SA(&addrbuf), addrlen);
2816 Py_END_ALLOW_THREADS
2818 PyBuffer_Release(&pbuf);
2819 if (timeout == 1) {
2820 PyErr_SetString(socket_timeout, "timed out");
2821 return NULL;
2823 if (n < 0)
2824 return s->errorhandler();
2825 return PyInt_FromLong((long)n);
2828 PyDoc_STRVAR(sendto_doc,
2829 "sendto(data[, flags], address) -> count\n\
2831 Like send(data, flags) but allows specifying the destination address.\n\
2832 For IP sockets, the address is a pair (hostaddr, port).");
2835 /* s.shutdown(how) method */
2837 static PyObject *
2838 sock_shutdown(PySocketSockObject *s, PyObject *arg)
2840 int how;
2841 int res;
2843 how = PyInt_AsLong(arg);
2844 if (how == -1 && PyErr_Occurred())
2845 return NULL;
2846 Py_BEGIN_ALLOW_THREADS
2847 res = shutdown(s->sock_fd, how);
2848 Py_END_ALLOW_THREADS
2849 if (res < 0)
2850 return s->errorhandler();
2851 Py_INCREF(Py_None);
2852 return Py_None;
2855 PyDoc_STRVAR(shutdown_doc,
2856 "shutdown(flag)\n\
2858 Shut down the reading side of the socket (flag == SHUT_RD), the writing side\n\
2859 of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).");
2861 #if defined(MS_WINDOWS) && defined(SIO_RCVALL)
2862 static PyObject*
2863 sock_ioctl(PySocketSockObject *s, PyObject *arg)
2865 unsigned long cmd = SIO_RCVALL;
2866 PyObject *argO;
2867 DWORD recv;
2869 if (!PyArg_ParseTuple(arg, "kO:ioctl", &cmd, &argO))
2870 return NULL;
2872 switch (cmd) {
2873 case SIO_RCVALL: {
2874 unsigned int option = RCVALL_ON;
2875 if (!PyArg_ParseTuple(arg, "kI:ioctl", &cmd, &option))
2876 return NULL;
2877 if (WSAIoctl(s->sock_fd, cmd, &option, sizeof(option),
2878 NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
2879 return set_error();
2881 return PyLong_FromUnsignedLong(recv); }
2882 case SIO_KEEPALIVE_VALS: {
2883 struct tcp_keepalive ka;
2884 if (!PyArg_ParseTuple(arg, "k(kkk):ioctl", &cmd,
2885 &ka.onoff, &ka.keepalivetime, &ka.keepaliveinterval))
2886 return NULL;
2887 if (WSAIoctl(s->sock_fd, cmd, &ka, sizeof(ka),
2888 NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
2889 return set_error();
2891 return PyLong_FromUnsignedLong(recv); }
2892 default:
2893 PyErr_Format(PyExc_ValueError, "invalid ioctl command %d", cmd);
2894 return NULL;
2897 PyDoc_STRVAR(sock_ioctl_doc,
2898 "ioctl(cmd, option) -> long\n\
2900 Control the socket with WSAIoctl syscall. Currently supported 'cmd' values are\n\
2901 SIO_RCVALL: 'option' must be one of the socket.RCVALL_* constants.\n\
2902 SIO_KEEPALIVE_VALS: 'option' is a tuple of (onoff, timeout, interval).");
2904 #endif
2906 /* List of methods for socket objects */
2908 static PyMethodDef sock_methods[] = {
2909 {"accept", (PyCFunction)sock_accept, METH_NOARGS,
2910 accept_doc},
2911 {"bind", (PyCFunction)sock_bind, METH_O,
2912 bind_doc},
2913 {"close", (PyCFunction)sock_close, METH_NOARGS,
2914 close_doc},
2915 {"connect", (PyCFunction)sock_connect, METH_O,
2916 connect_doc},
2917 {"connect_ex", (PyCFunction)sock_connect_ex, METH_O,
2918 connect_ex_doc},
2919 #ifndef NO_DUP
2920 {"dup", (PyCFunction)sock_dup, METH_NOARGS,
2921 dup_doc},
2922 #endif
2923 {"fileno", (PyCFunction)sock_fileno, METH_NOARGS,
2924 fileno_doc},
2925 #ifdef HAVE_GETPEERNAME
2926 {"getpeername", (PyCFunction)sock_getpeername,
2927 METH_NOARGS, getpeername_doc},
2928 #endif
2929 {"getsockname", (PyCFunction)sock_getsockname,
2930 METH_NOARGS, getsockname_doc},
2931 {"getsockopt", (PyCFunction)sock_getsockopt, METH_VARARGS,
2932 getsockopt_doc},
2933 #if defined(MS_WINDOWS) && defined(SIO_RCVALL)
2934 {"ioctl", (PyCFunction)sock_ioctl, METH_VARARGS,
2935 sock_ioctl_doc},
2936 #endif
2937 {"listen", (PyCFunction)sock_listen, METH_O,
2938 listen_doc},
2939 #ifndef NO_DUP
2940 {"makefile", (PyCFunction)sock_makefile, METH_VARARGS,
2941 makefile_doc},
2942 #endif
2943 {"recv", (PyCFunction)sock_recv, METH_VARARGS,
2944 recv_doc},
2945 {"recv_into", (PyCFunction)sock_recv_into, METH_VARARGS | METH_KEYWORDS,
2946 recv_into_doc},
2947 {"recvfrom", (PyCFunction)sock_recvfrom, METH_VARARGS,
2948 recvfrom_doc},
2949 {"recvfrom_into", (PyCFunction)sock_recvfrom_into, METH_VARARGS | METH_KEYWORDS,
2950 recvfrom_into_doc},
2951 {"send", (PyCFunction)sock_send, METH_VARARGS,
2952 send_doc},
2953 {"sendall", (PyCFunction)sock_sendall, METH_VARARGS,
2954 sendall_doc},
2955 {"sendto", (PyCFunction)sock_sendto, METH_VARARGS,
2956 sendto_doc},
2957 {"setblocking", (PyCFunction)sock_setblocking, METH_O,
2958 setblocking_doc},
2959 {"settimeout", (PyCFunction)sock_settimeout, METH_O,
2960 settimeout_doc},
2961 {"gettimeout", (PyCFunction)sock_gettimeout, METH_NOARGS,
2962 gettimeout_doc},
2963 {"setsockopt", (PyCFunction)sock_setsockopt, METH_VARARGS,
2964 setsockopt_doc},
2965 {"shutdown", (PyCFunction)sock_shutdown, METH_O,
2966 shutdown_doc},
2967 #ifdef RISCOS
2968 {"sleeptaskw", (PyCFunction)sock_sleeptaskw, METH_O,
2969 sleeptaskw_doc},
2970 #endif
2971 {NULL, NULL} /* sentinel */
2974 /* SockObject members */
2975 static PyMemberDef sock_memberlist[] = {
2976 {"family", T_INT, offsetof(PySocketSockObject, sock_family), READONLY, "the socket family"},
2977 {"type", T_INT, offsetof(PySocketSockObject, sock_type), READONLY, "the socket type"},
2978 {"proto", T_INT, offsetof(PySocketSockObject, sock_proto), READONLY, "the socket protocol"},
2979 {"timeout", T_DOUBLE, offsetof(PySocketSockObject, sock_timeout), READONLY, "the socket timeout"},
2980 {0},
2983 /* Deallocate a socket object in response to the last Py_DECREF().
2984 First close the file description. */
2986 static void
2987 sock_dealloc(PySocketSockObject *s)
2989 if (s->sock_fd != -1)
2990 (void) SOCKETCLOSE(s->sock_fd);
2991 Py_TYPE(s)->tp_free((PyObject *)s);
2995 static PyObject *
2996 sock_repr(PySocketSockObject *s)
2998 char buf[512];
2999 #if SIZEOF_SOCKET_T > SIZEOF_LONG
3000 if (s->sock_fd > LONG_MAX) {
3001 /* this can occur on Win64, and actually there is a special
3002 ugly printf formatter for decimal pointer length integer
3003 printing, only bother if necessary*/
3004 PyErr_SetString(PyExc_OverflowError,
3005 "no printf formatter to display "
3006 "the socket descriptor in decimal");
3007 return NULL;
3009 #endif
3010 PyOS_snprintf(
3011 buf, sizeof(buf),
3012 "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
3013 (long)s->sock_fd, s->sock_family,
3014 s->sock_type,
3015 s->sock_proto);
3016 return PyString_FromString(buf);
3020 /* Create a new, uninitialized socket object. */
3022 static PyObject *
3023 sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3025 PyObject *new;
3027 new = type->tp_alloc(type, 0);
3028 if (new != NULL) {
3029 ((PySocketSockObject *)new)->sock_fd = -1;
3030 ((PySocketSockObject *)new)->sock_timeout = -1.0;
3031 ((PySocketSockObject *)new)->errorhandler = &set_error;
3033 return new;
3037 /* Initialize a new socket object. */
3039 /*ARGSUSED*/
3040 static int
3041 sock_initobj(PyObject *self, PyObject *args, PyObject *kwds)
3043 PySocketSockObject *s = (PySocketSockObject *)self;
3044 SOCKET_T fd;
3045 int family = AF_INET, type = SOCK_STREAM, proto = 0;
3046 static char *keywords[] = {"family", "type", "proto", 0};
3048 if (!PyArg_ParseTupleAndKeywords(args, kwds,
3049 "|iii:socket", keywords,
3050 &family, &type, &proto))
3051 return -1;
3053 Py_BEGIN_ALLOW_THREADS
3054 fd = socket(family, type, proto);
3055 Py_END_ALLOW_THREADS
3057 #ifdef MS_WINDOWS
3058 if (fd == INVALID_SOCKET)
3059 #else
3060 if (fd < 0)
3061 #endif
3063 set_error();
3064 return -1;
3066 init_sockobject(s, fd, family, type, proto);
3068 return 0;
3073 /* Type object for socket objects. */
3075 static PyTypeObject sock_type = {
3076 PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */
3077 "_socket.socket", /* tp_name */
3078 sizeof(PySocketSockObject), /* tp_basicsize */
3079 0, /* tp_itemsize */
3080 (destructor)sock_dealloc, /* tp_dealloc */
3081 0, /* tp_print */
3082 0, /* tp_getattr */
3083 0, /* tp_setattr */
3084 0, /* tp_compare */
3085 (reprfunc)sock_repr, /* tp_repr */
3086 0, /* tp_as_number */
3087 0, /* tp_as_sequence */
3088 0, /* tp_as_mapping */
3089 0, /* tp_hash */
3090 0, /* tp_call */
3091 0, /* tp_str */
3092 PyObject_GenericGetAttr, /* tp_getattro */
3093 0, /* tp_setattro */
3094 0, /* tp_as_buffer */
3095 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3096 sock_doc, /* tp_doc */
3097 0, /* tp_traverse */
3098 0, /* tp_clear */
3099 0, /* tp_richcompare */
3100 0, /* tp_weaklistoffset */
3101 0, /* tp_iter */
3102 0, /* tp_iternext */
3103 sock_methods, /* tp_methods */
3104 sock_memberlist, /* tp_members */
3105 0, /* tp_getset */
3106 0, /* tp_base */
3107 0, /* tp_dict */
3108 0, /* tp_descr_get */
3109 0, /* tp_descr_set */
3110 0, /* tp_dictoffset */
3111 sock_initobj, /* tp_init */
3112 PyType_GenericAlloc, /* tp_alloc */
3113 sock_new, /* tp_new */
3114 PyObject_Del, /* tp_free */
3118 /* Python interface to gethostname(). */
3120 /*ARGSUSED*/
3121 static PyObject *
3122 socket_gethostname(PyObject *self, PyObject *unused)
3124 char buf[1024];
3125 int res;
3126 Py_BEGIN_ALLOW_THREADS
3127 res = gethostname(buf, (int) sizeof buf - 1);
3128 Py_END_ALLOW_THREADS
3129 if (res < 0)
3130 return set_error();
3131 buf[sizeof buf - 1] = '\0';
3132 return PyString_FromString(buf);
3135 PyDoc_STRVAR(gethostname_doc,
3136 "gethostname() -> string\n\
3138 Return the current host name.");
3141 /* Python interface to gethostbyname(name). */
3143 /*ARGSUSED*/
3144 static PyObject *
3145 socket_gethostbyname(PyObject *self, PyObject *args)
3147 char *name;
3148 sock_addr_t addrbuf;
3150 if (!PyArg_ParseTuple(args, "s:gethostbyname", &name))
3151 return NULL;
3152 if (setipaddr(name, SAS2SA(&addrbuf), sizeof(addrbuf), AF_INET) < 0)
3153 return NULL;
3154 return makeipaddr(SAS2SA(&addrbuf), sizeof(struct sockaddr_in));
3157 PyDoc_STRVAR(gethostbyname_doc,
3158 "gethostbyname(host) -> address\n\
3160 Return the IP address (a string of the form '255.255.255.255') for a host.");
3163 /* Convenience function common to gethostbyname_ex and gethostbyaddr */
3165 static PyObject *
3166 gethost_common(struct hostent *h, struct sockaddr *addr, int alen, int af)
3168 char **pch;
3169 PyObject *rtn_tuple = (PyObject *)NULL;
3170 PyObject *name_list = (PyObject *)NULL;
3171 PyObject *addr_list = (PyObject *)NULL;
3172 PyObject *tmp;
3174 if (h == NULL) {
3175 /* Let's get real error message to return */
3176 #ifndef RISCOS
3177 set_herror(h_errno);
3178 #else
3179 PyErr_SetString(socket_error, "host not found");
3180 #endif
3181 return NULL;
3184 if (h->h_addrtype != af) {
3185 /* Let's get real error message to return */
3186 PyErr_SetString(socket_error,
3187 (char *)strerror(EAFNOSUPPORT));
3189 return NULL;
3192 switch (af) {
3194 case AF_INET:
3195 if (alen < sizeof(struct sockaddr_in))
3196 return NULL;
3197 break;
3199 #ifdef ENABLE_IPV6
3200 case AF_INET6:
3201 if (alen < sizeof(struct sockaddr_in6))
3202 return NULL;
3203 break;
3204 #endif
3208 if ((name_list = PyList_New(0)) == NULL)
3209 goto err;
3211 if ((addr_list = PyList_New(0)) == NULL)
3212 goto err;
3214 /* SF #1511317: h_aliases can be NULL */
3215 if (h->h_aliases) {
3216 for (pch = h->h_aliases; *pch != NULL; pch++) {
3217 int status;
3218 tmp = PyString_FromString(*pch);
3219 if (tmp == NULL)
3220 goto err;
3222 status = PyList_Append(name_list, tmp);
3223 Py_DECREF(tmp);
3225 if (status)
3226 goto err;
3230 for (pch = h->h_addr_list; *pch != NULL; pch++) {
3231 int status;
3233 switch (af) {
3235 case AF_INET:
3237 struct sockaddr_in sin;
3238 memset(&sin, 0, sizeof(sin));
3239 sin.sin_family = af;
3240 #ifdef HAVE_SOCKADDR_SA_LEN
3241 sin.sin_len = sizeof(sin);
3242 #endif
3243 memcpy(&sin.sin_addr, *pch, sizeof(sin.sin_addr));
3244 tmp = makeipaddr((struct sockaddr *)&sin, sizeof(sin));
3246 if (pch == h->h_addr_list && alen >= sizeof(sin))
3247 memcpy((char *) addr, &sin, sizeof(sin));
3248 break;
3251 #ifdef ENABLE_IPV6
3252 case AF_INET6:
3254 struct sockaddr_in6 sin6;
3255 memset(&sin6, 0, sizeof(sin6));
3256 sin6.sin6_family = af;
3257 #ifdef HAVE_SOCKADDR_SA_LEN
3258 sin6.sin6_len = sizeof(sin6);
3259 #endif
3260 memcpy(&sin6.sin6_addr, *pch, sizeof(sin6.sin6_addr));
3261 tmp = makeipaddr((struct sockaddr *)&sin6,
3262 sizeof(sin6));
3264 if (pch == h->h_addr_list && alen >= sizeof(sin6))
3265 memcpy((char *) addr, &sin6, sizeof(sin6));
3266 break;
3268 #endif
3270 default: /* can't happen */
3271 PyErr_SetString(socket_error,
3272 "unsupported address family");
3273 return NULL;
3276 if (tmp == NULL)
3277 goto err;
3279 status = PyList_Append(addr_list, tmp);
3280 Py_DECREF(tmp);
3282 if (status)
3283 goto err;
3286 rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list);
3288 err:
3289 Py_XDECREF(name_list);
3290 Py_XDECREF(addr_list);
3291 return rtn_tuple;
3295 /* Python interface to gethostbyname_ex(name). */
3297 /*ARGSUSED*/
3298 static PyObject *
3299 socket_gethostbyname_ex(PyObject *self, PyObject *args)
3301 char *name;
3302 struct hostent *h;
3303 #ifdef ENABLE_IPV6
3304 struct sockaddr_storage addr;
3305 #else
3306 struct sockaddr_in addr;
3307 #endif
3308 struct sockaddr *sa;
3309 PyObject *ret;
3310 #ifdef HAVE_GETHOSTBYNAME_R
3311 struct hostent hp_allocated;
3312 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
3313 struct hostent_data data;
3314 #else
3315 char buf[16384];
3316 int buf_len = (sizeof buf) - 1;
3317 int errnop;
3318 #endif
3319 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3320 int result;
3321 #endif
3322 #endif /* HAVE_GETHOSTBYNAME_R */
3324 if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name))
3325 return NULL;
3326 if (setipaddr(name, (struct sockaddr *)&addr, sizeof(addr), AF_INET) < 0)
3327 return NULL;
3328 Py_BEGIN_ALLOW_THREADS
3329 #ifdef HAVE_GETHOSTBYNAME_R
3330 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3331 result = gethostbyname_r(name, &hp_allocated, buf, buf_len,
3332 &h, &errnop);
3333 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
3334 h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
3335 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
3336 memset((void *) &data, '\0', sizeof(data));
3337 result = gethostbyname_r(name, &hp_allocated, &data);
3338 h = (result != 0) ? NULL : &hp_allocated;
3339 #endif
3340 #else /* not HAVE_GETHOSTBYNAME_R */
3341 #ifdef USE_GETHOSTBYNAME_LOCK
3342 PyThread_acquire_lock(netdb_lock, 1);
3343 #endif
3344 h = gethostbyname(name);
3345 #endif /* HAVE_GETHOSTBYNAME_R */
3346 Py_END_ALLOW_THREADS
3347 /* Some C libraries would require addr.__ss_family instead of
3348 addr.ss_family.
3349 Therefore, we cast the sockaddr_storage into sockaddr to
3350 access sa_family. */
3351 sa = (struct sockaddr*)&addr;
3352 ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr),
3353 sa->sa_family);
3354 #ifdef USE_GETHOSTBYNAME_LOCK
3355 PyThread_release_lock(netdb_lock);
3356 #endif
3357 return ret;
3360 PyDoc_STRVAR(ghbn_ex_doc,
3361 "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
3363 Return the true host name, a list of aliases, and a list of IP addresses,\n\
3364 for a host. The host argument is a string giving a host name or IP number.");
3367 /* Python interface to gethostbyaddr(IP). */
3369 /*ARGSUSED*/
3370 static PyObject *
3371 socket_gethostbyaddr(PyObject *self, PyObject *args)
3373 #ifdef ENABLE_IPV6
3374 struct sockaddr_storage addr;
3375 #else
3376 struct sockaddr_in addr;
3377 #endif
3378 struct sockaddr *sa = (struct sockaddr *)&addr;
3379 char *ip_num;
3380 struct hostent *h;
3381 PyObject *ret;
3382 #ifdef HAVE_GETHOSTBYNAME_R
3383 struct hostent hp_allocated;
3384 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
3385 struct hostent_data data;
3386 #else
3387 /* glibcs up to 2.10 assume that the buf argument to
3388 gethostbyaddr_r is 8-byte aligned, which at least llvm-gcc
3389 does not ensure. The attribute below instructs the compiler
3390 to maintain this alignment. */
3391 char buf[16384] Py_ALIGNED(8);
3392 int buf_len = (sizeof buf) - 1;
3393 int errnop;
3394 #endif
3395 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3396 int result;
3397 #endif
3398 #endif /* HAVE_GETHOSTBYNAME_R */
3399 char *ap;
3400 int al;
3401 int af;
3403 if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num))
3404 return NULL;
3405 af = AF_UNSPEC;
3406 if (setipaddr(ip_num, sa, sizeof(addr), af) < 0)
3407 return NULL;
3408 af = sa->sa_family;
3409 ap = NULL;
3410 al = 0;
3411 switch (af) {
3412 case AF_INET:
3413 ap = (char *)&((struct sockaddr_in *)sa)->sin_addr;
3414 al = sizeof(((struct sockaddr_in *)sa)->sin_addr);
3415 break;
3416 #ifdef ENABLE_IPV6
3417 case AF_INET6:
3418 ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr;
3419 al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr);
3420 break;
3421 #endif
3422 default:
3423 PyErr_SetString(socket_error, "unsupported address family");
3424 return NULL;
3426 Py_BEGIN_ALLOW_THREADS
3427 #ifdef HAVE_GETHOSTBYNAME_R
3428 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3429 result = gethostbyaddr_r(ap, al, af,
3430 &hp_allocated, buf, buf_len,
3431 &h, &errnop);
3432 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
3433 h = gethostbyaddr_r(ap, al, af,
3434 &hp_allocated, buf, buf_len, &errnop);
3435 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
3436 memset((void *) &data, '\0', sizeof(data));
3437 result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data);
3438 h = (result != 0) ? NULL : &hp_allocated;
3439 #endif
3440 #else /* not HAVE_GETHOSTBYNAME_R */
3441 #ifdef USE_GETHOSTBYNAME_LOCK
3442 PyThread_acquire_lock(netdb_lock, 1);
3443 #endif
3444 h = gethostbyaddr(ap, al, af);
3445 #endif /* HAVE_GETHOSTBYNAME_R */
3446 Py_END_ALLOW_THREADS
3447 ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), af);
3448 #ifdef USE_GETHOSTBYNAME_LOCK
3449 PyThread_release_lock(netdb_lock);
3450 #endif
3451 return ret;
3454 PyDoc_STRVAR(gethostbyaddr_doc,
3455 "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
3457 Return the true host name, a list of aliases, and a list of IP addresses,\n\
3458 for a host. The host argument is a string giving a host name or IP number.");
3461 /* Python interface to getservbyname(name).
3462 This only returns the port number, since the other info is already
3463 known or not useful (like the list of aliases). */
3465 /*ARGSUSED*/
3466 static PyObject *
3467 socket_getservbyname(PyObject *self, PyObject *args)
3469 char *name, *proto=NULL;
3470 struct servent *sp;
3471 if (!PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto))
3472 return NULL;
3473 Py_BEGIN_ALLOW_THREADS
3474 sp = getservbyname(name, proto);
3475 Py_END_ALLOW_THREADS
3476 if (sp == NULL) {
3477 PyErr_SetString(socket_error, "service/proto not found");
3478 return NULL;
3480 return PyInt_FromLong((long) ntohs(sp->s_port));
3483 PyDoc_STRVAR(getservbyname_doc,
3484 "getservbyname(servicename[, protocolname]) -> integer\n\
3486 Return a port number from a service name and protocol name.\n\
3487 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3488 otherwise any protocol will match.");
3491 /* Python interface to getservbyport(port).
3492 This only returns the service name, since the other info is already
3493 known or not useful (like the list of aliases). */
3495 /*ARGSUSED*/
3496 static PyObject *
3497 socket_getservbyport(PyObject *self, PyObject *args)
3499 int port;
3500 char *proto=NULL;
3501 struct servent *sp;
3502 if (!PyArg_ParseTuple(args, "i|s:getservbyport", &port, &proto))
3503 return NULL;
3504 if (port < 0 || port > 0xffff) {
3505 PyErr_SetString(
3506 PyExc_OverflowError,
3507 "getservbyport: port must be 0-65535.");
3508 return NULL;
3510 Py_BEGIN_ALLOW_THREADS
3511 sp = getservbyport(htons((short)port), proto);
3512 Py_END_ALLOW_THREADS
3513 if (sp == NULL) {
3514 PyErr_SetString(socket_error, "port/proto not found");
3515 return NULL;
3517 return PyString_FromString(sp->s_name);
3520 PyDoc_STRVAR(getservbyport_doc,
3521 "getservbyport(port[, protocolname]) -> string\n\
3523 Return the service name from a port number and protocol name.\n\
3524 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3525 otherwise any protocol will match.");
3527 /* Python interface to getprotobyname(name).
3528 This only returns the protocol number, since the other info is
3529 already known or not useful (like the list of aliases). */
3531 /*ARGSUSED*/
3532 static PyObject *
3533 socket_getprotobyname(PyObject *self, PyObject *args)
3535 char *name;
3536 struct protoent *sp;
3537 #ifdef __BEOS__
3538 /* Not available in BeOS yet. - [cjh] */
3539 PyErr_SetString(socket_error, "getprotobyname not supported");
3540 return NULL;
3541 #else
3542 if (!PyArg_ParseTuple(args, "s:getprotobyname", &name))
3543 return NULL;
3544 Py_BEGIN_ALLOW_THREADS
3545 sp = getprotobyname(name);
3546 Py_END_ALLOW_THREADS
3547 if (sp == NULL) {
3548 PyErr_SetString(socket_error, "protocol not found");
3549 return NULL;
3551 return PyInt_FromLong((long) sp->p_proto);
3552 #endif
3555 PyDoc_STRVAR(getprotobyname_doc,
3556 "getprotobyname(name) -> integer\n\
3558 Return the protocol number for the named protocol. (Rarely used.)");
3561 #ifdef HAVE_SOCKETPAIR
3562 /* Create a pair of sockets using the socketpair() function.
3563 Arguments as for socket() except the default family is AF_UNIX if
3564 defined on the platform; otherwise, the default is AF_INET. */
3566 /*ARGSUSED*/
3567 static PyObject *
3568 socket_socketpair(PyObject *self, PyObject *args)
3570 PySocketSockObject *s0 = NULL, *s1 = NULL;
3571 SOCKET_T sv[2];
3572 int family, type = SOCK_STREAM, proto = 0;
3573 PyObject *res = NULL;
3575 #if defined(AF_UNIX)
3576 family = AF_UNIX;
3577 #else
3578 family = AF_INET;
3579 #endif
3580 if (!PyArg_ParseTuple(args, "|iii:socketpair",
3581 &family, &type, &proto))
3582 return NULL;
3583 /* Create a pair of socket fds */
3584 if (socketpair(family, type, proto, sv) < 0)
3585 return set_error();
3586 s0 = new_sockobject(sv[0], family, type, proto);
3587 if (s0 == NULL)
3588 goto finally;
3589 s1 = new_sockobject(sv[1], family, type, proto);
3590 if (s1 == NULL)
3591 goto finally;
3592 res = PyTuple_Pack(2, s0, s1);
3594 finally:
3595 if (res == NULL) {
3596 if (s0 == NULL)
3597 SOCKETCLOSE(sv[0]);
3598 if (s1 == NULL)
3599 SOCKETCLOSE(sv[1]);
3601 Py_XDECREF(s0);
3602 Py_XDECREF(s1);
3603 return res;
3606 PyDoc_STRVAR(socketpair_doc,
3607 "socketpair([family[, type[, proto]]]) -> (socket object, socket object)\n\
3609 Create a pair of socket objects from the sockets returned by the platform\n\
3610 socketpair() function.\n\
3611 The arguments are the same as for socket() except the default family is\n\
3612 AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");
3614 #endif /* HAVE_SOCKETPAIR */
3617 #ifndef NO_DUP
3618 /* Create a socket object from a numeric file description.
3619 Useful e.g. if stdin is a socket.
3620 Additional arguments as for socket(). */
3622 /*ARGSUSED*/
3623 static PyObject *
3624 socket_fromfd(PyObject *self, PyObject *args)
3626 PySocketSockObject *s;
3627 SOCKET_T fd;
3628 int family, type, proto = 0;
3629 if (!PyArg_ParseTuple(args, "iii|i:fromfd",
3630 &fd, &family, &type, &proto))
3631 return NULL;
3632 /* Dup the fd so it and the socket can be closed independently */
3633 fd = dup(fd);
3634 if (fd < 0)
3635 return set_error();
3636 s = new_sockobject(fd, family, type, proto);
3637 return (PyObject *) s;
3640 PyDoc_STRVAR(fromfd_doc,
3641 "fromfd(fd, family, type[, proto]) -> socket object\n\
3643 Create a socket object from a duplicate of the given\n\
3644 file descriptor.\n\
3645 The remaining arguments are the same as for socket().");
3647 #endif /* NO_DUP */
3650 static PyObject *
3651 socket_ntohs(PyObject *self, PyObject *args)
3653 int x1, x2;
3655 if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) {
3656 return NULL;
3658 if (x1 < 0) {
3659 PyErr_SetString(PyExc_OverflowError,
3660 "can't convert negative number to unsigned long");
3661 return NULL;
3663 x2 = (unsigned int)ntohs((unsigned short)x1);
3664 return PyInt_FromLong(x2);
3667 PyDoc_STRVAR(ntohs_doc,
3668 "ntohs(integer) -> integer\n\
3670 Convert a 16-bit integer from network to host byte order.");
3673 static PyObject *
3674 socket_ntohl(PyObject *self, PyObject *arg)
3676 unsigned long x;
3678 if (PyInt_Check(arg)) {
3679 x = PyInt_AS_LONG(arg);
3680 if (x == (unsigned long) -1 && PyErr_Occurred())
3681 return NULL;
3682 if ((long)x < 0) {
3683 PyErr_SetString(PyExc_OverflowError,
3684 "can't convert negative number to unsigned long");
3685 return NULL;
3688 else if (PyLong_Check(arg)) {
3689 x = PyLong_AsUnsignedLong(arg);
3690 if (x == (unsigned long) -1 && PyErr_Occurred())
3691 return NULL;
3692 #if SIZEOF_LONG > 4
3694 unsigned long y;
3695 /* only want the trailing 32 bits */
3696 y = x & 0xFFFFFFFFUL;
3697 if (y ^ x)
3698 return PyErr_Format(PyExc_OverflowError,
3699 "long int larger than 32 bits");
3700 x = y;
3702 #endif
3704 else
3705 return PyErr_Format(PyExc_TypeError,
3706 "expected int/long, %s found",
3707 Py_TYPE(arg)->tp_name);
3708 if (x == (unsigned long) -1 && PyErr_Occurred())
3709 return NULL;
3710 return PyLong_FromUnsignedLong(ntohl(x));
3713 PyDoc_STRVAR(ntohl_doc,
3714 "ntohl(integer) -> integer\n\
3716 Convert a 32-bit integer from network to host byte order.");
3719 static PyObject *
3720 socket_htons(PyObject *self, PyObject *args)
3722 int x1, x2;
3724 if (!PyArg_ParseTuple(args, "i:htons", &x1)) {
3725 return NULL;
3727 if (x1 < 0) {
3728 PyErr_SetString(PyExc_OverflowError,
3729 "can't convert negative number to unsigned long");
3730 return NULL;
3732 x2 = (unsigned int)htons((unsigned short)x1);
3733 return PyInt_FromLong(x2);
3736 PyDoc_STRVAR(htons_doc,
3737 "htons(integer) -> integer\n\
3739 Convert a 16-bit integer from host to network byte order.");
3742 static PyObject *
3743 socket_htonl(PyObject *self, PyObject *arg)
3745 unsigned long x;
3747 if (PyInt_Check(arg)) {
3748 x = PyInt_AS_LONG(arg);
3749 if (x == (unsigned long) -1 && PyErr_Occurred())
3750 return NULL;
3751 if ((long)x < 0) {
3752 PyErr_SetString(PyExc_OverflowError,
3753 "can't convert negative number to unsigned long");
3754 return NULL;
3757 else if (PyLong_Check(arg)) {
3758 x = PyLong_AsUnsignedLong(arg);
3759 if (x == (unsigned long) -1 && PyErr_Occurred())
3760 return NULL;
3761 #if SIZEOF_LONG > 4
3763 unsigned long y;
3764 /* only want the trailing 32 bits */
3765 y = x & 0xFFFFFFFFUL;
3766 if (y ^ x)
3767 return PyErr_Format(PyExc_OverflowError,
3768 "long int larger than 32 bits");
3769 x = y;
3771 #endif
3773 else
3774 return PyErr_Format(PyExc_TypeError,
3775 "expected int/long, %s found",
3776 Py_TYPE(arg)->tp_name);
3777 return PyLong_FromUnsignedLong(htonl((unsigned long)x));
3780 PyDoc_STRVAR(htonl_doc,
3781 "htonl(integer) -> integer\n\
3783 Convert a 32-bit integer from host to network byte order.");
3785 /* socket.inet_aton() and socket.inet_ntoa() functions. */
3787 PyDoc_STRVAR(inet_aton_doc,
3788 "inet_aton(string) -> packed 32-bit IP representation\n\
3790 Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
3791 binary format used in low-level network functions.");
3793 static PyObject*
3794 socket_inet_aton(PyObject *self, PyObject *args)
3796 #ifndef INADDR_NONE
3797 #define INADDR_NONE (-1)
3798 #endif
3799 #ifdef HAVE_INET_ATON
3800 struct in_addr buf;
3801 #endif
3803 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
3804 #if (SIZEOF_INT != 4)
3805 #error "Not sure if in_addr_t exists and int is not 32-bits."
3806 #endif
3807 /* Have to use inet_addr() instead */
3808 unsigned int packed_addr;
3809 #endif
3810 char *ip_addr;
3812 if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr))
3813 return NULL;
3816 #ifdef HAVE_INET_ATON
3818 #ifdef USE_INET_ATON_WEAKLINK
3819 if (inet_aton != NULL) {
3820 #endif
3821 if (inet_aton(ip_addr, &buf))
3822 return PyString_FromStringAndSize((char *)(&buf),
3823 sizeof(buf));
3825 PyErr_SetString(socket_error,
3826 "illegal IP address string passed to inet_aton");
3827 return NULL;
3829 #ifdef USE_INET_ATON_WEAKLINK
3830 } else {
3831 #endif
3833 #endif
3835 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
3837 /* special-case this address as inet_addr might return INADDR_NONE
3838 * for this */
3839 if (strcmp(ip_addr, "255.255.255.255") == 0) {
3840 packed_addr = 0xFFFFFFFF;
3841 } else {
3843 packed_addr = inet_addr(ip_addr);
3845 if (packed_addr == INADDR_NONE) { /* invalid address */
3846 PyErr_SetString(socket_error,
3847 "illegal IP address string passed to inet_aton");
3848 return NULL;
3851 return PyString_FromStringAndSize((char *) &packed_addr,
3852 sizeof(packed_addr));
3854 #ifdef USE_INET_ATON_WEAKLINK
3856 #endif
3858 #endif
3861 PyDoc_STRVAR(inet_ntoa_doc,
3862 "inet_ntoa(packed_ip) -> ip_address_string\n\
3864 Convert an IP address from 32-bit packed binary format to string format");
3866 static PyObject*
3867 socket_inet_ntoa(PyObject *self, PyObject *args)
3869 char *packed_str;
3870 int addr_len;
3871 struct in_addr packed_addr;
3873 if (!PyArg_ParseTuple(args, "s#:inet_ntoa", &packed_str, &addr_len)) {
3874 return NULL;
3877 if (addr_len != sizeof(packed_addr)) {
3878 PyErr_SetString(socket_error,
3879 "packed IP wrong length for inet_ntoa");
3880 return NULL;
3883 memcpy(&packed_addr, packed_str, addr_len);
3885 return PyString_FromString(inet_ntoa(packed_addr));
3888 #ifdef HAVE_INET_PTON
3890 PyDoc_STRVAR(inet_pton_doc,
3891 "inet_pton(af, ip) -> packed IP address string\n\
3893 Convert an IP address from string format to a packed string suitable\n\
3894 for use with low-level network functions.");
3896 static PyObject *
3897 socket_inet_pton(PyObject *self, PyObject *args)
3899 int af;
3900 char* ip;
3901 int retval;
3902 #ifdef ENABLE_IPV6
3903 char packed[MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
3904 #else
3905 char packed[sizeof(struct in_addr)];
3906 #endif
3907 if (!PyArg_ParseTuple(args, "is:inet_pton", &af, &ip)) {
3908 return NULL;
3911 #if !defined(ENABLE_IPV6) && defined(AF_INET6)
3912 if(af == AF_INET6) {
3913 PyErr_SetString(socket_error,
3914 "can't use AF_INET6, IPv6 is disabled");
3915 return NULL;
3917 #endif
3919 retval = inet_pton(af, ip, packed);
3920 if (retval < 0) {
3921 PyErr_SetFromErrno(socket_error);
3922 return NULL;
3923 } else if (retval == 0) {
3924 PyErr_SetString(socket_error,
3925 "illegal IP address string passed to inet_pton");
3926 return NULL;
3927 } else if (af == AF_INET) {
3928 return PyString_FromStringAndSize(packed,
3929 sizeof(struct in_addr));
3930 #ifdef ENABLE_IPV6
3931 } else if (af == AF_INET6) {
3932 return PyString_FromStringAndSize(packed,
3933 sizeof(struct in6_addr));
3934 #endif
3935 } else {
3936 PyErr_SetString(socket_error, "unknown address family");
3937 return NULL;
3941 PyDoc_STRVAR(inet_ntop_doc,
3942 "inet_ntop(af, packed_ip) -> string formatted IP address\n\
3944 Convert a packed IP address of the given family to string format.");
3946 static PyObject *
3947 socket_inet_ntop(PyObject *self, PyObject *args)
3949 int af;
3950 char* packed;
3951 int len;
3952 const char* retval;
3953 #ifdef ENABLE_IPV6
3954 char ip[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) + 1];
3955 #else
3956 char ip[INET_ADDRSTRLEN + 1];
3957 #endif
3959 /* Guarantee NUL-termination for PyString_FromString() below */
3960 memset((void *) &ip[0], '\0', sizeof(ip));
3962 if (!PyArg_ParseTuple(args, "is#:inet_ntop", &af, &packed, &len)) {
3963 return NULL;
3966 if (af == AF_INET) {
3967 if (len != sizeof(struct in_addr)) {
3968 PyErr_SetString(PyExc_ValueError,
3969 "invalid length of packed IP address string");
3970 return NULL;
3972 #ifdef ENABLE_IPV6
3973 } else if (af == AF_INET6) {
3974 if (len != sizeof(struct in6_addr)) {
3975 PyErr_SetString(PyExc_ValueError,
3976 "invalid length of packed IP address string");
3977 return NULL;
3979 #endif
3980 } else {
3981 PyErr_Format(PyExc_ValueError,
3982 "unknown address family %d", af);
3983 return NULL;
3986 retval = inet_ntop(af, packed, ip, sizeof(ip));
3987 if (!retval) {
3988 PyErr_SetFromErrno(socket_error);
3989 return NULL;
3990 } else {
3991 return PyString_FromString(retval);
3994 /* NOTREACHED */
3995 PyErr_SetString(PyExc_RuntimeError, "invalid handling of inet_ntop");
3996 return NULL;
3999 #endif /* HAVE_INET_PTON */
4001 /* Python interface to getaddrinfo(host, port). */
4003 /*ARGSUSED*/
4004 static PyObject *
4005 socket_getaddrinfo(PyObject *self, PyObject *args)
4007 struct addrinfo hints, *res;
4008 struct addrinfo *res0 = NULL;
4009 PyObject *hobj = NULL;
4010 PyObject *pobj = (PyObject *)NULL;
4011 char pbuf[30];
4012 char *hptr, *pptr;
4013 int family, socktype, protocol, flags;
4014 int error;
4015 PyObject *all = (PyObject *)NULL;
4016 PyObject *single = (PyObject *)NULL;
4017 PyObject *idna = NULL;
4019 family = socktype = protocol = flags = 0;
4020 family = AF_UNSPEC;
4021 if (!PyArg_ParseTuple(args, "OO|iiii:getaddrinfo",
4022 &hobj, &pobj, &family, &socktype,
4023 &protocol, &flags)) {
4024 return NULL;
4026 if (hobj == Py_None) {
4027 hptr = NULL;
4028 } else if (PyUnicode_Check(hobj)) {
4029 idna = PyObject_CallMethod(hobj, "encode", "s", "idna");
4030 if (!idna)
4031 return NULL;
4032 hptr = PyString_AsString(idna);
4033 } else if (PyString_Check(hobj)) {
4034 hptr = PyString_AsString(hobj);
4035 } else {
4036 PyErr_SetString(PyExc_TypeError,
4037 "getaddrinfo() argument 1 must be string or None");
4038 return NULL;
4040 if (PyInt_Check(pobj)) {
4041 PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", PyInt_AsLong(pobj));
4042 pptr = pbuf;
4043 } else if (PyString_Check(pobj)) {
4044 pptr = PyString_AsString(pobj);
4045 } else if (pobj == Py_None) {
4046 pptr = (char *)NULL;
4047 } else {
4048 PyErr_SetString(socket_error, "Int or String expected");
4049 goto err;
4051 memset(&hints, 0, sizeof(hints));
4052 hints.ai_family = family;
4053 hints.ai_socktype = socktype;
4054 hints.ai_protocol = protocol;
4055 hints.ai_flags = flags;
4056 Py_BEGIN_ALLOW_THREADS
4057 ACQUIRE_GETADDRINFO_LOCK
4058 error = getaddrinfo(hptr, pptr, &hints, &res0);
4059 Py_END_ALLOW_THREADS
4060 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
4061 if (error) {
4062 set_gaierror(error);
4063 goto err;
4066 if ((all = PyList_New(0)) == NULL)
4067 goto err;
4068 for (res = res0; res; res = res->ai_next) {
4069 PyObject *addr =
4070 makesockaddr(-1, res->ai_addr, res->ai_addrlen, protocol);
4071 if (addr == NULL)
4072 goto err;
4073 single = Py_BuildValue("iiisO", res->ai_family,
4074 res->ai_socktype, res->ai_protocol,
4075 res->ai_canonname ? res->ai_canonname : "",
4076 addr);
4077 Py_DECREF(addr);
4078 if (single == NULL)
4079 goto err;
4081 if (PyList_Append(all, single))
4082 goto err;
4083 Py_XDECREF(single);
4085 Py_XDECREF(idna);
4086 if (res0)
4087 freeaddrinfo(res0);
4088 return all;
4089 err:
4090 Py_XDECREF(single);
4091 Py_XDECREF(all);
4092 Py_XDECREF(idna);
4093 if (res0)
4094 freeaddrinfo(res0);
4095 return (PyObject *)NULL;
4098 PyDoc_STRVAR(getaddrinfo_doc,
4099 "getaddrinfo(host, port [, family, socktype, proto, flags])\n\
4100 -> list of (family, socktype, proto, canonname, sockaddr)\n\
4102 Resolve host and port into addrinfo struct.");
4104 /* Python interface to getnameinfo(sa, flags). */
4106 /*ARGSUSED*/
4107 static PyObject *
4108 socket_getnameinfo(PyObject *self, PyObject *args)
4110 PyObject *sa = (PyObject *)NULL;
4111 int flags;
4112 char *hostp;
4113 int port, flowinfo, scope_id;
4114 char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
4115 struct addrinfo hints, *res = NULL;
4116 int error;
4117 PyObject *ret = (PyObject *)NULL;
4119 flags = flowinfo = scope_id = 0;
4120 if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags))
4121 return NULL;
4122 if (!PyTuple_Check(sa)) {
4123 PyErr_SetString(PyExc_TypeError,
4124 "getnameinfo() argument 1 must be a tuple");
4125 return NULL;
4127 if (!PyArg_ParseTuple(sa, "si|ii",
4128 &hostp, &port, &flowinfo, &scope_id))
4129 return NULL;
4130 PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port);
4131 memset(&hints, 0, sizeof(hints));
4132 hints.ai_family = AF_UNSPEC;
4133 hints.ai_socktype = SOCK_DGRAM; /* make numeric port happy */
4134 Py_BEGIN_ALLOW_THREADS
4135 ACQUIRE_GETADDRINFO_LOCK
4136 error = getaddrinfo(hostp, pbuf, &hints, &res);
4137 Py_END_ALLOW_THREADS
4138 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
4139 if (error) {
4140 set_gaierror(error);
4141 goto fail;
4143 if (res->ai_next) {
4144 PyErr_SetString(socket_error,
4145 "sockaddr resolved to multiple addresses");
4146 goto fail;
4148 switch (res->ai_family) {
4149 case AF_INET:
4151 if (PyTuple_GET_SIZE(sa) != 2) {
4152 PyErr_SetString(socket_error,
4153 "IPv4 sockaddr must be 2 tuple");
4154 goto fail;
4156 break;
4158 #ifdef ENABLE_IPV6
4159 case AF_INET6:
4161 struct sockaddr_in6 *sin6;
4162 sin6 = (struct sockaddr_in6 *)res->ai_addr;
4163 sin6->sin6_flowinfo = flowinfo;
4164 sin6->sin6_scope_id = scope_id;
4165 break;
4167 #endif
4169 error = getnameinfo(res->ai_addr, res->ai_addrlen,
4170 hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags);
4171 if (error) {
4172 set_gaierror(error);
4173 goto fail;
4175 ret = Py_BuildValue("ss", hbuf, pbuf);
4177 fail:
4178 if (res)
4179 freeaddrinfo(res);
4180 return ret;
4183 PyDoc_STRVAR(getnameinfo_doc,
4184 "getnameinfo(sockaddr, flags) --> (host, port)\n\
4186 Get host and port for a sockaddr.");
4189 /* Python API to getting and setting the default timeout value. */
4191 static PyObject *
4192 socket_getdefaulttimeout(PyObject *self)
4194 if (defaulttimeout < 0.0) {
4195 Py_INCREF(Py_None);
4196 return Py_None;
4198 else
4199 return PyFloat_FromDouble(defaulttimeout);
4202 PyDoc_STRVAR(getdefaulttimeout_doc,
4203 "getdefaulttimeout() -> timeout\n\
4205 Returns the default timeout in floating seconds for new socket objects.\n\
4206 A value of None indicates that new socket objects have no timeout.\n\
4207 When the socket module is first imported, the default is None.");
4209 static PyObject *
4210 socket_setdefaulttimeout(PyObject *self, PyObject *arg)
4212 double timeout;
4214 if (arg == Py_None)
4215 timeout = -1.0;
4216 else {
4217 timeout = PyFloat_AsDouble(arg);
4218 if (timeout < 0.0) {
4219 if (!PyErr_Occurred())
4220 PyErr_SetString(PyExc_ValueError,
4221 "Timeout value out of range");
4222 return NULL;
4226 defaulttimeout = timeout;
4228 Py_INCREF(Py_None);
4229 return Py_None;
4232 PyDoc_STRVAR(setdefaulttimeout_doc,
4233 "setdefaulttimeout(timeout)\n\
4235 Set the default timeout in floating seconds for new socket objects.\n\
4236 A value of None indicates that new socket objects have no timeout.\n\
4237 When the socket module is first imported, the default is None.");
4240 /* List of functions exported by this module. */
4242 static PyMethodDef socket_methods[] = {
4243 {"gethostbyname", socket_gethostbyname,
4244 METH_VARARGS, gethostbyname_doc},
4245 {"gethostbyname_ex", socket_gethostbyname_ex,
4246 METH_VARARGS, ghbn_ex_doc},
4247 {"gethostbyaddr", socket_gethostbyaddr,
4248 METH_VARARGS, gethostbyaddr_doc},
4249 {"gethostname", socket_gethostname,
4250 METH_NOARGS, gethostname_doc},
4251 {"getservbyname", socket_getservbyname,
4252 METH_VARARGS, getservbyname_doc},
4253 {"getservbyport", socket_getservbyport,
4254 METH_VARARGS, getservbyport_doc},
4255 {"getprotobyname", socket_getprotobyname,
4256 METH_VARARGS, getprotobyname_doc},
4257 #ifndef NO_DUP
4258 {"fromfd", socket_fromfd,
4259 METH_VARARGS, fromfd_doc},
4260 #endif
4261 #ifdef HAVE_SOCKETPAIR
4262 {"socketpair", socket_socketpair,
4263 METH_VARARGS, socketpair_doc},
4264 #endif
4265 {"ntohs", socket_ntohs,
4266 METH_VARARGS, ntohs_doc},
4267 {"ntohl", socket_ntohl,
4268 METH_O, ntohl_doc},
4269 {"htons", socket_htons,
4270 METH_VARARGS, htons_doc},
4271 {"htonl", socket_htonl,
4272 METH_O, htonl_doc},
4273 {"inet_aton", socket_inet_aton,
4274 METH_VARARGS, inet_aton_doc},
4275 {"inet_ntoa", socket_inet_ntoa,
4276 METH_VARARGS, inet_ntoa_doc},
4277 #ifdef HAVE_INET_PTON
4278 {"inet_pton", socket_inet_pton,
4279 METH_VARARGS, inet_pton_doc},
4280 {"inet_ntop", socket_inet_ntop,
4281 METH_VARARGS, inet_ntop_doc},
4282 #endif
4283 {"getaddrinfo", socket_getaddrinfo,
4284 METH_VARARGS, getaddrinfo_doc},
4285 {"getnameinfo", socket_getnameinfo,
4286 METH_VARARGS, getnameinfo_doc},
4287 {"getdefaulttimeout", (PyCFunction)socket_getdefaulttimeout,
4288 METH_NOARGS, getdefaulttimeout_doc},
4289 {"setdefaulttimeout", socket_setdefaulttimeout,
4290 METH_O, setdefaulttimeout_doc},
4291 {NULL, NULL} /* Sentinel */
4295 #ifdef RISCOS
4296 #define OS_INIT_DEFINED
4298 static int
4299 os_init(void)
4301 _kernel_swi_regs r;
4303 r.r[0] = 0;
4304 _kernel_swi(0x43380, &r, &r);
4305 taskwindow = r.r[0];
4307 return 1;
4310 #endif /* RISCOS */
4313 #ifdef MS_WINDOWS
4314 #define OS_INIT_DEFINED
4316 /* Additional initialization and cleanup for Windows */
4318 static void
4319 os_cleanup(void)
4321 WSACleanup();
4324 static int
4325 os_init(void)
4327 WSADATA WSAData;
4328 int ret;
4329 char buf[100];
4330 ret = WSAStartup(0x0101, &WSAData);
4331 switch (ret) {
4332 case 0: /* No error */
4333 Py_AtExit(os_cleanup);
4334 return 1; /* Success */
4335 case WSASYSNOTREADY:
4336 PyErr_SetString(PyExc_ImportError,
4337 "WSAStartup failed: network not ready");
4338 break;
4339 case WSAVERNOTSUPPORTED:
4340 case WSAEINVAL:
4341 PyErr_SetString(
4342 PyExc_ImportError,
4343 "WSAStartup failed: requested version not supported");
4344 break;
4345 default:
4346 PyOS_snprintf(buf, sizeof(buf),
4347 "WSAStartup failed: error code %d", ret);
4348 PyErr_SetString(PyExc_ImportError, buf);
4349 break;
4351 return 0; /* Failure */
4354 #endif /* MS_WINDOWS */
4357 #ifdef PYOS_OS2
4358 #define OS_INIT_DEFINED
4360 /* Additional initialization for OS/2 */
4362 static int
4363 os_init(void)
4365 #ifndef PYCC_GCC
4366 char reason[64];
4367 int rc = sock_init();
4369 if (rc == 0) {
4370 return 1; /* Success */
4373 PyOS_snprintf(reason, sizeof(reason),
4374 "OS/2 TCP/IP Error# %d", sock_errno());
4375 PyErr_SetString(PyExc_ImportError, reason);
4377 return 0; /* Failure */
4378 #else
4379 /* No need to initialise sockets with GCC/EMX */
4380 return 1; /* Success */
4381 #endif
4384 #endif /* PYOS_OS2 */
4387 #ifndef OS_INIT_DEFINED
4388 static int
4389 os_init(void)
4391 return 1; /* Success */
4393 #endif
4396 /* C API table - always add new things to the end for binary
4397 compatibility. */
4398 static
4399 PySocketModule_APIObject PySocketModuleAPI =
4401 &sock_type,
4402 NULL
4406 /* Initialize the _socket module.
4408 This module is actually called "_socket", and there's a wrapper
4409 "socket.py" which implements some additional functionality. On some
4410 platforms (e.g. Windows and OS/2), socket.py also implements a
4411 wrapper for the socket type that provides missing functionality such
4412 as makefile(), dup() and fromfd(). The import of "_socket" may fail
4413 with an ImportError exception if os-specific initialization fails.
4414 On Windows, this does WINSOCK initialization. When WINSOCK is
4415 initialized succesfully, a call to WSACleanup() is scheduled to be
4416 made at exit time.
4419 PyDoc_STRVAR(socket_doc,
4420 "Implementation module for socket operations.\n\
4422 See the socket module for documentation.");
4424 PyMODINIT_FUNC
4425 init_socket(void)
4427 PyObject *m, *has_ipv6;
4429 if (!os_init())
4430 return;
4432 Py_TYPE(&sock_type) = &PyType_Type;
4433 m = Py_InitModule3(PySocket_MODULE_NAME,
4434 socket_methods,
4435 socket_doc);
4436 if (m == NULL)
4437 return;
4439 socket_error = PyErr_NewException("socket.error",
4440 PyExc_IOError, NULL);
4441 if (socket_error == NULL)
4442 return;
4443 PySocketModuleAPI.error = socket_error;
4444 Py_INCREF(socket_error);
4445 PyModule_AddObject(m, "error", socket_error);
4446 socket_herror = PyErr_NewException("socket.herror",
4447 socket_error, NULL);
4448 if (socket_herror == NULL)
4449 return;
4450 Py_INCREF(socket_herror);
4451 PyModule_AddObject(m, "herror", socket_herror);
4452 socket_gaierror = PyErr_NewException("socket.gaierror", socket_error,
4453 NULL);
4454 if (socket_gaierror == NULL)
4455 return;
4456 Py_INCREF(socket_gaierror);
4457 PyModule_AddObject(m, "gaierror", socket_gaierror);
4458 socket_timeout = PyErr_NewException("socket.timeout",
4459 socket_error, NULL);
4460 if (socket_timeout == NULL)
4461 return;
4462 Py_INCREF(socket_timeout);
4463 PyModule_AddObject(m, "timeout", socket_timeout);
4464 Py_INCREF((PyObject *)&sock_type);
4465 if (PyModule_AddObject(m, "SocketType",
4466 (PyObject *)&sock_type) != 0)
4467 return;
4468 Py_INCREF((PyObject *)&sock_type);
4469 if (PyModule_AddObject(m, "socket",
4470 (PyObject *)&sock_type) != 0)
4471 return;
4473 #ifdef ENABLE_IPV6
4474 has_ipv6 = Py_True;
4475 #else
4476 has_ipv6 = Py_False;
4477 #endif
4478 Py_INCREF(has_ipv6);
4479 PyModule_AddObject(m, "has_ipv6", has_ipv6);
4481 /* Export C API */
4482 if (PyModule_AddObject(m, PySocket_CAPI_NAME,
4483 PyCObject_FromVoidPtr((void *)&PySocketModuleAPI, NULL)
4484 ) != 0)
4485 return;
4487 /* Address families (we only support AF_INET and AF_UNIX) */
4488 #ifdef AF_UNSPEC
4489 PyModule_AddIntConstant(m, "AF_UNSPEC", AF_UNSPEC);
4490 #endif
4491 PyModule_AddIntConstant(m, "AF_INET", AF_INET);
4492 #ifdef AF_INET6
4493 PyModule_AddIntConstant(m, "AF_INET6", AF_INET6);
4494 #endif /* AF_INET6 */
4495 #if defined(AF_UNIX)
4496 PyModule_AddIntConstant(m, "AF_UNIX", AF_UNIX);
4497 #endif /* AF_UNIX */
4498 #ifdef AF_AX25
4499 /* Amateur Radio AX.25 */
4500 PyModule_AddIntConstant(m, "AF_AX25", AF_AX25);
4501 #endif
4502 #ifdef AF_IPX
4503 PyModule_AddIntConstant(m, "AF_IPX", AF_IPX); /* Novell IPX */
4504 #endif
4505 #ifdef AF_APPLETALK
4506 /* Appletalk DDP */
4507 PyModule_AddIntConstant(m, "AF_APPLETALK", AF_APPLETALK);
4508 #endif
4509 #ifdef AF_NETROM
4510 /* Amateur radio NetROM */
4511 PyModule_AddIntConstant(m, "AF_NETROM", AF_NETROM);
4512 #endif
4513 #ifdef AF_BRIDGE
4514 /* Multiprotocol bridge */
4515 PyModule_AddIntConstant(m, "AF_BRIDGE", AF_BRIDGE);
4516 #endif
4517 #ifdef AF_ATMPVC
4518 /* ATM PVCs */
4519 PyModule_AddIntConstant(m, "AF_ATMPVC", AF_ATMPVC);
4520 #endif
4521 #ifdef AF_AAL5
4522 /* Reserved for Werner's ATM */
4523 PyModule_AddIntConstant(m, "AF_AAL5", AF_AAL5);
4524 #endif
4525 #ifdef AF_X25
4526 /* Reserved for X.25 project */
4527 PyModule_AddIntConstant(m, "AF_X25", AF_X25);
4528 #endif
4529 #ifdef AF_INET6
4530 PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); /* IP version 6 */
4531 #endif
4532 #ifdef AF_ROSE
4533 /* Amateur Radio X.25 PLP */
4534 PyModule_AddIntConstant(m, "AF_ROSE", AF_ROSE);
4535 #endif
4536 #ifdef AF_DECnet
4537 /* Reserved for DECnet project */
4538 PyModule_AddIntConstant(m, "AF_DECnet", AF_DECnet);
4539 #endif
4540 #ifdef AF_NETBEUI
4541 /* Reserved for 802.2LLC project */
4542 PyModule_AddIntConstant(m, "AF_NETBEUI", AF_NETBEUI);
4543 #endif
4544 #ifdef AF_SECURITY
4545 /* Security callback pseudo AF */
4546 PyModule_AddIntConstant(m, "AF_SECURITY", AF_SECURITY);
4547 #endif
4548 #ifdef AF_KEY
4549 /* PF_KEY key management API */
4550 PyModule_AddIntConstant(m, "AF_KEY", AF_KEY);
4551 #endif
4552 #ifdef AF_NETLINK
4553 /* */
4554 PyModule_AddIntConstant(m, "AF_NETLINK", AF_NETLINK);
4555 PyModule_AddIntConstant(m, "NETLINK_ROUTE", NETLINK_ROUTE);
4556 #ifdef NETLINK_SKIP
4557 PyModule_AddIntConstant(m, "NETLINK_SKIP", NETLINK_SKIP);
4558 #endif
4559 #ifdef NETLINK_W1
4560 PyModule_AddIntConstant(m, "NETLINK_W1", NETLINK_W1);
4561 #endif
4562 PyModule_AddIntConstant(m, "NETLINK_USERSOCK", NETLINK_USERSOCK);
4563 PyModule_AddIntConstant(m, "NETLINK_FIREWALL", NETLINK_FIREWALL);
4564 #ifdef NETLINK_TCPDIAG
4565 PyModule_AddIntConstant(m, "NETLINK_TCPDIAG", NETLINK_TCPDIAG);
4566 #endif
4567 #ifdef NETLINK_NFLOG
4568 PyModule_AddIntConstant(m, "NETLINK_NFLOG", NETLINK_NFLOG);
4569 #endif
4570 #ifdef NETLINK_XFRM
4571 PyModule_AddIntConstant(m, "NETLINK_XFRM", NETLINK_XFRM);
4572 #endif
4573 #ifdef NETLINK_ARPD
4574 PyModule_AddIntConstant(m, "NETLINK_ARPD", NETLINK_ARPD);
4575 #endif
4576 #ifdef NETLINK_ROUTE6
4577 PyModule_AddIntConstant(m, "NETLINK_ROUTE6", NETLINK_ROUTE6);
4578 #endif
4579 PyModule_AddIntConstant(m, "NETLINK_IP6_FW", NETLINK_IP6_FW);
4580 #ifdef NETLINK_DNRTMSG
4581 PyModule_AddIntConstant(m, "NETLINK_DNRTMSG", NETLINK_DNRTMSG);
4582 #endif
4583 #ifdef NETLINK_TAPBASE
4584 PyModule_AddIntConstant(m, "NETLINK_TAPBASE", NETLINK_TAPBASE);
4585 #endif
4586 #endif /* AF_NETLINK */
4587 #ifdef AF_ROUTE
4588 /* Alias to emulate 4.4BSD */
4589 PyModule_AddIntConstant(m, "AF_ROUTE", AF_ROUTE);
4590 #endif
4591 #ifdef AF_ASH
4592 /* Ash */
4593 PyModule_AddIntConstant(m, "AF_ASH", AF_ASH);
4594 #endif
4595 #ifdef AF_ECONET
4596 /* Acorn Econet */
4597 PyModule_AddIntConstant(m, "AF_ECONET", AF_ECONET);
4598 #endif
4599 #ifdef AF_ATMSVC
4600 /* ATM SVCs */
4601 PyModule_AddIntConstant(m, "AF_ATMSVC", AF_ATMSVC);
4602 #endif
4603 #ifdef AF_SNA
4604 /* Linux SNA Project (nutters!) */
4605 PyModule_AddIntConstant(m, "AF_SNA", AF_SNA);
4606 #endif
4607 #ifdef AF_IRDA
4608 /* IRDA sockets */
4609 PyModule_AddIntConstant(m, "AF_IRDA", AF_IRDA);
4610 #endif
4611 #ifdef AF_PPPOX
4612 /* PPPoX sockets */
4613 PyModule_AddIntConstant(m, "AF_PPPOX", AF_PPPOX);
4614 #endif
4615 #ifdef AF_WANPIPE
4616 /* Wanpipe API Sockets */
4617 PyModule_AddIntConstant(m, "AF_WANPIPE", AF_WANPIPE);
4618 #endif
4619 #ifdef AF_LLC
4620 /* Linux LLC */
4621 PyModule_AddIntConstant(m, "AF_LLC", AF_LLC);
4622 #endif
4624 #ifdef USE_BLUETOOTH
4625 PyModule_AddIntConstant(m, "AF_BLUETOOTH", AF_BLUETOOTH);
4626 PyModule_AddIntConstant(m, "BTPROTO_L2CAP", BTPROTO_L2CAP);
4627 PyModule_AddIntConstant(m, "BTPROTO_HCI", BTPROTO_HCI);
4628 PyModule_AddIntConstant(m, "SOL_HCI", SOL_HCI);
4629 PyModule_AddIntConstant(m, "HCI_FILTER", HCI_FILTER);
4630 #if !defined(__FreeBSD__)
4631 PyModule_AddIntConstant(m, "HCI_TIME_STAMP", HCI_TIME_STAMP);
4632 PyModule_AddIntConstant(m, "HCI_DATA_DIR", HCI_DATA_DIR);
4633 PyModule_AddIntConstant(m, "BTPROTO_SCO", BTPROTO_SCO);
4634 #endif
4635 PyModule_AddIntConstant(m, "BTPROTO_RFCOMM", BTPROTO_RFCOMM);
4636 PyModule_AddStringConstant(m, "BDADDR_ANY", "00:00:00:00:00:00");
4637 PyModule_AddStringConstant(m, "BDADDR_LOCAL", "00:00:00:FF:FF:FF");
4638 #endif
4640 #ifdef HAVE_NETPACKET_PACKET_H
4641 PyModule_AddIntConstant(m, "AF_PACKET", AF_PACKET);
4642 PyModule_AddIntConstant(m, "PF_PACKET", PF_PACKET);
4643 PyModule_AddIntConstant(m, "PACKET_HOST", PACKET_HOST);
4644 PyModule_AddIntConstant(m, "PACKET_BROADCAST", PACKET_BROADCAST);
4645 PyModule_AddIntConstant(m, "PACKET_MULTICAST", PACKET_MULTICAST);
4646 PyModule_AddIntConstant(m, "PACKET_OTHERHOST", PACKET_OTHERHOST);
4647 PyModule_AddIntConstant(m, "PACKET_OUTGOING", PACKET_OUTGOING);
4648 PyModule_AddIntConstant(m, "PACKET_LOOPBACK", PACKET_LOOPBACK);
4649 PyModule_AddIntConstant(m, "PACKET_FASTROUTE", PACKET_FASTROUTE);
4650 #endif
4652 #ifdef HAVE_LINUX_TIPC_H
4653 PyModule_AddIntConstant(m, "AF_TIPC", AF_TIPC);
4655 /* for addresses */
4656 PyModule_AddIntConstant(m, "TIPC_ADDR_NAMESEQ", TIPC_ADDR_NAMESEQ);
4657 PyModule_AddIntConstant(m, "TIPC_ADDR_NAME", TIPC_ADDR_NAME);
4658 PyModule_AddIntConstant(m, "TIPC_ADDR_ID", TIPC_ADDR_ID);
4660 PyModule_AddIntConstant(m, "TIPC_ZONE_SCOPE", TIPC_ZONE_SCOPE);
4661 PyModule_AddIntConstant(m, "TIPC_CLUSTER_SCOPE", TIPC_CLUSTER_SCOPE);
4662 PyModule_AddIntConstant(m, "TIPC_NODE_SCOPE", TIPC_NODE_SCOPE);
4664 /* for setsockopt() */
4665 PyModule_AddIntConstant(m, "SOL_TIPC", SOL_TIPC);
4666 PyModule_AddIntConstant(m, "TIPC_IMPORTANCE", TIPC_IMPORTANCE);
4667 PyModule_AddIntConstant(m, "TIPC_SRC_DROPPABLE", TIPC_SRC_DROPPABLE);
4668 PyModule_AddIntConstant(m, "TIPC_DEST_DROPPABLE",
4669 TIPC_DEST_DROPPABLE);
4670 PyModule_AddIntConstant(m, "TIPC_CONN_TIMEOUT", TIPC_CONN_TIMEOUT);
4672 PyModule_AddIntConstant(m, "TIPC_LOW_IMPORTANCE",
4673 TIPC_LOW_IMPORTANCE);
4674 PyModule_AddIntConstant(m, "TIPC_MEDIUM_IMPORTANCE",
4675 TIPC_MEDIUM_IMPORTANCE);
4676 PyModule_AddIntConstant(m, "TIPC_HIGH_IMPORTANCE",
4677 TIPC_HIGH_IMPORTANCE);
4678 PyModule_AddIntConstant(m, "TIPC_CRITICAL_IMPORTANCE",
4679 TIPC_CRITICAL_IMPORTANCE);
4681 /* for subscriptions */
4682 PyModule_AddIntConstant(m, "TIPC_SUB_PORTS", TIPC_SUB_PORTS);
4683 PyModule_AddIntConstant(m, "TIPC_SUB_SERVICE", TIPC_SUB_SERVICE);
4684 #ifdef TIPC_SUB_CANCEL
4685 /* doesn't seem to be available everywhere */
4686 PyModule_AddIntConstant(m, "TIPC_SUB_CANCEL", TIPC_SUB_CANCEL);
4687 #endif
4688 PyModule_AddIntConstant(m, "TIPC_WAIT_FOREVER", TIPC_WAIT_FOREVER);
4689 PyModule_AddIntConstant(m, "TIPC_PUBLISHED", TIPC_PUBLISHED);
4690 PyModule_AddIntConstant(m, "TIPC_WITHDRAWN", TIPC_WITHDRAWN);
4691 PyModule_AddIntConstant(m, "TIPC_SUBSCR_TIMEOUT", TIPC_SUBSCR_TIMEOUT);
4692 PyModule_AddIntConstant(m, "TIPC_CFG_SRV", TIPC_CFG_SRV);
4693 PyModule_AddIntConstant(m, "TIPC_TOP_SRV", TIPC_TOP_SRV);
4694 #endif
4696 /* Socket types */
4697 PyModule_AddIntConstant(m, "SOCK_STREAM", SOCK_STREAM);
4698 PyModule_AddIntConstant(m, "SOCK_DGRAM", SOCK_DGRAM);
4699 #ifndef __BEOS__
4700 /* We have incomplete socket support. */
4701 PyModule_AddIntConstant(m, "SOCK_RAW", SOCK_RAW);
4702 PyModule_AddIntConstant(m, "SOCK_SEQPACKET", SOCK_SEQPACKET);
4703 #if defined(SOCK_RDM)
4704 PyModule_AddIntConstant(m, "SOCK_RDM", SOCK_RDM);
4705 #endif
4706 #endif
4708 #ifdef SO_DEBUG
4709 PyModule_AddIntConstant(m, "SO_DEBUG", SO_DEBUG);
4710 #endif
4711 #ifdef SO_ACCEPTCONN
4712 PyModule_AddIntConstant(m, "SO_ACCEPTCONN", SO_ACCEPTCONN);
4713 #endif
4714 #ifdef SO_REUSEADDR
4715 PyModule_AddIntConstant(m, "SO_REUSEADDR", SO_REUSEADDR);
4716 #endif
4717 #ifdef SO_EXCLUSIVEADDRUSE
4718 PyModule_AddIntConstant(m, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE);
4719 #endif
4721 #ifdef SO_KEEPALIVE
4722 PyModule_AddIntConstant(m, "SO_KEEPALIVE", SO_KEEPALIVE);
4723 #endif
4724 #ifdef SO_DONTROUTE
4725 PyModule_AddIntConstant(m, "SO_DONTROUTE", SO_DONTROUTE);
4726 #endif
4727 #ifdef SO_BROADCAST
4728 PyModule_AddIntConstant(m, "SO_BROADCAST", SO_BROADCAST);
4729 #endif
4730 #ifdef SO_USELOOPBACK
4731 PyModule_AddIntConstant(m, "SO_USELOOPBACK", SO_USELOOPBACK);
4732 #endif
4733 #ifdef SO_LINGER
4734 PyModule_AddIntConstant(m, "SO_LINGER", SO_LINGER);
4735 #endif
4736 #ifdef SO_OOBINLINE
4737 PyModule_AddIntConstant(m, "SO_OOBINLINE", SO_OOBINLINE);
4738 #endif
4739 #ifdef SO_REUSEPORT
4740 PyModule_AddIntConstant(m, "SO_REUSEPORT", SO_REUSEPORT);
4741 #endif
4742 #ifdef SO_SNDBUF
4743 PyModule_AddIntConstant(m, "SO_SNDBUF", SO_SNDBUF);
4744 #endif
4745 #ifdef SO_RCVBUF
4746 PyModule_AddIntConstant(m, "SO_RCVBUF", SO_RCVBUF);
4747 #endif
4748 #ifdef SO_SNDLOWAT
4749 PyModule_AddIntConstant(m, "SO_SNDLOWAT", SO_SNDLOWAT);
4750 #endif
4751 #ifdef SO_RCVLOWAT
4752 PyModule_AddIntConstant(m, "SO_RCVLOWAT", SO_RCVLOWAT);
4753 #endif
4754 #ifdef SO_SNDTIMEO
4755 PyModule_AddIntConstant(m, "SO_SNDTIMEO", SO_SNDTIMEO);
4756 #endif
4757 #ifdef SO_RCVTIMEO
4758 PyModule_AddIntConstant(m, "SO_RCVTIMEO", SO_RCVTIMEO);
4759 #endif
4760 #ifdef SO_ERROR
4761 PyModule_AddIntConstant(m, "SO_ERROR", SO_ERROR);
4762 #endif
4763 #ifdef SO_TYPE
4764 PyModule_AddIntConstant(m, "SO_TYPE", SO_TYPE);
4765 #endif
4767 /* Maximum number of connections for "listen" */
4768 #ifdef SOMAXCONN
4769 PyModule_AddIntConstant(m, "SOMAXCONN", SOMAXCONN);
4770 #else
4771 PyModule_AddIntConstant(m, "SOMAXCONN", 5); /* Common value */
4772 #endif
4774 /* Flags for send, recv */
4775 #ifdef MSG_OOB
4776 PyModule_AddIntConstant(m, "MSG_OOB", MSG_OOB);
4777 #endif
4778 #ifdef MSG_PEEK
4779 PyModule_AddIntConstant(m, "MSG_PEEK", MSG_PEEK);
4780 #endif
4781 #ifdef MSG_DONTROUTE
4782 PyModule_AddIntConstant(m, "MSG_DONTROUTE", MSG_DONTROUTE);
4783 #endif
4784 #ifdef MSG_DONTWAIT
4785 PyModule_AddIntConstant(m, "MSG_DONTWAIT", MSG_DONTWAIT);
4786 #endif
4787 #ifdef MSG_EOR
4788 PyModule_AddIntConstant(m, "MSG_EOR", MSG_EOR);
4789 #endif
4790 #ifdef MSG_TRUNC
4791 PyModule_AddIntConstant(m, "MSG_TRUNC", MSG_TRUNC);
4792 #endif
4793 #ifdef MSG_CTRUNC
4794 PyModule_AddIntConstant(m, "MSG_CTRUNC", MSG_CTRUNC);
4795 #endif
4796 #ifdef MSG_WAITALL
4797 PyModule_AddIntConstant(m, "MSG_WAITALL", MSG_WAITALL);
4798 #endif
4799 #ifdef MSG_BTAG
4800 PyModule_AddIntConstant(m, "MSG_BTAG", MSG_BTAG);
4801 #endif
4802 #ifdef MSG_ETAG
4803 PyModule_AddIntConstant(m, "MSG_ETAG", MSG_ETAG);
4804 #endif
4806 /* Protocol level and numbers, usable for [gs]etsockopt */
4807 #ifdef SOL_SOCKET
4808 PyModule_AddIntConstant(m, "SOL_SOCKET", SOL_SOCKET);
4809 #endif
4810 #ifdef SOL_IP
4811 PyModule_AddIntConstant(m, "SOL_IP", SOL_IP);
4812 #else
4813 PyModule_AddIntConstant(m, "SOL_IP", 0);
4814 #endif
4815 #ifdef SOL_IPX
4816 PyModule_AddIntConstant(m, "SOL_IPX", SOL_IPX);
4817 #endif
4818 #ifdef SOL_AX25
4819 PyModule_AddIntConstant(m, "SOL_AX25", SOL_AX25);
4820 #endif
4821 #ifdef SOL_ATALK
4822 PyModule_AddIntConstant(m, "SOL_ATALK", SOL_ATALK);
4823 #endif
4824 #ifdef SOL_NETROM
4825 PyModule_AddIntConstant(m, "SOL_NETROM", SOL_NETROM);
4826 #endif
4827 #ifdef SOL_ROSE
4828 PyModule_AddIntConstant(m, "SOL_ROSE", SOL_ROSE);
4829 #endif
4830 #ifdef SOL_TCP
4831 PyModule_AddIntConstant(m, "SOL_TCP", SOL_TCP);
4832 #else
4833 PyModule_AddIntConstant(m, "SOL_TCP", 6);
4834 #endif
4835 #ifdef SOL_UDP
4836 PyModule_AddIntConstant(m, "SOL_UDP", SOL_UDP);
4837 #else
4838 PyModule_AddIntConstant(m, "SOL_UDP", 17);
4839 #endif
4840 #ifdef IPPROTO_IP
4841 PyModule_AddIntConstant(m, "IPPROTO_IP", IPPROTO_IP);
4842 #else
4843 PyModule_AddIntConstant(m, "IPPROTO_IP", 0);
4844 #endif
4845 #ifdef IPPROTO_HOPOPTS
4846 PyModule_AddIntConstant(m, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS);
4847 #endif
4848 #ifdef IPPROTO_ICMP
4849 PyModule_AddIntConstant(m, "IPPROTO_ICMP", IPPROTO_ICMP);
4850 #else
4851 PyModule_AddIntConstant(m, "IPPROTO_ICMP", 1);
4852 #endif
4853 #ifdef IPPROTO_IGMP
4854 PyModule_AddIntConstant(m, "IPPROTO_IGMP", IPPROTO_IGMP);
4855 #endif
4856 #ifdef IPPROTO_GGP
4857 PyModule_AddIntConstant(m, "IPPROTO_GGP", IPPROTO_GGP);
4858 #endif
4859 #ifdef IPPROTO_IPV4
4860 PyModule_AddIntConstant(m, "IPPROTO_IPV4", IPPROTO_IPV4);
4861 #endif
4862 #ifdef IPPROTO_IPV6
4863 PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
4864 #endif
4865 #ifdef IPPROTO_IPIP
4866 PyModule_AddIntConstant(m, "IPPROTO_IPIP", IPPROTO_IPIP);
4867 #endif
4868 #ifdef IPPROTO_TCP
4869 PyModule_AddIntConstant(m, "IPPROTO_TCP", IPPROTO_TCP);
4870 #else
4871 PyModule_AddIntConstant(m, "IPPROTO_TCP", 6);
4872 #endif
4873 #ifdef IPPROTO_EGP
4874 PyModule_AddIntConstant(m, "IPPROTO_EGP", IPPROTO_EGP);
4875 #endif
4876 #ifdef IPPROTO_PUP
4877 PyModule_AddIntConstant(m, "IPPROTO_PUP", IPPROTO_PUP);
4878 #endif
4879 #ifdef IPPROTO_UDP
4880 PyModule_AddIntConstant(m, "IPPROTO_UDP", IPPROTO_UDP);
4881 #else
4882 PyModule_AddIntConstant(m, "IPPROTO_UDP", 17);
4883 #endif
4884 #ifdef IPPROTO_IDP
4885 PyModule_AddIntConstant(m, "IPPROTO_IDP", IPPROTO_IDP);
4886 #endif
4887 #ifdef IPPROTO_HELLO
4888 PyModule_AddIntConstant(m, "IPPROTO_HELLO", IPPROTO_HELLO);
4889 #endif
4890 #ifdef IPPROTO_ND
4891 PyModule_AddIntConstant(m, "IPPROTO_ND", IPPROTO_ND);
4892 #endif
4893 #ifdef IPPROTO_TP
4894 PyModule_AddIntConstant(m, "IPPROTO_TP", IPPROTO_TP);
4895 #endif
4896 #ifdef IPPROTO_IPV6
4897 PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
4898 #endif
4899 #ifdef IPPROTO_ROUTING
4900 PyModule_AddIntConstant(m, "IPPROTO_ROUTING", IPPROTO_ROUTING);
4901 #endif
4902 #ifdef IPPROTO_FRAGMENT
4903 PyModule_AddIntConstant(m, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT);
4904 #endif
4905 #ifdef IPPROTO_RSVP
4906 PyModule_AddIntConstant(m, "IPPROTO_RSVP", IPPROTO_RSVP);
4907 #endif
4908 #ifdef IPPROTO_GRE
4909 PyModule_AddIntConstant(m, "IPPROTO_GRE", IPPROTO_GRE);
4910 #endif
4911 #ifdef IPPROTO_ESP
4912 PyModule_AddIntConstant(m, "IPPROTO_ESP", IPPROTO_ESP);
4913 #endif
4914 #ifdef IPPROTO_AH
4915 PyModule_AddIntConstant(m, "IPPROTO_AH", IPPROTO_AH);
4916 #endif
4917 #ifdef IPPROTO_MOBILE
4918 PyModule_AddIntConstant(m, "IPPROTO_MOBILE", IPPROTO_MOBILE);
4919 #endif
4920 #ifdef IPPROTO_ICMPV6
4921 PyModule_AddIntConstant(m, "IPPROTO_ICMPV6", IPPROTO_ICMPV6);
4922 #endif
4923 #ifdef IPPROTO_NONE
4924 PyModule_AddIntConstant(m, "IPPROTO_NONE", IPPROTO_NONE);
4925 #endif
4926 #ifdef IPPROTO_DSTOPTS
4927 PyModule_AddIntConstant(m, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS);
4928 #endif
4929 #ifdef IPPROTO_XTP
4930 PyModule_AddIntConstant(m, "IPPROTO_XTP", IPPROTO_XTP);
4931 #endif
4932 #ifdef IPPROTO_EON
4933 PyModule_AddIntConstant(m, "IPPROTO_EON", IPPROTO_EON);
4934 #endif
4935 #ifdef IPPROTO_PIM
4936 PyModule_AddIntConstant(m, "IPPROTO_PIM", IPPROTO_PIM);
4937 #endif
4938 #ifdef IPPROTO_IPCOMP
4939 PyModule_AddIntConstant(m, "IPPROTO_IPCOMP", IPPROTO_IPCOMP);
4940 #endif
4941 #ifdef IPPROTO_VRRP
4942 PyModule_AddIntConstant(m, "IPPROTO_VRRP", IPPROTO_VRRP);
4943 #endif
4944 #ifdef IPPROTO_BIP
4945 PyModule_AddIntConstant(m, "IPPROTO_BIP", IPPROTO_BIP);
4946 #endif
4947 /**/
4948 #ifdef IPPROTO_RAW
4949 PyModule_AddIntConstant(m, "IPPROTO_RAW", IPPROTO_RAW);
4950 #else
4951 PyModule_AddIntConstant(m, "IPPROTO_RAW", 255);
4952 #endif
4953 #ifdef IPPROTO_MAX
4954 PyModule_AddIntConstant(m, "IPPROTO_MAX", IPPROTO_MAX);
4955 #endif
4957 /* Some port configuration */
4958 #ifdef IPPORT_RESERVED
4959 PyModule_AddIntConstant(m, "IPPORT_RESERVED", IPPORT_RESERVED);
4960 #else
4961 PyModule_AddIntConstant(m, "IPPORT_RESERVED", 1024);
4962 #endif
4963 #ifdef IPPORT_USERRESERVED
4964 PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", IPPORT_USERRESERVED);
4965 #else
4966 PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", 5000);
4967 #endif
4969 /* Some reserved IP v.4 addresses */
4970 #ifdef INADDR_ANY
4971 PyModule_AddIntConstant(m, "INADDR_ANY", INADDR_ANY);
4972 #else
4973 PyModule_AddIntConstant(m, "INADDR_ANY", 0x00000000);
4974 #endif
4975 #ifdef INADDR_BROADCAST
4976 PyModule_AddIntConstant(m, "INADDR_BROADCAST", INADDR_BROADCAST);
4977 #else
4978 PyModule_AddIntConstant(m, "INADDR_BROADCAST", 0xffffffff);
4979 #endif
4980 #ifdef INADDR_LOOPBACK
4981 PyModule_AddIntConstant(m, "INADDR_LOOPBACK", INADDR_LOOPBACK);
4982 #else
4983 PyModule_AddIntConstant(m, "INADDR_LOOPBACK", 0x7F000001);
4984 #endif
4985 #ifdef INADDR_UNSPEC_GROUP
4986 PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
4987 #else
4988 PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", 0xe0000000);
4989 #endif
4990 #ifdef INADDR_ALLHOSTS_GROUP
4991 PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP",
4992 INADDR_ALLHOSTS_GROUP);
4993 #else
4994 PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
4995 #endif
4996 #ifdef INADDR_MAX_LOCAL_GROUP
4997 PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP",
4998 INADDR_MAX_LOCAL_GROUP);
4999 #else
5000 PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
5001 #endif
5002 #ifdef INADDR_NONE
5003 PyModule_AddIntConstant(m, "INADDR_NONE", INADDR_NONE);
5004 #else
5005 PyModule_AddIntConstant(m, "INADDR_NONE", 0xffffffff);
5006 #endif
5008 /* IPv4 [gs]etsockopt options */
5009 #ifdef IP_OPTIONS
5010 PyModule_AddIntConstant(m, "IP_OPTIONS", IP_OPTIONS);
5011 #endif
5012 #ifdef IP_HDRINCL
5013 PyModule_AddIntConstant(m, "IP_HDRINCL", IP_HDRINCL);
5014 #endif
5015 #ifdef IP_TOS
5016 PyModule_AddIntConstant(m, "IP_TOS", IP_TOS);
5017 #endif
5018 #ifdef IP_TTL
5019 PyModule_AddIntConstant(m, "IP_TTL", IP_TTL);
5020 #endif
5021 #ifdef IP_RECVOPTS
5022 PyModule_AddIntConstant(m, "IP_RECVOPTS", IP_RECVOPTS);
5023 #endif
5024 #ifdef IP_RECVRETOPTS
5025 PyModule_AddIntConstant(m, "IP_RECVRETOPTS", IP_RECVRETOPTS);
5026 #endif
5027 #ifdef IP_RECVDSTADDR
5028 PyModule_AddIntConstant(m, "IP_RECVDSTADDR", IP_RECVDSTADDR);
5029 #endif
5030 #ifdef IP_RETOPTS
5031 PyModule_AddIntConstant(m, "IP_RETOPTS", IP_RETOPTS);
5032 #endif
5033 #ifdef IP_MULTICAST_IF
5034 PyModule_AddIntConstant(m, "IP_MULTICAST_IF", IP_MULTICAST_IF);
5035 #endif
5036 #ifdef IP_MULTICAST_TTL
5037 PyModule_AddIntConstant(m, "IP_MULTICAST_TTL", IP_MULTICAST_TTL);
5038 #endif
5039 #ifdef IP_MULTICAST_LOOP
5040 PyModule_AddIntConstant(m, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
5041 #endif
5042 #ifdef IP_ADD_MEMBERSHIP
5043 PyModule_AddIntConstant(m, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
5044 #endif
5045 #ifdef IP_DROP_MEMBERSHIP
5046 PyModule_AddIntConstant(m, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
5047 #endif
5048 #ifdef IP_DEFAULT_MULTICAST_TTL
5049 PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_TTL",
5050 IP_DEFAULT_MULTICAST_TTL);
5051 #endif
5052 #ifdef IP_DEFAULT_MULTICAST_LOOP
5053 PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_LOOP",
5054 IP_DEFAULT_MULTICAST_LOOP);
5055 #endif
5056 #ifdef IP_MAX_MEMBERSHIPS
5057 PyModule_AddIntConstant(m, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS);
5058 #endif
5060 /* IPv6 [gs]etsockopt options, defined in RFC2553 */
5061 #ifdef IPV6_JOIN_GROUP
5062 PyModule_AddIntConstant(m, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP);
5063 #endif
5064 #ifdef IPV6_LEAVE_GROUP
5065 PyModule_AddIntConstant(m, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP);
5066 #endif
5067 #ifdef IPV6_MULTICAST_HOPS
5068 PyModule_AddIntConstant(m, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS);
5069 #endif
5070 #ifdef IPV6_MULTICAST_IF
5071 PyModule_AddIntConstant(m, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF);
5072 #endif
5073 #ifdef IPV6_MULTICAST_LOOP
5074 PyModule_AddIntConstant(m, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP);
5075 #endif
5076 #ifdef IPV6_UNICAST_HOPS
5077 PyModule_AddIntConstant(m, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS);
5078 #endif
5079 /* Additional IPV6 socket options, defined in RFC 3493 */
5080 #ifdef IPV6_V6ONLY
5081 PyModule_AddIntConstant(m, "IPV6_V6ONLY", IPV6_V6ONLY);
5082 #endif
5083 /* Advanced IPV6 socket options, from RFC 3542 */
5084 #ifdef IPV6_CHECKSUM
5085 PyModule_AddIntConstant(m, "IPV6_CHECKSUM", IPV6_CHECKSUM);
5086 #endif
5087 #ifdef IPV6_DONTFRAG
5088 PyModule_AddIntConstant(m, "IPV6_DONTFRAG", IPV6_DONTFRAG);
5089 #endif
5090 #ifdef IPV6_DSTOPTS
5091 PyModule_AddIntConstant(m, "IPV6_DSTOPTS", IPV6_DSTOPTS);
5092 #endif
5093 #ifdef IPV6_HOPLIMIT
5094 PyModule_AddIntConstant(m, "IPV6_HOPLIMIT", IPV6_HOPLIMIT);
5095 #endif
5096 #ifdef IPV6_HOPOPTS
5097 PyModule_AddIntConstant(m, "IPV6_HOPOPTS", IPV6_HOPOPTS);
5098 #endif
5099 #ifdef IPV6_NEXTHOP
5100 PyModule_AddIntConstant(m, "IPV6_NEXTHOP", IPV6_NEXTHOP);
5101 #endif
5102 #ifdef IPV6_PATHMTU
5103 PyModule_AddIntConstant(m, "IPV6_PATHMTU", IPV6_PATHMTU);
5104 #endif
5105 #ifdef IPV6_PKTINFO
5106 PyModule_AddIntConstant(m, "IPV6_PKTINFO", IPV6_PKTINFO);
5107 #endif
5108 #ifdef IPV6_RECVDSTOPTS
5109 PyModule_AddIntConstant(m, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS);
5110 #endif
5111 #ifdef IPV6_RECVHOPLIMIT
5112 PyModule_AddIntConstant(m, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT);
5113 #endif
5114 #ifdef IPV6_RECVHOPOPTS
5115 PyModule_AddIntConstant(m, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS);
5116 #endif
5117 #ifdef IPV6_RECVPKTINFO
5118 PyModule_AddIntConstant(m, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO);
5119 #endif
5120 #ifdef IPV6_RECVRTHDR
5121 PyModule_AddIntConstant(m, "IPV6_RECVRTHDR", IPV6_RECVRTHDR);
5122 #endif
5123 #ifdef IPV6_RECVTCLASS
5124 PyModule_AddIntConstant(m, "IPV6_RECVTCLASS", IPV6_RECVTCLASS);
5125 #endif
5126 #ifdef IPV6_RTHDR
5127 PyModule_AddIntConstant(m, "IPV6_RTHDR", IPV6_RTHDR);
5128 #endif
5129 #ifdef IPV6_RTHDRDSTOPTS
5130 PyModule_AddIntConstant(m, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS);
5131 #endif
5132 #ifdef IPV6_RTHDR_TYPE_0
5133 PyModule_AddIntConstant(m, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0);
5134 #endif
5135 #ifdef IPV6_RECVPATHMTU
5136 PyModule_AddIntConstant(m, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU);
5137 #endif
5138 #ifdef IPV6_TCLASS
5139 PyModule_AddIntConstant(m, "IPV6_TCLASS", IPV6_TCLASS);
5140 #endif
5141 #ifdef IPV6_USE_MIN_MTU
5142 PyModule_AddIntConstant(m, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU);
5143 #endif
5145 /* TCP options */
5146 #ifdef TCP_NODELAY
5147 PyModule_AddIntConstant(m, "TCP_NODELAY", TCP_NODELAY);
5148 #endif
5149 #ifdef TCP_MAXSEG
5150 PyModule_AddIntConstant(m, "TCP_MAXSEG", TCP_MAXSEG);
5151 #endif
5152 #ifdef TCP_CORK
5153 PyModule_AddIntConstant(m, "TCP_CORK", TCP_CORK);
5154 #endif
5155 #ifdef TCP_KEEPIDLE
5156 PyModule_AddIntConstant(m, "TCP_KEEPIDLE", TCP_KEEPIDLE);
5157 #endif
5158 #ifdef TCP_KEEPINTVL
5159 PyModule_AddIntConstant(m, "TCP_KEEPINTVL", TCP_KEEPINTVL);
5160 #endif
5161 #ifdef TCP_KEEPCNT
5162 PyModule_AddIntConstant(m, "TCP_KEEPCNT", TCP_KEEPCNT);
5163 #endif
5164 #ifdef TCP_SYNCNT
5165 PyModule_AddIntConstant(m, "TCP_SYNCNT", TCP_SYNCNT);
5166 #endif
5167 #ifdef TCP_LINGER2
5168 PyModule_AddIntConstant(m, "TCP_LINGER2", TCP_LINGER2);
5169 #endif
5170 #ifdef TCP_DEFER_ACCEPT
5171 PyModule_AddIntConstant(m, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT);
5172 #endif
5173 #ifdef TCP_WINDOW_CLAMP
5174 PyModule_AddIntConstant(m, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP);
5175 #endif
5176 #ifdef TCP_INFO
5177 PyModule_AddIntConstant(m, "TCP_INFO", TCP_INFO);
5178 #endif
5179 #ifdef TCP_QUICKACK
5180 PyModule_AddIntConstant(m, "TCP_QUICKACK", TCP_QUICKACK);
5181 #endif
5184 /* IPX options */
5185 #ifdef IPX_TYPE
5186 PyModule_AddIntConstant(m, "IPX_TYPE", IPX_TYPE);
5187 #endif
5189 /* get{addr,name}info parameters */
5190 #ifdef EAI_ADDRFAMILY
5191 PyModule_AddIntConstant(m, "EAI_ADDRFAMILY", EAI_ADDRFAMILY);
5192 #endif
5193 #ifdef EAI_AGAIN
5194 PyModule_AddIntConstant(m, "EAI_AGAIN", EAI_AGAIN);
5195 #endif
5196 #ifdef EAI_BADFLAGS
5197 PyModule_AddIntConstant(m, "EAI_BADFLAGS", EAI_BADFLAGS);
5198 #endif
5199 #ifdef EAI_FAIL
5200 PyModule_AddIntConstant(m, "EAI_FAIL", EAI_FAIL);
5201 #endif
5202 #ifdef EAI_FAMILY
5203 PyModule_AddIntConstant(m, "EAI_FAMILY", EAI_FAMILY);
5204 #endif
5205 #ifdef EAI_MEMORY
5206 PyModule_AddIntConstant(m, "EAI_MEMORY", EAI_MEMORY);
5207 #endif
5208 #ifdef EAI_NODATA
5209 PyModule_AddIntConstant(m, "EAI_NODATA", EAI_NODATA);
5210 #endif
5211 #ifdef EAI_NONAME
5212 PyModule_AddIntConstant(m, "EAI_NONAME", EAI_NONAME);
5213 #endif
5214 #ifdef EAI_OVERFLOW
5215 PyModule_AddIntConstant(m, "EAI_OVERFLOW", EAI_OVERFLOW);
5216 #endif
5217 #ifdef EAI_SERVICE
5218 PyModule_AddIntConstant(m, "EAI_SERVICE", EAI_SERVICE);
5219 #endif
5220 #ifdef EAI_SOCKTYPE
5221 PyModule_AddIntConstant(m, "EAI_SOCKTYPE", EAI_SOCKTYPE);
5222 #endif
5223 #ifdef EAI_SYSTEM
5224 PyModule_AddIntConstant(m, "EAI_SYSTEM", EAI_SYSTEM);
5225 #endif
5226 #ifdef EAI_BADHINTS
5227 PyModule_AddIntConstant(m, "EAI_BADHINTS", EAI_BADHINTS);
5228 #endif
5229 #ifdef EAI_PROTOCOL
5230 PyModule_AddIntConstant(m, "EAI_PROTOCOL", EAI_PROTOCOL);
5231 #endif
5232 #ifdef EAI_MAX
5233 PyModule_AddIntConstant(m, "EAI_MAX", EAI_MAX);
5234 #endif
5235 #ifdef AI_PASSIVE
5236 PyModule_AddIntConstant(m, "AI_PASSIVE", AI_PASSIVE);
5237 #endif
5238 #ifdef AI_CANONNAME
5239 PyModule_AddIntConstant(m, "AI_CANONNAME", AI_CANONNAME);
5240 #endif
5241 #ifdef AI_NUMERICHOST
5242 PyModule_AddIntConstant(m, "AI_NUMERICHOST", AI_NUMERICHOST);
5243 #endif
5244 #ifdef AI_NUMERICSERV
5245 PyModule_AddIntConstant(m, "AI_NUMERICSERV", AI_NUMERICSERV);
5246 #endif
5247 #ifdef AI_MASK
5248 PyModule_AddIntConstant(m, "AI_MASK", AI_MASK);
5249 #endif
5250 #ifdef AI_ALL
5251 PyModule_AddIntConstant(m, "AI_ALL", AI_ALL);
5252 #endif
5253 #ifdef AI_V4MAPPED_CFG
5254 PyModule_AddIntConstant(m, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG);
5255 #endif
5256 #ifdef AI_ADDRCONFIG
5257 PyModule_AddIntConstant(m, "AI_ADDRCONFIG", AI_ADDRCONFIG);
5258 #endif
5259 #ifdef AI_V4MAPPED
5260 PyModule_AddIntConstant(m, "AI_V4MAPPED", AI_V4MAPPED);
5261 #endif
5262 #ifdef AI_DEFAULT
5263 PyModule_AddIntConstant(m, "AI_DEFAULT", AI_DEFAULT);
5264 #endif
5265 #ifdef NI_MAXHOST
5266 PyModule_AddIntConstant(m, "NI_MAXHOST", NI_MAXHOST);
5267 #endif
5268 #ifdef NI_MAXSERV
5269 PyModule_AddIntConstant(m, "NI_MAXSERV", NI_MAXSERV);
5270 #endif
5271 #ifdef NI_NOFQDN
5272 PyModule_AddIntConstant(m, "NI_NOFQDN", NI_NOFQDN);
5273 #endif
5274 #ifdef NI_NUMERICHOST
5275 PyModule_AddIntConstant(m, "NI_NUMERICHOST", NI_NUMERICHOST);
5276 #endif
5277 #ifdef NI_NAMEREQD
5278 PyModule_AddIntConstant(m, "NI_NAMEREQD", NI_NAMEREQD);
5279 #endif
5280 #ifdef NI_NUMERICSERV
5281 PyModule_AddIntConstant(m, "NI_NUMERICSERV", NI_NUMERICSERV);
5282 #endif
5283 #ifdef NI_DGRAM
5284 PyModule_AddIntConstant(m, "NI_DGRAM", NI_DGRAM);
5285 #endif
5287 /* shutdown() parameters */
5288 #ifdef SHUT_RD
5289 PyModule_AddIntConstant(m, "SHUT_RD", SHUT_RD);
5290 #elif defined(SD_RECEIVE)
5291 PyModule_AddIntConstant(m, "SHUT_RD", SD_RECEIVE);
5292 #else
5293 PyModule_AddIntConstant(m, "SHUT_RD", 0);
5294 #endif
5295 #ifdef SHUT_WR
5296 PyModule_AddIntConstant(m, "SHUT_WR", SHUT_WR);
5297 #elif defined(SD_SEND)
5298 PyModule_AddIntConstant(m, "SHUT_WR", SD_SEND);
5299 #else
5300 PyModule_AddIntConstant(m, "SHUT_WR", 1);
5301 #endif
5302 #ifdef SHUT_RDWR
5303 PyModule_AddIntConstant(m, "SHUT_RDWR", SHUT_RDWR);
5304 #elif defined(SD_BOTH)
5305 PyModule_AddIntConstant(m, "SHUT_RDWR", SD_BOTH);
5306 #else
5307 PyModule_AddIntConstant(m, "SHUT_RDWR", 2);
5308 #endif
5310 #ifdef SIO_RCVALL
5312 DWORD codes[] = {SIO_RCVALL, SIO_KEEPALIVE_VALS};
5313 const char *names[] = {"SIO_RCVALL", "SIO_KEEPALIVE_VALS"};
5314 int i;
5315 for(i = 0; i<sizeof(codes)/sizeof(*codes); ++i) {
5316 PyObject *tmp;
5317 tmp = PyLong_FromUnsignedLong(codes[i]);
5318 if (tmp == NULL)
5319 return;
5320 PyModule_AddObject(m, names[i], tmp);
5323 PyModule_AddIntConstant(m, "RCVALL_OFF", RCVALL_OFF);
5324 PyModule_AddIntConstant(m, "RCVALL_ON", RCVALL_ON);
5325 PyModule_AddIntConstant(m, "RCVALL_SOCKETLEVELONLY", RCVALL_SOCKETLEVELONLY);
5326 #ifdef RCVALL_IPLEVEL
5327 PyModule_AddIntConstant(m, "RCVALL_IPLEVEL", RCVALL_IPLEVEL);
5328 #endif
5329 #ifdef RCVALL_MAX
5330 PyModule_AddIntConstant(m, "RCVALL_MAX", RCVALL_MAX);
5331 #endif
5332 #endif /* _MSTCPIP_ */
5334 /* Initialize gethostbyname lock */
5335 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
5336 netdb_lock = PyThread_allocate_lock();
5337 #endif
5341 #ifndef HAVE_INET_PTON
5342 #if !defined(NTDDI_VERSION) || (NTDDI_VERSION < NTDDI_LONGHORN)
5344 /* Simplistic emulation code for inet_pton that only works for IPv4 */
5345 /* These are not exposed because they do not set errno properly */
5348 inet_pton(int af, const char *src, void *dst)
5350 if (af == AF_INET) {
5351 #if (SIZEOF_INT != 4)
5352 #error "Not sure if in_addr_t exists and int is not 32-bits."
5353 #endif
5354 unsigned int packed_addr;
5355 packed_addr = inet_addr(src);
5356 if (packed_addr == INADDR_NONE)
5357 return 0;
5358 memcpy(dst, &packed_addr, 4);
5359 return 1;
5361 /* Should set errno to EAFNOSUPPORT */
5362 return -1;
5365 const char *
5366 inet_ntop(int af, const void *src, char *dst, socklen_t size)
5368 if (af == AF_INET) {
5369 struct in_addr packed_addr;
5370 if (size < 16)
5371 /* Should set errno to ENOSPC. */
5372 return NULL;
5373 memcpy(&packed_addr, src, sizeof(packed_addr));
5374 return strncpy(dst, inet_ntoa(packed_addr), size);
5376 /* Should set errno to EAFNOSUPPORT */
5377 return NULL;
5380 #endif
5381 #endif