move sections
[python/dscho.git] / Modules / socketmodule.c
blob5da7809ea1355af5063ded79add8794d406af149
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
1092 default:
1093 PyErr_SetString(PyExc_ValueError,
1094 "Unknown Bluetooth protocol");
1095 return NULL;
1097 #endif
1099 #ifdef HAVE_NETPACKET_PACKET_H
1100 case AF_PACKET:
1102 struct sockaddr_ll *a = (struct sockaddr_ll *)addr;
1103 char *ifname = "";
1104 struct ifreq ifr;
1105 /* need to look up interface name give index */
1106 if (a->sll_ifindex) {
1107 ifr.ifr_ifindex = a->sll_ifindex;
1108 if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0)
1109 ifname = ifr.ifr_name;
1111 return Py_BuildValue("shbhs#",
1112 ifname,
1113 ntohs(a->sll_protocol),
1114 a->sll_pkttype,
1115 a->sll_hatype,
1116 a->sll_addr,
1117 a->sll_halen);
1119 #endif
1121 #ifdef HAVE_LINUX_TIPC_H
1122 case AF_TIPC:
1124 struct sockaddr_tipc *a = (struct sockaddr_tipc *) addr;
1125 if (a->addrtype == TIPC_ADDR_NAMESEQ) {
1126 return Py_BuildValue("IIIII",
1127 a->addrtype,
1128 a->addr.nameseq.type,
1129 a->addr.nameseq.lower,
1130 a->addr.nameseq.upper,
1131 a->scope);
1132 } else if (a->addrtype == TIPC_ADDR_NAME) {
1133 return Py_BuildValue("IIIII",
1134 a->addrtype,
1135 a->addr.name.name.type,
1136 a->addr.name.name.instance,
1137 a->addr.name.name.instance,
1138 a->scope);
1139 } else if (a->addrtype == TIPC_ADDR_ID) {
1140 return Py_BuildValue("IIIII",
1141 a->addrtype,
1142 a->addr.id.node,
1143 a->addr.id.ref,
1145 a->scope);
1146 } else {
1147 PyErr_SetString(PyExc_ValueError,
1148 "Invalid address type");
1149 return NULL;
1152 #endif
1154 /* More cases here... */
1156 default:
1157 /* If we don't know the address family, don't raise an
1158 exception -- return it as a tuple. */
1159 return Py_BuildValue("is#",
1160 addr->sa_family,
1161 addr->sa_data,
1162 sizeof(addr->sa_data));
1168 /* Parse a socket address argument according to the socket object's
1169 address family. Return 1 if the address was in the proper format,
1170 0 of not. The address is returned through addr_ret, its length
1171 through len_ret. */
1173 static int
1174 getsockaddrarg(PySocketSockObject *s, PyObject *args,
1175 struct sockaddr *addr_ret, int *len_ret)
1177 switch (s->sock_family) {
1179 #if defined(AF_UNIX)
1180 case AF_UNIX:
1182 struct sockaddr_un* addr;
1183 char *path;
1184 int len;
1185 if (!PyArg_Parse(args, "t#", &path, &len))
1186 return 0;
1188 addr = (struct sockaddr_un*)addr_ret;
1189 #ifdef linux
1190 if (len > 0 && path[0] == 0) {
1191 /* Linux abstract namespace extension */
1192 if (len > sizeof addr->sun_path) {
1193 PyErr_SetString(socket_error,
1194 "AF_UNIX path too long");
1195 return 0;
1198 else
1199 #endif /* linux */
1201 /* regular NULL-terminated string */
1202 if (len >= sizeof addr->sun_path) {
1203 PyErr_SetString(socket_error,
1204 "AF_UNIX path too long");
1205 return 0;
1207 addr->sun_path[len] = 0;
1209 addr->sun_family = s->sock_family;
1210 memcpy(addr->sun_path, path, len);
1211 #if defined(PYOS_OS2)
1212 *len_ret = sizeof(*addr);
1213 #else
1214 *len_ret = len + offsetof(struct sockaddr_un, sun_path);
1215 #endif
1216 return 1;
1218 #endif /* AF_UNIX */
1220 #if defined(AF_NETLINK)
1221 case AF_NETLINK:
1223 struct sockaddr_nl* addr;
1224 int pid, groups;
1225 addr = (struct sockaddr_nl *)addr_ret;
1226 if (!PyTuple_Check(args)) {
1227 PyErr_Format(
1228 PyExc_TypeError,
1229 "getsockaddrarg: "
1230 "AF_NETLINK address must be tuple, not %.500s",
1231 Py_TYPE(args)->tp_name);
1232 return 0;
1234 if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &pid, &groups))
1235 return 0;
1236 addr->nl_family = AF_NETLINK;
1237 addr->nl_pid = pid;
1238 addr->nl_groups = groups;
1239 *len_ret = sizeof(*addr);
1240 return 1;
1242 #endif
1244 case AF_INET:
1246 struct sockaddr_in* addr;
1247 char *host;
1248 int port, result;
1249 if (!PyTuple_Check(args)) {
1250 PyErr_Format(
1251 PyExc_TypeError,
1252 "getsockaddrarg: "
1253 "AF_INET address must be tuple, not %.500s",
1254 Py_TYPE(args)->tp_name);
1255 return 0;
1257 if (!PyArg_ParseTuple(args, "eti:getsockaddrarg",
1258 "idna", &host, &port))
1259 return 0;
1260 addr=(struct sockaddr_in*)addr_ret;
1261 result = setipaddr(host, (struct sockaddr *)addr,
1262 sizeof(*addr), AF_INET);
1263 PyMem_Free(host);
1264 if (result < 0)
1265 return 0;
1266 if (port < 0 || port > 0xffff) {
1267 PyErr_SetString(
1268 PyExc_OverflowError,
1269 "getsockaddrarg: port must be 0-65535.");
1270 return 0;
1272 addr->sin_family = AF_INET;
1273 addr->sin_port = htons((short)port);
1274 *len_ret = sizeof *addr;
1275 return 1;
1278 #ifdef ENABLE_IPV6
1279 case AF_INET6:
1281 struct sockaddr_in6* addr;
1282 char *host;
1283 int port, flowinfo, scope_id, result;
1284 flowinfo = scope_id = 0;
1285 if (!PyTuple_Check(args)) {
1286 PyErr_Format(
1287 PyExc_TypeError,
1288 "getsockaddrarg: "
1289 "AF_INET6 address must be tuple, not %.500s",
1290 Py_TYPE(args)->tp_name);
1291 return 0;
1293 if (!PyArg_ParseTuple(args, "eti|ii",
1294 "idna", &host, &port, &flowinfo,
1295 &scope_id)) {
1296 return 0;
1298 addr = (struct sockaddr_in6*)addr_ret;
1299 result = setipaddr(host, (struct sockaddr *)addr,
1300 sizeof(*addr), AF_INET6);
1301 PyMem_Free(host);
1302 if (result < 0)
1303 return 0;
1304 if (port < 0 || port > 0xffff) {
1305 PyErr_SetString(
1306 PyExc_OverflowError,
1307 "getsockaddrarg: port must be 0-65535.");
1308 return 0;
1310 addr->sin6_family = s->sock_family;
1311 addr->sin6_port = htons((short)port);
1312 addr->sin6_flowinfo = flowinfo;
1313 addr->sin6_scope_id = scope_id;
1314 *len_ret = sizeof *addr;
1315 return 1;
1317 #endif
1319 #ifdef USE_BLUETOOTH
1320 case AF_BLUETOOTH:
1322 switch (s->sock_proto) {
1323 case BTPROTO_L2CAP:
1325 struct sockaddr_l2 *addr;
1326 char *straddr;
1328 addr = (struct sockaddr_l2 *)addr_ret;
1329 memset(addr, 0, sizeof(struct sockaddr_l2));
1330 _BT_L2_MEMB(addr, family) = AF_BLUETOOTH;
1331 if (!PyArg_ParseTuple(args, "si", &straddr,
1332 &_BT_L2_MEMB(addr, psm))) {
1333 PyErr_SetString(socket_error, "getsockaddrarg: "
1334 "wrong format");
1335 return 0;
1337 if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0)
1338 return 0;
1340 *len_ret = sizeof *addr;
1341 return 1;
1343 case BTPROTO_RFCOMM:
1345 struct sockaddr_rc *addr;
1346 char *straddr;
1348 addr = (struct sockaddr_rc *)addr_ret;
1349 _BT_RC_MEMB(addr, family) = AF_BLUETOOTH;
1350 if (!PyArg_ParseTuple(args, "si", &straddr,
1351 &_BT_RC_MEMB(addr, channel))) {
1352 PyErr_SetString(socket_error, "getsockaddrarg: "
1353 "wrong format");
1354 return 0;
1356 if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0)
1357 return 0;
1359 *len_ret = sizeof *addr;
1360 return 1;
1362 case BTPROTO_HCI:
1364 struct sockaddr_hci *addr = (struct sockaddr_hci *)addr_ret;
1365 _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH;
1366 if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) {
1367 PyErr_SetString(socket_error, "getsockaddrarg: "
1368 "wrong format");
1369 return 0;
1371 *len_ret = sizeof *addr;
1372 return 1;
1374 #if !defined(__FreeBSD__)
1375 case BTPROTO_SCO:
1377 struct sockaddr_sco *addr;
1378 char *straddr;
1380 addr = (struct sockaddr_sco *)addr_ret;
1381 _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH;
1382 straddr = PyString_AsString(args);
1383 if (straddr == NULL) {
1384 PyErr_SetString(socket_error, "getsockaddrarg: "
1385 "wrong format");
1386 return 0;
1388 if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0)
1389 return 0;
1391 *len_ret = sizeof *addr;
1392 return 1;
1394 #endif
1395 default:
1396 PyErr_SetString(socket_error, "getsockaddrarg: unknown Bluetooth protocol");
1397 return 0;
1400 #endif
1402 #ifdef HAVE_NETPACKET_PACKET_H
1403 case AF_PACKET:
1405 struct sockaddr_ll* addr;
1406 struct ifreq ifr;
1407 char *interfaceName;
1408 int protoNumber;
1409 int hatype = 0;
1410 int pkttype = 0;
1411 char *haddr = NULL;
1412 unsigned int halen = 0;
1414 if (!PyTuple_Check(args)) {
1415 PyErr_Format(
1416 PyExc_TypeError,
1417 "getsockaddrarg: "
1418 "AF_PACKET address must be tuple, not %.500s",
1419 Py_TYPE(args)->tp_name);
1420 return 0;
1422 if (!PyArg_ParseTuple(args, "si|iis#", &interfaceName,
1423 &protoNumber, &pkttype, &hatype,
1424 &haddr, &halen))
1425 return 0;
1426 strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name));
1427 ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
1428 if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
1429 s->errorhandler();
1430 return 0;
1432 if (halen > 8) {
1433 PyErr_SetString(PyExc_ValueError,
1434 "Hardware address must be 8 bytes or less");
1435 return 0;
1437 if (protoNumber < 0 || protoNumber > 0xffff) {
1438 PyErr_SetString(
1439 PyExc_OverflowError,
1440 "getsockaddrarg: protoNumber must be 0-65535.");
1441 return 0;
1443 addr = (struct sockaddr_ll*)addr_ret;
1444 addr->sll_family = AF_PACKET;
1445 addr->sll_protocol = htons((short)protoNumber);
1446 addr->sll_ifindex = ifr.ifr_ifindex;
1447 addr->sll_pkttype = pkttype;
1448 addr->sll_hatype = hatype;
1449 if (halen != 0) {
1450 memcpy(&addr->sll_addr, haddr, halen);
1452 addr->sll_halen = halen;
1453 *len_ret = sizeof *addr;
1454 return 1;
1456 #endif
1458 #ifdef HAVE_LINUX_TIPC_H
1459 case AF_TIPC:
1461 unsigned int atype, v1, v2, v3;
1462 unsigned int scope = TIPC_CLUSTER_SCOPE;
1463 struct sockaddr_tipc *addr;
1465 if (!PyTuple_Check(args)) {
1466 PyErr_Format(
1467 PyExc_TypeError,
1468 "getsockaddrarg: "
1469 "AF_TIPC address must be tuple, not %.500s",
1470 Py_TYPE(args)->tp_name);
1471 return 0;
1474 if (!PyArg_ParseTuple(args,
1475 "IIII|I;Invalid TIPC address format",
1476 &atype, &v1, &v2, &v3, &scope))
1477 return 0;
1479 addr = (struct sockaddr_tipc *) addr_ret;
1480 memset(addr, 0, sizeof(struct sockaddr_tipc));
1482 addr->family = AF_TIPC;
1483 addr->scope = scope;
1484 addr->addrtype = atype;
1486 if (atype == TIPC_ADDR_NAMESEQ) {
1487 addr->addr.nameseq.type = v1;
1488 addr->addr.nameseq.lower = v2;
1489 addr->addr.nameseq.upper = v3;
1490 } else if (atype == TIPC_ADDR_NAME) {
1491 addr->addr.name.name.type = v1;
1492 addr->addr.name.name.instance = v2;
1493 } else if (atype == TIPC_ADDR_ID) {
1494 addr->addr.id.node = v1;
1495 addr->addr.id.ref = v2;
1496 } else {
1497 /* Shouldn't happen */
1498 PyErr_SetString(PyExc_TypeError, "Invalid address type");
1499 return 0;
1502 *len_ret = sizeof(*addr);
1504 return 1;
1506 #endif
1508 /* More cases here... */
1510 default:
1511 PyErr_SetString(socket_error, "getsockaddrarg: bad family");
1512 return 0;
1518 /* Get the address length according to the socket object's address family.
1519 Return 1 if the family is known, 0 otherwise. The length is returned
1520 through len_ret. */
1522 static int
1523 getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
1525 switch (s->sock_family) {
1527 #if defined(AF_UNIX)
1528 case AF_UNIX:
1530 *len_ret = sizeof (struct sockaddr_un);
1531 return 1;
1533 #endif /* AF_UNIX */
1534 #if defined(AF_NETLINK)
1535 case AF_NETLINK:
1537 *len_ret = sizeof (struct sockaddr_nl);
1538 return 1;
1540 #endif
1542 case AF_INET:
1544 *len_ret = sizeof (struct sockaddr_in);
1545 return 1;
1548 #ifdef ENABLE_IPV6
1549 case AF_INET6:
1551 *len_ret = sizeof (struct sockaddr_in6);
1552 return 1;
1554 #endif
1556 #ifdef USE_BLUETOOTH
1557 case AF_BLUETOOTH:
1559 switch(s->sock_proto)
1562 case BTPROTO_L2CAP:
1563 *len_ret = sizeof (struct sockaddr_l2);
1564 return 1;
1565 case BTPROTO_RFCOMM:
1566 *len_ret = sizeof (struct sockaddr_rc);
1567 return 1;
1568 case BTPROTO_HCI:
1569 *len_ret = sizeof (struct sockaddr_hci);
1570 return 1;
1571 #if !defined(__FreeBSD__)
1572 case BTPROTO_SCO:
1573 *len_ret = sizeof (struct sockaddr_sco);
1574 return 1;
1575 #endif
1576 default:
1577 PyErr_SetString(socket_error, "getsockaddrlen: "
1578 "unknown BT protocol");
1579 return 0;
1583 #endif
1585 #ifdef HAVE_NETPACKET_PACKET_H
1586 case AF_PACKET:
1588 *len_ret = sizeof (struct sockaddr_ll);
1589 return 1;
1591 #endif
1593 #ifdef HAVE_LINUX_TIPC_H
1594 case AF_TIPC:
1596 *len_ret = sizeof (struct sockaddr_tipc);
1597 return 1;
1599 #endif
1601 /* More cases here... */
1603 default:
1604 PyErr_SetString(socket_error, "getsockaddrlen: bad family");
1605 return 0;
1611 /* s.accept() method */
1613 static PyObject *
1614 sock_accept(PySocketSockObject *s)
1616 sock_addr_t addrbuf;
1617 SOCKET_T newfd;
1618 socklen_t addrlen;
1619 PyObject *sock = NULL;
1620 PyObject *addr = NULL;
1621 PyObject *res = NULL;
1622 int timeout;
1624 if (!getsockaddrlen(s, &addrlen))
1625 return NULL;
1626 memset(&addrbuf, 0, addrlen);
1628 #ifdef MS_WINDOWS
1629 newfd = INVALID_SOCKET;
1630 #else
1631 newfd = -1;
1632 #endif
1634 if (!IS_SELECTABLE(s))
1635 return select_error();
1637 Py_BEGIN_ALLOW_THREADS
1638 timeout = internal_select(s, 0);
1639 if (!timeout)
1640 newfd = accept(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
1641 Py_END_ALLOW_THREADS
1643 if (timeout == 1) {
1644 PyErr_SetString(socket_timeout, "timed out");
1645 return NULL;
1648 #ifdef MS_WINDOWS
1649 if (newfd == INVALID_SOCKET)
1650 #else
1651 if (newfd < 0)
1652 #endif
1653 return s->errorhandler();
1655 /* Create the new object with unspecified family,
1656 to avoid calls to bind() etc. on it. */
1657 sock = (PyObject *) new_sockobject(newfd,
1658 s->sock_family,
1659 s->sock_type,
1660 s->sock_proto);
1662 if (sock == NULL) {
1663 SOCKETCLOSE(newfd);
1664 goto finally;
1666 addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
1667 addrlen, s->sock_proto);
1668 if (addr == NULL)
1669 goto finally;
1671 res = PyTuple_Pack(2, sock, addr);
1673 finally:
1674 Py_XDECREF(sock);
1675 Py_XDECREF(addr);
1676 return res;
1679 PyDoc_STRVAR(accept_doc,
1680 "accept() -> (socket object, address info)\n\
1682 Wait for an incoming connection. Return a new socket representing the\n\
1683 connection, and the address of the client. For IP sockets, the address\n\
1684 info is a pair (hostaddr, port).");
1686 /* s.setblocking(flag) method. Argument:
1687 False -- non-blocking mode; same as settimeout(0)
1688 True -- blocking mode; same as settimeout(None)
1691 static PyObject *
1692 sock_setblocking(PySocketSockObject *s, PyObject *arg)
1694 int block;
1696 block = PyInt_AsLong(arg);
1697 if (block == -1 && PyErr_Occurred())
1698 return NULL;
1700 s->sock_timeout = block ? -1.0 : 0.0;
1701 internal_setblocking(s, block);
1703 Py_INCREF(Py_None);
1704 return Py_None;
1707 PyDoc_STRVAR(setblocking_doc,
1708 "setblocking(flag)\n\
1710 Set the socket to blocking (flag is true) or non-blocking (false).\n\
1711 setblocking(True) is equivalent to settimeout(None);\n\
1712 setblocking(False) is equivalent to settimeout(0.0).");
1714 /* s.settimeout(timeout) method. Argument:
1715 None -- no timeout, blocking mode; same as setblocking(True)
1716 0.0 -- non-blocking mode; same as setblocking(False)
1717 > 0 -- timeout mode; operations time out after timeout seconds
1718 < 0 -- illegal; raises an exception
1720 static PyObject *
1721 sock_settimeout(PySocketSockObject *s, PyObject *arg)
1723 double timeout;
1725 if (arg == Py_None)
1726 timeout = -1.0;
1727 else {
1728 timeout = PyFloat_AsDouble(arg);
1729 if (timeout < 0.0) {
1730 if (!PyErr_Occurred())
1731 PyErr_SetString(PyExc_ValueError,
1732 "Timeout value out of range");
1733 return NULL;
1737 s->sock_timeout = timeout;
1738 internal_setblocking(s, timeout < 0.0);
1740 Py_INCREF(Py_None);
1741 return Py_None;
1744 PyDoc_STRVAR(settimeout_doc,
1745 "settimeout(timeout)\n\
1747 Set a timeout on socket operations. 'timeout' can be a float,\n\
1748 giving in seconds, or None. Setting a timeout of None disables\n\
1749 the timeout feature and is equivalent to setblocking(1).\n\
1750 Setting a timeout of zero is the same as setblocking(0).");
1752 /* s.gettimeout() method.
1753 Returns the timeout associated with a socket. */
1754 static PyObject *
1755 sock_gettimeout(PySocketSockObject *s)
1757 if (s->sock_timeout < 0.0) {
1758 Py_INCREF(Py_None);
1759 return Py_None;
1761 else
1762 return PyFloat_FromDouble(s->sock_timeout);
1765 PyDoc_STRVAR(gettimeout_doc,
1766 "gettimeout() -> timeout\n\
1768 Returns the timeout in floating seconds associated with socket \n\
1769 operations. A timeout of None indicates that timeouts on socket \n\
1770 operations are disabled.");
1772 #ifdef RISCOS
1773 /* s.sleeptaskw(1 | 0) method */
1775 static PyObject *
1776 sock_sleeptaskw(PySocketSockObject *s,PyObject *arg)
1778 int block;
1779 block = PyInt_AsLong(arg);
1780 if (block == -1 && PyErr_Occurred())
1781 return NULL;
1782 Py_BEGIN_ALLOW_THREADS
1783 socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
1784 Py_END_ALLOW_THREADS
1786 Py_INCREF(Py_None);
1787 return Py_None;
1789 PyDoc_STRVAR(sleeptaskw_doc,
1790 "sleeptaskw(flag)\n\
1792 Allow sleeps in taskwindows.");
1793 #endif
1796 /* s.setsockopt() method.
1797 With an integer third argument, sets an integer option.
1798 With a string third argument, sets an option from a buffer;
1799 use optional built-in module 'struct' to encode the string. */
1801 static PyObject *
1802 sock_setsockopt(PySocketSockObject *s, PyObject *args)
1804 int level;
1805 int optname;
1806 int res;
1807 char *buf;
1808 int buflen;
1809 int flag;
1811 if (PyArg_ParseTuple(args, "iii:setsockopt",
1812 &level, &optname, &flag)) {
1813 buf = (char *) &flag;
1814 buflen = sizeof flag;
1816 else {
1817 PyErr_Clear();
1818 if (!PyArg_ParseTuple(args, "iis#:setsockopt",
1819 &level, &optname, &buf, &buflen))
1820 return NULL;
1822 res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen);
1823 if (res < 0)
1824 return s->errorhandler();
1825 Py_INCREF(Py_None);
1826 return Py_None;
1829 PyDoc_STRVAR(setsockopt_doc,
1830 "setsockopt(level, option, value)\n\
1832 Set a socket option. See the Unix manual for level and option.\n\
1833 The value argument can either be an integer or a string.");
1836 /* s.getsockopt() method.
1837 With two arguments, retrieves an integer option.
1838 With a third integer argument, retrieves a string buffer of that size;
1839 use optional built-in module 'struct' to decode the string. */
1841 static PyObject *
1842 sock_getsockopt(PySocketSockObject *s, PyObject *args)
1844 int level;
1845 int optname;
1846 int res;
1847 PyObject *buf;
1848 socklen_t buflen = 0;
1850 #ifdef __BEOS__
1851 /* We have incomplete socket support. */
1852 PyErr_SetString(socket_error, "getsockopt not supported");
1853 return NULL;
1854 #else
1856 if (!PyArg_ParseTuple(args, "ii|i:getsockopt",
1857 &level, &optname, &buflen))
1858 return NULL;
1860 if (buflen == 0) {
1861 int flag = 0;
1862 socklen_t flagsize = sizeof flag;
1863 res = getsockopt(s->sock_fd, level, optname,
1864 (void *)&flag, &flagsize);
1865 if (res < 0)
1866 return s->errorhandler();
1867 return PyInt_FromLong(flag);
1869 #ifdef __VMS
1870 /* socklen_t is unsigned so no negative test is needed,
1871 test buflen == 0 is previously done */
1872 if (buflen > 1024) {
1873 #else
1874 if (buflen <= 0 || buflen > 1024) {
1875 #endif
1876 PyErr_SetString(socket_error,
1877 "getsockopt buflen out of range");
1878 return NULL;
1880 buf = PyString_FromStringAndSize((char *)NULL, buflen);
1881 if (buf == NULL)
1882 return NULL;
1883 res = getsockopt(s->sock_fd, level, optname,
1884 (void *)PyString_AS_STRING(buf), &buflen);
1885 if (res < 0) {
1886 Py_DECREF(buf);
1887 return s->errorhandler();
1889 _PyString_Resize(&buf, buflen);
1890 return buf;
1891 #endif /* __BEOS__ */
1894 PyDoc_STRVAR(getsockopt_doc,
1895 "getsockopt(level, option[, buffersize]) -> value\n\
1897 Get a socket option. See the Unix manual for level and option.\n\
1898 If a nonzero buffersize argument is given, the return value is a\n\
1899 string of that length; otherwise it is an integer.");
1902 /* s.bind(sockaddr) method */
1904 static PyObject *
1905 sock_bind(PySocketSockObject *s, PyObject *addro)
1907 sock_addr_t addrbuf;
1908 int addrlen;
1909 int res;
1911 if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
1912 return NULL;
1913 Py_BEGIN_ALLOW_THREADS
1914 res = bind(s->sock_fd, SAS2SA(&addrbuf), addrlen);
1915 Py_END_ALLOW_THREADS
1916 if (res < 0)
1917 return s->errorhandler();
1918 Py_INCREF(Py_None);
1919 return Py_None;
1922 PyDoc_STRVAR(bind_doc,
1923 "bind(address)\n\
1925 Bind the socket to a local address. For IP sockets, the address is a\n\
1926 pair (host, port); the host must refer to the local host. For raw packet\n\
1927 sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");
1930 /* s.close() method.
1931 Set the file descriptor to -1 so operations tried subsequently
1932 will surely fail. */
1934 static PyObject *
1935 sock_close(PySocketSockObject *s)
1937 SOCKET_T fd;
1939 if ((fd = s->sock_fd) != -1) {
1940 s->sock_fd = -1;
1941 Py_BEGIN_ALLOW_THREADS
1942 (void) SOCKETCLOSE(fd);
1943 Py_END_ALLOW_THREADS
1945 Py_INCREF(Py_None);
1946 return Py_None;
1949 PyDoc_STRVAR(close_doc,
1950 "close()\n\
1952 Close the socket. It cannot be used after this call.");
1954 static int
1955 internal_connect(PySocketSockObject *s, struct sockaddr *addr, int addrlen,
1956 int *timeoutp)
1958 int res, timeout;
1960 timeout = 0;
1961 res = connect(s->sock_fd, addr, addrlen);
1963 #ifdef MS_WINDOWS
1965 if (s->sock_timeout > 0.0) {
1966 if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK &&
1967 IS_SELECTABLE(s)) {
1968 /* This is a mess. Best solution: trust select */
1969 fd_set fds;
1970 fd_set fds_exc;
1971 struct timeval tv;
1972 tv.tv_sec = (int)s->sock_timeout;
1973 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1974 FD_ZERO(&fds);
1975 FD_SET(s->sock_fd, &fds);
1976 FD_ZERO(&fds_exc);
1977 FD_SET(s->sock_fd, &fds_exc);
1978 res = select(s->sock_fd+1, NULL, &fds, &fds_exc, &tv);
1979 if (res == 0) {
1980 res = WSAEWOULDBLOCK;
1981 timeout = 1;
1982 } else if (res > 0) {
1983 if (FD_ISSET(s->sock_fd, &fds))
1984 /* The socket is in the writeable set - this
1985 means connected */
1986 res = 0;
1987 else {
1988 /* As per MS docs, we need to call getsockopt()
1989 to get the underlying error */
1990 int res_size = sizeof res;
1991 /* It must be in the exception set */
1992 assert(FD_ISSET(s->sock_fd, &fds_exc));
1993 if (0 == getsockopt(s->sock_fd, SOL_SOCKET, SO_ERROR,
1994 (char *)&res, &res_size))
1995 /* getsockopt also clears WSAGetLastError,
1996 so reset it back. */
1997 WSASetLastError(res);
1998 else
1999 res = WSAGetLastError();
2002 /* else if (res < 0) an error occurred */
2006 if (res < 0)
2007 res = WSAGetLastError();
2009 #else
2011 if (s->sock_timeout > 0.0) {
2012 if (res < 0 && errno == EINPROGRESS && IS_SELECTABLE(s)) {
2013 timeout = internal_select(s, 1);
2014 if (timeout == 0) {
2015 /* Bug #1019808: in case of an EINPROGRESS,
2016 use getsockopt(SO_ERROR) to get the real
2017 error. */
2018 socklen_t res_size = sizeof res;
2019 (void)getsockopt(s->sock_fd, SOL_SOCKET,
2020 SO_ERROR, &res, &res_size);
2021 if (res == EISCONN)
2022 res = 0;
2023 errno = res;
2025 else if (timeout == -1) {
2026 res = errno; /* had error */
2028 else
2029 res = EWOULDBLOCK; /* timed out */
2033 if (res < 0)
2034 res = errno;
2036 #endif
2037 *timeoutp = timeout;
2039 return res;
2042 /* s.connect(sockaddr) method */
2044 static PyObject *
2045 sock_connect(PySocketSockObject *s, PyObject *addro)
2047 sock_addr_t addrbuf;
2048 int addrlen;
2049 int res;
2050 int timeout;
2052 if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
2053 return NULL;
2055 Py_BEGIN_ALLOW_THREADS
2056 res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
2057 Py_END_ALLOW_THREADS
2059 if (timeout == 1) {
2060 PyErr_SetString(socket_timeout, "timed out");
2061 return NULL;
2063 if (res != 0)
2064 return s->errorhandler();
2065 Py_INCREF(Py_None);
2066 return Py_None;
2069 PyDoc_STRVAR(connect_doc,
2070 "connect(address)\n\
2072 Connect the socket to a remote address. For IP sockets, the address\n\
2073 is a pair (host, port).");
2076 /* s.connect_ex(sockaddr) method */
2078 static PyObject *
2079 sock_connect_ex(PySocketSockObject *s, PyObject *addro)
2081 sock_addr_t addrbuf;
2082 int addrlen;
2083 int res;
2084 int timeout;
2086 if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
2087 return NULL;
2089 Py_BEGIN_ALLOW_THREADS
2090 res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
2091 Py_END_ALLOW_THREADS
2093 /* Signals are not errors (though they may raise exceptions). Adapted
2094 from PyErr_SetFromErrnoWithFilenameObject(). */
2095 #ifdef EINTR
2096 if (res == EINTR && PyErr_CheckSignals())
2097 return NULL;
2098 #endif
2100 return PyInt_FromLong((long) res);
2103 PyDoc_STRVAR(connect_ex_doc,
2104 "connect_ex(address) -> errno\n\
2106 This is like connect(address), but returns an error code (the errno value)\n\
2107 instead of raising an exception when an error occurs.");
2110 /* s.fileno() method */
2112 static PyObject *
2113 sock_fileno(PySocketSockObject *s)
2115 #if SIZEOF_SOCKET_T <= SIZEOF_LONG
2116 return PyInt_FromLong((long) s->sock_fd);
2117 #else
2118 return PyLong_FromLongLong((PY_LONG_LONG)s->sock_fd);
2119 #endif
2122 PyDoc_STRVAR(fileno_doc,
2123 "fileno() -> integer\n\
2125 Return the integer file descriptor of the socket.");
2128 #ifndef NO_DUP
2129 /* s.dup() method */
2131 static PyObject *
2132 sock_dup(PySocketSockObject *s)
2134 SOCKET_T newfd;
2135 PyObject *sock;
2137 newfd = dup(s->sock_fd);
2138 if (newfd < 0)
2139 return s->errorhandler();
2140 sock = (PyObject *) new_sockobject(newfd,
2141 s->sock_family,
2142 s->sock_type,
2143 s->sock_proto);
2144 if (sock == NULL)
2145 SOCKETCLOSE(newfd);
2146 return sock;
2149 PyDoc_STRVAR(dup_doc,
2150 "dup() -> socket object\n\
2152 Return a new socket object connected to the same system resource.");
2154 #endif
2157 /* s.getsockname() method */
2159 static PyObject *
2160 sock_getsockname(PySocketSockObject *s)
2162 sock_addr_t addrbuf;
2163 int res;
2164 socklen_t addrlen;
2166 if (!getsockaddrlen(s, &addrlen))
2167 return NULL;
2168 memset(&addrbuf, 0, addrlen);
2169 Py_BEGIN_ALLOW_THREADS
2170 res = getsockname(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
2171 Py_END_ALLOW_THREADS
2172 if (res < 0)
2173 return s->errorhandler();
2174 return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
2175 s->sock_proto);
2178 PyDoc_STRVAR(getsockname_doc,
2179 "getsockname() -> address info\n\
2181 Return the address of the local endpoint. For IP sockets, the address\n\
2182 info is a pair (hostaddr, port).");
2185 #ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
2186 /* s.getpeername() method */
2188 static PyObject *
2189 sock_getpeername(PySocketSockObject *s)
2191 sock_addr_t addrbuf;
2192 int res;
2193 socklen_t addrlen;
2195 if (!getsockaddrlen(s, &addrlen))
2196 return NULL;
2197 memset(&addrbuf, 0, addrlen);
2198 Py_BEGIN_ALLOW_THREADS
2199 res = getpeername(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
2200 Py_END_ALLOW_THREADS
2201 if (res < 0)
2202 return s->errorhandler();
2203 return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
2204 s->sock_proto);
2207 PyDoc_STRVAR(getpeername_doc,
2208 "getpeername() -> address info\n\
2210 Return the address of the remote endpoint. For IP sockets, the address\n\
2211 info is a pair (hostaddr, port).");
2213 #endif /* HAVE_GETPEERNAME */
2216 /* s.listen(n) method */
2218 static PyObject *
2219 sock_listen(PySocketSockObject *s, PyObject *arg)
2221 int backlog;
2222 int res;
2224 backlog = PyInt_AsLong(arg);
2225 if (backlog == -1 && PyErr_Occurred())
2226 return NULL;
2227 Py_BEGIN_ALLOW_THREADS
2228 if (backlog < 1)
2229 backlog = 1;
2230 res = listen(s->sock_fd, backlog);
2231 Py_END_ALLOW_THREADS
2232 if (res < 0)
2233 return s->errorhandler();
2234 Py_INCREF(Py_None);
2235 return Py_None;
2238 PyDoc_STRVAR(listen_doc,
2239 "listen(backlog)\n\
2241 Enable a server to accept connections. The backlog argument must be at\n\
2242 least 1; it specifies the number of unaccepted connection that the system\n\
2243 will allow before refusing new connections.");
2246 #ifndef NO_DUP
2247 /* s.makefile(mode) method.
2248 Create a new open file object referring to a dupped version of
2249 the socket's file descriptor. (The dup() call is necessary so
2250 that the open file and socket objects may be closed independent
2251 of each other.)
2252 The mode argument specifies 'r' or 'w' passed to fdopen(). */
2254 static PyObject *
2255 sock_makefile(PySocketSockObject *s, PyObject *args)
2257 extern int fclose(FILE *);
2258 char *mode = "r";
2259 int bufsize = -1;
2260 #ifdef MS_WIN32
2261 Py_intptr_t fd;
2262 #else
2263 int fd;
2264 #endif
2265 FILE *fp;
2266 PyObject *f;
2267 #ifdef __VMS
2268 char *mode_r = "r";
2269 char *mode_w = "w";
2270 #endif
2272 if (!PyArg_ParseTuple(args, "|si:makefile", &mode, &bufsize))
2273 return NULL;
2274 #ifdef __VMS
2275 if (strcmp(mode,"rb") == 0) {
2276 mode = mode_r;
2278 else {
2279 if (strcmp(mode,"wb") == 0) {
2280 mode = mode_w;
2283 #endif
2284 #ifdef MS_WIN32
2285 if (((fd = _open_osfhandle(s->sock_fd, _O_BINARY)) < 0) ||
2286 ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL))
2287 #else
2288 if ((fd = dup(s->sock_fd)) < 0 || (fp = fdopen(fd, mode)) == NULL)
2289 #endif
2291 if (fd >= 0)
2292 SOCKETCLOSE(fd);
2293 return s->errorhandler();
2295 f = PyFile_FromFile(fp, "<socket>", mode, fclose);
2296 if (f != NULL)
2297 PyFile_SetBufSize(f, bufsize);
2298 return f;
2301 PyDoc_STRVAR(makefile_doc,
2302 "makefile([mode[, buffersize]]) -> file object\n\
2304 Return a regular file object corresponding to the socket.\n\
2305 The mode and buffersize arguments are as for the built-in open() function.");
2307 #endif /* NO_DUP */
2310 * This is the guts of the recv() and recv_into() methods, which reads into a
2311 * char buffer. If you have any inc/dec ref to do to the objects that contain
2312 * the buffer, do it in the caller. This function returns the number of bytes
2313 * succesfully read. If there was an error, it returns -1. Note that it is
2314 * also possible that we return a number of bytes smaller than the request
2315 * bytes.
2317 static ssize_t
2318 sock_recv_guts(PySocketSockObject *s, char* cbuf, int len, int flags)
2320 ssize_t outlen = -1;
2321 int timeout;
2322 #ifdef __VMS
2323 int remaining;
2324 char *read_buf;
2325 #endif
2327 if (!IS_SELECTABLE(s)) {
2328 select_error();
2329 return -1;
2332 #ifndef __VMS
2333 Py_BEGIN_ALLOW_THREADS
2334 timeout = internal_select(s, 0);
2335 if (!timeout)
2336 outlen = recv(s->sock_fd, cbuf, len, flags);
2337 Py_END_ALLOW_THREADS
2339 if (timeout == 1) {
2340 PyErr_SetString(socket_timeout, "timed out");
2341 return -1;
2343 if (outlen < 0) {
2344 /* Note: the call to errorhandler() ALWAYS indirectly returned
2345 NULL, so ignore its return value */
2346 s->errorhandler();
2347 return -1;
2349 #else
2350 read_buf = cbuf;
2351 remaining = len;
2352 while (remaining != 0) {
2353 unsigned int segment;
2354 int nread = -1;
2356 segment = remaining /SEGMENT_SIZE;
2357 if (segment != 0) {
2358 segment = SEGMENT_SIZE;
2360 else {
2361 segment = remaining;
2364 Py_BEGIN_ALLOW_THREADS
2365 timeout = internal_select(s, 0);
2366 if (!timeout)
2367 nread = recv(s->sock_fd, read_buf, segment, flags);
2368 Py_END_ALLOW_THREADS
2370 if (timeout == 1) {
2371 PyErr_SetString(socket_timeout, "timed out");
2372 return -1;
2374 if (nread < 0) {
2375 s->errorhandler();
2376 return -1;
2378 if (nread != remaining) {
2379 read_buf += nread;
2380 break;
2383 remaining -= segment;
2384 read_buf += segment;
2386 outlen = read_buf - cbuf;
2387 #endif /* !__VMS */
2389 return outlen;
2393 /* s.recv(nbytes [,flags]) method */
2395 static PyObject *
2396 sock_recv(PySocketSockObject *s, PyObject *args)
2398 int recvlen, flags = 0;
2399 ssize_t outlen;
2400 PyObject *buf;
2402 if (!PyArg_ParseTuple(args, "i|i:recv", &recvlen, &flags))
2403 return NULL;
2405 if (recvlen < 0) {
2406 PyErr_SetString(PyExc_ValueError,
2407 "negative buffersize in recv");
2408 return NULL;
2411 /* Allocate a new string. */
2412 buf = PyString_FromStringAndSize((char *) 0, recvlen);
2413 if (buf == NULL)
2414 return NULL;
2416 /* Call the guts */
2417 outlen = sock_recv_guts(s, PyString_AS_STRING(buf), recvlen, flags);
2418 if (outlen < 0) {
2419 /* An error occurred, release the string and return an
2420 error. */
2421 Py_DECREF(buf);
2422 return NULL;
2424 if (outlen != recvlen) {
2425 /* We did not read as many bytes as we anticipated, resize the
2426 string if possible and be succesful. */
2427 if (_PyString_Resize(&buf, outlen) < 0)
2428 /* Oopsy, not so succesful after all. */
2429 return NULL;
2432 return buf;
2435 PyDoc_STRVAR(recv_doc,
2436 "recv(buffersize[, flags]) -> data\n\
2438 Receive up to buffersize bytes from the socket. For the optional flags\n\
2439 argument, see the Unix manual. When no data is available, block until\n\
2440 at least one byte is available or until the remote end is closed. When\n\
2441 the remote end is closed and all data is read, return the empty string.");
2444 /* s.recv_into(buffer, [nbytes [,flags]]) method */
2446 static PyObject*
2447 sock_recv_into(PySocketSockObject *s, PyObject *args, PyObject *kwds)
2449 static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
2451 int recvlen = 0, flags = 0;
2452 ssize_t readlen;
2453 Py_buffer buf;
2454 Py_ssize_t buflen;
2456 /* Get the buffer's memory */
2457 if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recv_into", kwlist,
2458 &buf, &recvlen, &flags))
2459 return NULL;
2460 buflen = buf.len;
2461 assert(buf.buf != 0 && buflen > 0);
2463 if (recvlen < 0) {
2464 PyErr_SetString(PyExc_ValueError,
2465 "negative buffersize in recv_into");
2466 goto error;
2468 if (recvlen == 0) {
2469 /* If nbytes was not specified, use the buffer's length */
2470 recvlen = buflen;
2473 /* Check if the buffer is large enough */
2474 if (buflen < recvlen) {
2475 PyErr_SetString(PyExc_ValueError,
2476 "buffer too small for requested bytes");
2477 goto error;
2480 /* Call the guts */
2481 readlen = sock_recv_guts(s, buf.buf, recvlen, flags);
2482 if (readlen < 0) {
2483 /* Return an error. */
2484 goto error;
2487 PyBuffer_Release(&buf);
2488 /* Return the number of bytes read. Note that we do not do anything
2489 special here in the case that readlen < recvlen. */
2490 return PyInt_FromSsize_t(readlen);
2492 error:
2493 PyBuffer_Release(&buf);
2494 return NULL;
2497 PyDoc_STRVAR(recv_into_doc,
2498 "recv_into(buffer, [nbytes[, flags]]) -> nbytes_read\n\
2500 A version of recv() that stores its data into a buffer rather than creating \n\
2501 a new string. Receive up to buffersize bytes from the socket. If buffersize \n\
2502 is not specified (or 0), receive up to the size available in the given buffer.\n\
2504 See recv() for documentation about the flags.");
2508 * This is the guts of the recvfrom() and recvfrom_into() methods, which reads
2509 * into a char buffer. If you have any inc/def ref to do to the objects that
2510 * contain the buffer, do it in the caller. This function returns the number
2511 * of bytes succesfully read. If there was an error, it returns -1. Note
2512 * that it is also possible that we return a number of bytes smaller than the
2513 * request bytes.
2515 * 'addr' is a return value for the address object. Note that you must decref
2516 * it yourself.
2518 static ssize_t
2519 sock_recvfrom_guts(PySocketSockObject *s, char* cbuf, int len, int flags,
2520 PyObject** addr)
2522 sock_addr_t addrbuf;
2523 int timeout;
2524 ssize_t n = -1;
2525 socklen_t addrlen;
2527 *addr = NULL;
2529 if (!getsockaddrlen(s, &addrlen))
2530 return -1;
2532 if (!IS_SELECTABLE(s)) {
2533 select_error();
2534 return -1;
2537 Py_BEGIN_ALLOW_THREADS
2538 memset(&addrbuf, 0, addrlen);
2539 timeout = internal_select(s, 0);
2540 if (!timeout) {
2541 #ifndef MS_WINDOWS
2542 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
2543 n = recvfrom(s->sock_fd, cbuf, len, flags,
2544 SAS2SA(&addrbuf), &addrlen);
2545 #else
2546 n = recvfrom(s->sock_fd, cbuf, len, flags,
2547 (void *) &addrbuf, &addrlen);
2548 #endif
2549 #else
2550 n = recvfrom(s->sock_fd, cbuf, len, flags,
2551 SAS2SA(&addrbuf), &addrlen);
2552 #endif
2554 Py_END_ALLOW_THREADS
2556 if (timeout == 1) {
2557 PyErr_SetString(socket_timeout, "timed out");
2558 return -1;
2560 if (n < 0) {
2561 s->errorhandler();
2562 return -1;
2565 if (!(*addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
2566 addrlen, s->sock_proto)))
2567 return -1;
2569 return n;
2572 /* s.recvfrom(nbytes [,flags]) method */
2574 static PyObject *
2575 sock_recvfrom(PySocketSockObject *s, PyObject *args)
2577 PyObject *buf = NULL;
2578 PyObject *addr = NULL;
2579 PyObject *ret = NULL;
2580 int recvlen, flags = 0;
2581 ssize_t outlen;
2583 if (!PyArg_ParseTuple(args, "i|i:recvfrom", &recvlen, &flags))
2584 return NULL;
2586 if (recvlen < 0) {
2587 PyErr_SetString(PyExc_ValueError,
2588 "negative buffersize in recvfrom");
2589 return NULL;
2592 buf = PyString_FromStringAndSize((char *) 0, recvlen);
2593 if (buf == NULL)
2594 return NULL;
2596 outlen = sock_recvfrom_guts(s, PyString_AS_STRING(buf),
2597 recvlen, flags, &addr);
2598 if (outlen < 0) {
2599 goto finally;
2602 if (outlen != recvlen) {
2603 /* We did not read as many bytes as we anticipated, resize the
2604 string if possible and be succesful. */
2605 if (_PyString_Resize(&buf, outlen) < 0)
2606 /* Oopsy, not so succesful after all. */
2607 goto finally;
2610 ret = PyTuple_Pack(2, buf, addr);
2612 finally:
2613 Py_XDECREF(buf);
2614 Py_XDECREF(addr);
2615 return ret;
2618 PyDoc_STRVAR(recvfrom_doc,
2619 "recvfrom(buffersize[, flags]) -> (data, address info)\n\
2621 Like recv(buffersize, flags) but also return the sender's address info.");
2624 /* s.recvfrom_into(buffer[, nbytes [,flags]]) method */
2626 static PyObject *
2627 sock_recvfrom_into(PySocketSockObject *s, PyObject *args, PyObject* kwds)
2629 static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
2631 int recvlen = 0, flags = 0;
2632 ssize_t readlen;
2633 Py_buffer buf;
2634 int buflen;
2636 PyObject *addr = NULL;
2638 if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recvfrom_into",
2639 kwlist, &buf,
2640 &recvlen, &flags))
2641 return NULL;
2642 buflen = buf.len;
2643 assert(buf.buf != 0 && buflen > 0);
2645 if (recvlen < 0) {
2646 PyErr_SetString(PyExc_ValueError,
2647 "negative buffersize in recvfrom_into");
2648 goto error;
2650 if (recvlen == 0) {
2651 /* If nbytes was not specified, use the buffer's length */
2652 recvlen = buflen;
2655 readlen = sock_recvfrom_guts(s, buf.buf, recvlen, flags, &addr);
2656 if (readlen < 0) {
2657 /* Return an error */
2658 goto error;
2661 PyBuffer_Release(&buf);
2662 /* Return the number of bytes read and the address. Note that we do
2663 not do anything special here in the case that readlen < recvlen. */
2664 return Py_BuildValue("lN", readlen, addr);
2666 error:
2667 Py_XDECREF(addr);
2668 PyBuffer_Release(&buf);
2669 return NULL;
2672 PyDoc_STRVAR(recvfrom_into_doc,
2673 "recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)\n\
2675 Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.");
2678 /* s.send(data [,flags]) method */
2680 static PyObject *
2681 sock_send(PySocketSockObject *s, PyObject *args)
2683 char *buf;
2684 int len, n = -1, flags = 0, timeout;
2685 Py_buffer pbuf;
2687 if (!PyArg_ParseTuple(args, "s*|i:send", &pbuf, &flags))
2688 return NULL;
2690 if (!IS_SELECTABLE(s)) {
2691 PyBuffer_Release(&pbuf);
2692 return select_error();
2694 buf = pbuf.buf;
2695 len = pbuf.len;
2697 Py_BEGIN_ALLOW_THREADS
2698 timeout = internal_select(s, 1);
2699 if (!timeout)
2700 #ifdef __VMS
2701 n = sendsegmented(s->sock_fd, buf, len, flags);
2702 #else
2703 n = send(s->sock_fd, buf, len, flags);
2704 #endif
2705 Py_END_ALLOW_THREADS
2707 PyBuffer_Release(&pbuf);
2709 if (timeout == 1) {
2710 PyErr_SetString(socket_timeout, "timed out");
2711 return NULL;
2713 if (n < 0)
2714 return s->errorhandler();
2715 return PyInt_FromLong((long)n);
2718 PyDoc_STRVAR(send_doc,
2719 "send(data[, flags]) -> count\n\
2721 Send a data string to the socket. For the optional flags\n\
2722 argument, see the Unix manual. Return the number of bytes\n\
2723 sent; this may be less than len(data) if the network is busy.");
2726 /* s.sendall(data [,flags]) method */
2728 static PyObject *
2729 sock_sendall(PySocketSockObject *s, PyObject *args)
2731 char *buf;
2732 int len, n = -1, flags = 0, timeout;
2733 Py_buffer pbuf;
2735 if (!PyArg_ParseTuple(args, "s*|i:sendall", &pbuf, &flags))
2736 return NULL;
2737 buf = pbuf.buf;
2738 len = pbuf.len;
2740 if (!IS_SELECTABLE(s)) {
2741 PyBuffer_Release(&pbuf);
2742 return select_error();
2745 Py_BEGIN_ALLOW_THREADS
2746 do {
2747 timeout = internal_select(s, 1);
2748 n = -1;
2749 if (timeout)
2750 break;
2751 #ifdef __VMS
2752 n = sendsegmented(s->sock_fd, buf, len, flags);
2753 #else
2754 n = send(s->sock_fd, buf, len, flags);
2755 #endif
2756 if (n < 0) {
2757 #ifdef EINTR
2758 /* We must handle EINTR here as there is no way for
2759 * the caller to know how much was sent otherwise. */
2760 if (errno == EINTR) {
2761 /* Run signal handlers. If an exception was
2762 * raised, abort and leave this socket in
2763 * an unknown state. */
2764 if (PyErr_CheckSignals())
2765 return NULL;
2766 continue;
2768 #endif
2769 break;
2771 buf += n;
2772 len -= n;
2773 } while (len > 0);
2774 Py_END_ALLOW_THREADS
2775 PyBuffer_Release(&pbuf);
2777 if (timeout == 1) {
2778 PyErr_SetString(socket_timeout, "timed out");
2779 return NULL;
2781 if (n < 0)
2782 return s->errorhandler();
2784 Py_INCREF(Py_None);
2785 return Py_None;
2788 PyDoc_STRVAR(sendall_doc,
2789 "sendall(data[, flags])\n\
2791 Send a data string to the socket. For the optional flags\n\
2792 argument, see the Unix manual. This calls send() repeatedly\n\
2793 until all data is sent. If an error occurs, it's impossible\n\
2794 to tell how much data has been sent.");
2797 /* s.sendto(data, [flags,] sockaddr) method */
2799 static PyObject *
2800 sock_sendto(PySocketSockObject *s, PyObject *args)
2802 Py_buffer pbuf;
2803 PyObject *addro;
2804 char *buf;
2805 Py_ssize_t len;
2806 sock_addr_t addrbuf;
2807 int addrlen, n = -1, flags, timeout;
2809 flags = 0;
2810 if (!PyArg_ParseTuple(args, "s*O:sendto", &pbuf, &addro)) {
2811 PyErr_Clear();
2812 if (!PyArg_ParseTuple(args, "s*iO:sendto",
2813 &pbuf, &flags, &addro))
2814 return NULL;
2816 buf = pbuf.buf;
2817 len = pbuf.len;
2819 if (!IS_SELECTABLE(s)) {
2820 PyBuffer_Release(&pbuf);
2821 return select_error();
2824 if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) {
2825 PyBuffer_Release(&pbuf);
2826 return NULL;
2829 Py_BEGIN_ALLOW_THREADS
2830 timeout = internal_select(s, 1);
2831 if (!timeout)
2832 n = sendto(s->sock_fd, buf, len, flags, SAS2SA(&addrbuf), addrlen);
2833 Py_END_ALLOW_THREADS
2835 PyBuffer_Release(&pbuf);
2836 if (timeout == 1) {
2837 PyErr_SetString(socket_timeout, "timed out");
2838 return NULL;
2840 if (n < 0)
2841 return s->errorhandler();
2842 return PyInt_FromLong((long)n);
2845 PyDoc_STRVAR(sendto_doc,
2846 "sendto(data[, flags], address) -> count\n\
2848 Like send(data, flags) but allows specifying the destination address.\n\
2849 For IP sockets, the address is a pair (hostaddr, port).");
2852 /* s.shutdown(how) method */
2854 static PyObject *
2855 sock_shutdown(PySocketSockObject *s, PyObject *arg)
2857 int how;
2858 int res;
2860 how = PyInt_AsLong(arg);
2861 if (how == -1 && PyErr_Occurred())
2862 return NULL;
2863 Py_BEGIN_ALLOW_THREADS
2864 res = shutdown(s->sock_fd, how);
2865 Py_END_ALLOW_THREADS
2866 if (res < 0)
2867 return s->errorhandler();
2868 Py_INCREF(Py_None);
2869 return Py_None;
2872 PyDoc_STRVAR(shutdown_doc,
2873 "shutdown(flag)\n\
2875 Shut down the reading side of the socket (flag == SHUT_RD), the writing side\n\
2876 of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).");
2878 #if defined(MS_WINDOWS) && defined(SIO_RCVALL)
2879 static PyObject*
2880 sock_ioctl(PySocketSockObject *s, PyObject *arg)
2882 unsigned long cmd = SIO_RCVALL;
2883 PyObject *argO;
2884 DWORD recv;
2886 if (!PyArg_ParseTuple(arg, "kO:ioctl", &cmd, &argO))
2887 return NULL;
2889 switch (cmd) {
2890 case SIO_RCVALL: {
2891 unsigned int option = RCVALL_ON;
2892 if (!PyArg_ParseTuple(arg, "kI:ioctl", &cmd, &option))
2893 return NULL;
2894 if (WSAIoctl(s->sock_fd, cmd, &option, sizeof(option),
2895 NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
2896 return set_error();
2898 return PyLong_FromUnsignedLong(recv); }
2899 case SIO_KEEPALIVE_VALS: {
2900 struct tcp_keepalive ka;
2901 if (!PyArg_ParseTuple(arg, "k(kkk):ioctl", &cmd,
2902 &ka.onoff, &ka.keepalivetime, &ka.keepaliveinterval))
2903 return NULL;
2904 if (WSAIoctl(s->sock_fd, cmd, &ka, sizeof(ka),
2905 NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
2906 return set_error();
2908 return PyLong_FromUnsignedLong(recv); }
2909 default:
2910 PyErr_Format(PyExc_ValueError, "invalid ioctl command %d", cmd);
2911 return NULL;
2914 PyDoc_STRVAR(sock_ioctl_doc,
2915 "ioctl(cmd, option) -> long\n\
2917 Control the socket with WSAIoctl syscall. Currently supported 'cmd' values are\n\
2918 SIO_RCVALL: 'option' must be one of the socket.RCVALL_* constants.\n\
2919 SIO_KEEPALIVE_VALS: 'option' is a tuple of (onoff, timeout, interval).");
2921 #endif
2923 /* List of methods for socket objects */
2925 static PyMethodDef sock_methods[] = {
2926 {"accept", (PyCFunction)sock_accept, METH_NOARGS,
2927 accept_doc},
2928 {"bind", (PyCFunction)sock_bind, METH_O,
2929 bind_doc},
2930 {"close", (PyCFunction)sock_close, METH_NOARGS,
2931 close_doc},
2932 {"connect", (PyCFunction)sock_connect, METH_O,
2933 connect_doc},
2934 {"connect_ex", (PyCFunction)sock_connect_ex, METH_O,
2935 connect_ex_doc},
2936 #ifndef NO_DUP
2937 {"dup", (PyCFunction)sock_dup, METH_NOARGS,
2938 dup_doc},
2939 #endif
2940 {"fileno", (PyCFunction)sock_fileno, METH_NOARGS,
2941 fileno_doc},
2942 #ifdef HAVE_GETPEERNAME
2943 {"getpeername", (PyCFunction)sock_getpeername,
2944 METH_NOARGS, getpeername_doc},
2945 #endif
2946 {"getsockname", (PyCFunction)sock_getsockname,
2947 METH_NOARGS, getsockname_doc},
2948 {"getsockopt", (PyCFunction)sock_getsockopt, METH_VARARGS,
2949 getsockopt_doc},
2950 #if defined(MS_WINDOWS) && defined(SIO_RCVALL)
2951 {"ioctl", (PyCFunction)sock_ioctl, METH_VARARGS,
2952 sock_ioctl_doc},
2953 #endif
2954 {"listen", (PyCFunction)sock_listen, METH_O,
2955 listen_doc},
2956 #ifndef NO_DUP
2957 {"makefile", (PyCFunction)sock_makefile, METH_VARARGS,
2958 makefile_doc},
2959 #endif
2960 {"recv", (PyCFunction)sock_recv, METH_VARARGS,
2961 recv_doc},
2962 {"recv_into", (PyCFunction)sock_recv_into, METH_VARARGS | METH_KEYWORDS,
2963 recv_into_doc},
2964 {"recvfrom", (PyCFunction)sock_recvfrom, METH_VARARGS,
2965 recvfrom_doc},
2966 {"recvfrom_into", (PyCFunction)sock_recvfrom_into, METH_VARARGS | METH_KEYWORDS,
2967 recvfrom_into_doc},
2968 {"send", (PyCFunction)sock_send, METH_VARARGS,
2969 send_doc},
2970 {"sendall", (PyCFunction)sock_sendall, METH_VARARGS,
2971 sendall_doc},
2972 {"sendto", (PyCFunction)sock_sendto, METH_VARARGS,
2973 sendto_doc},
2974 {"setblocking", (PyCFunction)sock_setblocking, METH_O,
2975 setblocking_doc},
2976 {"settimeout", (PyCFunction)sock_settimeout, METH_O,
2977 settimeout_doc},
2978 {"gettimeout", (PyCFunction)sock_gettimeout, METH_NOARGS,
2979 gettimeout_doc},
2980 {"setsockopt", (PyCFunction)sock_setsockopt, METH_VARARGS,
2981 setsockopt_doc},
2982 {"shutdown", (PyCFunction)sock_shutdown, METH_O,
2983 shutdown_doc},
2984 #ifdef RISCOS
2985 {"sleeptaskw", (PyCFunction)sock_sleeptaskw, METH_O,
2986 sleeptaskw_doc},
2987 #endif
2988 {NULL, NULL} /* sentinel */
2991 /* SockObject members */
2992 static PyMemberDef sock_memberlist[] = {
2993 {"family", T_INT, offsetof(PySocketSockObject, sock_family), READONLY, "the socket family"},
2994 {"type", T_INT, offsetof(PySocketSockObject, sock_type), READONLY, "the socket type"},
2995 {"proto", T_INT, offsetof(PySocketSockObject, sock_proto), READONLY, "the socket protocol"},
2996 {"timeout", T_DOUBLE, offsetof(PySocketSockObject, sock_timeout), READONLY, "the socket timeout"},
2997 {0},
3000 /* Deallocate a socket object in response to the last Py_DECREF().
3001 First close the file description. */
3003 static void
3004 sock_dealloc(PySocketSockObject *s)
3006 if (s->sock_fd != -1)
3007 (void) SOCKETCLOSE(s->sock_fd);
3008 Py_TYPE(s)->tp_free((PyObject *)s);
3012 static PyObject *
3013 sock_repr(PySocketSockObject *s)
3015 char buf[512];
3016 #if SIZEOF_SOCKET_T > SIZEOF_LONG
3017 if (s->sock_fd > LONG_MAX) {
3018 /* this can occur on Win64, and actually there is a special
3019 ugly printf formatter for decimal pointer length integer
3020 printing, only bother if necessary*/
3021 PyErr_SetString(PyExc_OverflowError,
3022 "no printf formatter to display "
3023 "the socket descriptor in decimal");
3024 return NULL;
3026 #endif
3027 PyOS_snprintf(
3028 buf, sizeof(buf),
3029 "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
3030 (long)s->sock_fd, s->sock_family,
3031 s->sock_type,
3032 s->sock_proto);
3033 return PyString_FromString(buf);
3037 /* Create a new, uninitialized socket object. */
3039 static PyObject *
3040 sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3042 PyObject *new;
3044 new = type->tp_alloc(type, 0);
3045 if (new != NULL) {
3046 ((PySocketSockObject *)new)->sock_fd = -1;
3047 ((PySocketSockObject *)new)->sock_timeout = -1.0;
3048 ((PySocketSockObject *)new)->errorhandler = &set_error;
3050 return new;
3054 /* Initialize a new socket object. */
3056 /*ARGSUSED*/
3057 static int
3058 sock_initobj(PyObject *self, PyObject *args, PyObject *kwds)
3060 PySocketSockObject *s = (PySocketSockObject *)self;
3061 SOCKET_T fd;
3062 int family = AF_INET, type = SOCK_STREAM, proto = 0;
3063 static char *keywords[] = {"family", "type", "proto", 0};
3065 if (!PyArg_ParseTupleAndKeywords(args, kwds,
3066 "|iii:socket", keywords,
3067 &family, &type, &proto))
3068 return -1;
3070 Py_BEGIN_ALLOW_THREADS
3071 fd = socket(family, type, proto);
3072 Py_END_ALLOW_THREADS
3074 #ifdef MS_WINDOWS
3075 if (fd == INVALID_SOCKET)
3076 #else
3077 if (fd < 0)
3078 #endif
3080 set_error();
3081 return -1;
3083 init_sockobject(s, fd, family, type, proto);
3085 return 0;
3090 /* Type object for socket objects. */
3092 static PyTypeObject sock_type = {
3093 PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */
3094 "_socket.socket", /* tp_name */
3095 sizeof(PySocketSockObject), /* tp_basicsize */
3096 0, /* tp_itemsize */
3097 (destructor)sock_dealloc, /* tp_dealloc */
3098 0, /* tp_print */
3099 0, /* tp_getattr */
3100 0, /* tp_setattr */
3101 0, /* tp_compare */
3102 (reprfunc)sock_repr, /* tp_repr */
3103 0, /* tp_as_number */
3104 0, /* tp_as_sequence */
3105 0, /* tp_as_mapping */
3106 0, /* tp_hash */
3107 0, /* tp_call */
3108 0, /* tp_str */
3109 PyObject_GenericGetAttr, /* tp_getattro */
3110 0, /* tp_setattro */
3111 0, /* tp_as_buffer */
3112 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3113 sock_doc, /* tp_doc */
3114 0, /* tp_traverse */
3115 0, /* tp_clear */
3116 0, /* tp_richcompare */
3117 0, /* tp_weaklistoffset */
3118 0, /* tp_iter */
3119 0, /* tp_iternext */
3120 sock_methods, /* tp_methods */
3121 sock_memberlist, /* tp_members */
3122 0, /* tp_getset */
3123 0, /* tp_base */
3124 0, /* tp_dict */
3125 0, /* tp_descr_get */
3126 0, /* tp_descr_set */
3127 0, /* tp_dictoffset */
3128 sock_initobj, /* tp_init */
3129 PyType_GenericAlloc, /* tp_alloc */
3130 sock_new, /* tp_new */
3131 PyObject_Del, /* tp_free */
3135 /* Python interface to gethostname(). */
3137 /*ARGSUSED*/
3138 static PyObject *
3139 socket_gethostname(PyObject *self, PyObject *unused)
3141 char buf[1024];
3142 int res;
3143 Py_BEGIN_ALLOW_THREADS
3144 res = gethostname(buf, (int) sizeof buf - 1);
3145 Py_END_ALLOW_THREADS
3146 if (res < 0)
3147 return set_error();
3148 buf[sizeof buf - 1] = '\0';
3149 return PyString_FromString(buf);
3152 PyDoc_STRVAR(gethostname_doc,
3153 "gethostname() -> string\n\
3155 Return the current host name.");
3158 /* Python interface to gethostbyname(name). */
3160 /*ARGSUSED*/
3161 static PyObject *
3162 socket_gethostbyname(PyObject *self, PyObject *args)
3164 char *name;
3165 sock_addr_t addrbuf;
3167 if (!PyArg_ParseTuple(args, "s:gethostbyname", &name))
3168 return NULL;
3169 if (setipaddr(name, SAS2SA(&addrbuf), sizeof(addrbuf), AF_INET) < 0)
3170 return NULL;
3171 return makeipaddr(SAS2SA(&addrbuf), sizeof(struct sockaddr_in));
3174 PyDoc_STRVAR(gethostbyname_doc,
3175 "gethostbyname(host) -> address\n\
3177 Return the IP address (a string of the form '255.255.255.255') for a host.");
3180 /* Convenience function common to gethostbyname_ex and gethostbyaddr */
3182 static PyObject *
3183 gethost_common(struct hostent *h, struct sockaddr *addr, int alen, int af)
3185 char **pch;
3186 PyObject *rtn_tuple = (PyObject *)NULL;
3187 PyObject *name_list = (PyObject *)NULL;
3188 PyObject *addr_list = (PyObject *)NULL;
3189 PyObject *tmp;
3191 if (h == NULL) {
3192 /* Let's get real error message to return */
3193 #ifndef RISCOS
3194 set_herror(h_errno);
3195 #else
3196 PyErr_SetString(socket_error, "host not found");
3197 #endif
3198 return NULL;
3201 if (h->h_addrtype != af) {
3202 /* Let's get real error message to return */
3203 PyErr_SetString(socket_error,
3204 (char *)strerror(EAFNOSUPPORT));
3206 return NULL;
3209 switch (af) {
3211 case AF_INET:
3212 if (alen < sizeof(struct sockaddr_in))
3213 return NULL;
3214 break;
3216 #ifdef ENABLE_IPV6
3217 case AF_INET6:
3218 if (alen < sizeof(struct sockaddr_in6))
3219 return NULL;
3220 break;
3221 #endif
3225 if ((name_list = PyList_New(0)) == NULL)
3226 goto err;
3228 if ((addr_list = PyList_New(0)) == NULL)
3229 goto err;
3231 /* SF #1511317: h_aliases can be NULL */
3232 if (h->h_aliases) {
3233 for (pch = h->h_aliases; *pch != NULL; pch++) {
3234 int status;
3235 tmp = PyString_FromString(*pch);
3236 if (tmp == NULL)
3237 goto err;
3239 status = PyList_Append(name_list, tmp);
3240 Py_DECREF(tmp);
3242 if (status)
3243 goto err;
3247 for (pch = h->h_addr_list; *pch != NULL; pch++) {
3248 int status;
3250 switch (af) {
3252 case AF_INET:
3254 struct sockaddr_in sin;
3255 memset(&sin, 0, sizeof(sin));
3256 sin.sin_family = af;
3257 #ifdef HAVE_SOCKADDR_SA_LEN
3258 sin.sin_len = sizeof(sin);
3259 #endif
3260 memcpy(&sin.sin_addr, *pch, sizeof(sin.sin_addr));
3261 tmp = makeipaddr((struct sockaddr *)&sin, sizeof(sin));
3263 if (pch == h->h_addr_list && alen >= sizeof(sin))
3264 memcpy((char *) addr, &sin, sizeof(sin));
3265 break;
3268 #ifdef ENABLE_IPV6
3269 case AF_INET6:
3271 struct sockaddr_in6 sin6;
3272 memset(&sin6, 0, sizeof(sin6));
3273 sin6.sin6_family = af;
3274 #ifdef HAVE_SOCKADDR_SA_LEN
3275 sin6.sin6_len = sizeof(sin6);
3276 #endif
3277 memcpy(&sin6.sin6_addr, *pch, sizeof(sin6.sin6_addr));
3278 tmp = makeipaddr((struct sockaddr *)&sin6,
3279 sizeof(sin6));
3281 if (pch == h->h_addr_list && alen >= sizeof(sin6))
3282 memcpy((char *) addr, &sin6, sizeof(sin6));
3283 break;
3285 #endif
3287 default: /* can't happen */
3288 PyErr_SetString(socket_error,
3289 "unsupported address family");
3290 return NULL;
3293 if (tmp == NULL)
3294 goto err;
3296 status = PyList_Append(addr_list, tmp);
3297 Py_DECREF(tmp);
3299 if (status)
3300 goto err;
3303 rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list);
3305 err:
3306 Py_XDECREF(name_list);
3307 Py_XDECREF(addr_list);
3308 return rtn_tuple;
3312 /* Python interface to gethostbyname_ex(name). */
3314 /*ARGSUSED*/
3315 static PyObject *
3316 socket_gethostbyname_ex(PyObject *self, PyObject *args)
3318 char *name;
3319 struct hostent *h;
3320 #ifdef ENABLE_IPV6
3321 struct sockaddr_storage addr;
3322 #else
3323 struct sockaddr_in addr;
3324 #endif
3325 struct sockaddr *sa;
3326 PyObject *ret;
3327 #ifdef HAVE_GETHOSTBYNAME_R
3328 struct hostent hp_allocated;
3329 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
3330 struct hostent_data data;
3331 #else
3332 char buf[16384];
3333 int buf_len = (sizeof buf) - 1;
3334 int errnop;
3335 #endif
3336 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3337 int result;
3338 #endif
3339 #endif /* HAVE_GETHOSTBYNAME_R */
3341 if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name))
3342 return NULL;
3343 if (setipaddr(name, (struct sockaddr *)&addr, sizeof(addr), AF_INET) < 0)
3344 return NULL;
3345 Py_BEGIN_ALLOW_THREADS
3346 #ifdef HAVE_GETHOSTBYNAME_R
3347 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3348 result = gethostbyname_r(name, &hp_allocated, buf, buf_len,
3349 &h, &errnop);
3350 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
3351 h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
3352 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
3353 memset((void *) &data, '\0', sizeof(data));
3354 result = gethostbyname_r(name, &hp_allocated, &data);
3355 h = (result != 0) ? NULL : &hp_allocated;
3356 #endif
3357 #else /* not HAVE_GETHOSTBYNAME_R */
3358 #ifdef USE_GETHOSTBYNAME_LOCK
3359 PyThread_acquire_lock(netdb_lock, 1);
3360 #endif
3361 h = gethostbyname(name);
3362 #endif /* HAVE_GETHOSTBYNAME_R */
3363 Py_END_ALLOW_THREADS
3364 /* Some C libraries would require addr.__ss_family instead of
3365 addr.ss_family.
3366 Therefore, we cast the sockaddr_storage into sockaddr to
3367 access sa_family. */
3368 sa = (struct sockaddr*)&addr;
3369 ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr),
3370 sa->sa_family);
3371 #ifdef USE_GETHOSTBYNAME_LOCK
3372 PyThread_release_lock(netdb_lock);
3373 #endif
3374 return ret;
3377 PyDoc_STRVAR(ghbn_ex_doc,
3378 "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
3380 Return the true host name, a list of aliases, and a list of IP addresses,\n\
3381 for a host. The host argument is a string giving a host name or IP number.");
3384 /* Python interface to gethostbyaddr(IP). */
3386 /*ARGSUSED*/
3387 static PyObject *
3388 socket_gethostbyaddr(PyObject *self, PyObject *args)
3390 #ifdef ENABLE_IPV6
3391 struct sockaddr_storage addr;
3392 #else
3393 struct sockaddr_in addr;
3394 #endif
3395 struct sockaddr *sa = (struct sockaddr *)&addr;
3396 char *ip_num;
3397 struct hostent *h;
3398 PyObject *ret;
3399 #ifdef HAVE_GETHOSTBYNAME_R
3400 struct hostent hp_allocated;
3401 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
3402 struct hostent_data data;
3403 #else
3404 /* glibcs up to 2.10 assume that the buf argument to
3405 gethostbyaddr_r is 8-byte aligned, which at least llvm-gcc
3406 does not ensure. The attribute below instructs the compiler
3407 to maintain this alignment. */
3408 char buf[16384] Py_ALIGNED(8);
3409 int buf_len = (sizeof buf) - 1;
3410 int errnop;
3411 #endif
3412 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3413 int result;
3414 #endif
3415 #endif /* HAVE_GETHOSTBYNAME_R */
3416 char *ap;
3417 int al;
3418 int af;
3420 if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num))
3421 return NULL;
3422 af = AF_UNSPEC;
3423 if (setipaddr(ip_num, sa, sizeof(addr), af) < 0)
3424 return NULL;
3425 af = sa->sa_family;
3426 ap = NULL;
3427 switch (af) {
3428 case AF_INET:
3429 ap = (char *)&((struct sockaddr_in *)sa)->sin_addr;
3430 al = sizeof(((struct sockaddr_in *)sa)->sin_addr);
3431 break;
3432 #ifdef ENABLE_IPV6
3433 case AF_INET6:
3434 ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr;
3435 al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr);
3436 break;
3437 #endif
3438 default:
3439 PyErr_SetString(socket_error, "unsupported address family");
3440 return NULL;
3442 Py_BEGIN_ALLOW_THREADS
3443 #ifdef HAVE_GETHOSTBYNAME_R
3444 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3445 result = gethostbyaddr_r(ap, al, af,
3446 &hp_allocated, buf, buf_len,
3447 &h, &errnop);
3448 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
3449 h = gethostbyaddr_r(ap, al, af,
3450 &hp_allocated, buf, buf_len, &errnop);
3451 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
3452 memset((void *) &data, '\0', sizeof(data));
3453 result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data);
3454 h = (result != 0) ? NULL : &hp_allocated;
3455 #endif
3456 #else /* not HAVE_GETHOSTBYNAME_R */
3457 #ifdef USE_GETHOSTBYNAME_LOCK
3458 PyThread_acquire_lock(netdb_lock, 1);
3459 #endif
3460 h = gethostbyaddr(ap, al, af);
3461 #endif /* HAVE_GETHOSTBYNAME_R */
3462 Py_END_ALLOW_THREADS
3463 ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), af);
3464 #ifdef USE_GETHOSTBYNAME_LOCK
3465 PyThread_release_lock(netdb_lock);
3466 #endif
3467 return ret;
3470 PyDoc_STRVAR(gethostbyaddr_doc,
3471 "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
3473 Return the true host name, a list of aliases, and a list of IP addresses,\n\
3474 for a host. The host argument is a string giving a host name or IP number.");
3477 /* Python interface to getservbyname(name).
3478 This only returns the port number, since the other info is already
3479 known or not useful (like the list of aliases). */
3481 /*ARGSUSED*/
3482 static PyObject *
3483 socket_getservbyname(PyObject *self, PyObject *args)
3485 char *name, *proto=NULL;
3486 struct servent *sp;
3487 if (!PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto))
3488 return NULL;
3489 Py_BEGIN_ALLOW_THREADS
3490 sp = getservbyname(name, proto);
3491 Py_END_ALLOW_THREADS
3492 if (sp == NULL) {
3493 PyErr_SetString(socket_error, "service/proto not found");
3494 return NULL;
3496 return PyInt_FromLong((long) ntohs(sp->s_port));
3499 PyDoc_STRVAR(getservbyname_doc,
3500 "getservbyname(servicename[, protocolname]) -> integer\n\
3502 Return a port number from a service name and protocol name.\n\
3503 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3504 otherwise any protocol will match.");
3507 /* Python interface to getservbyport(port).
3508 This only returns the service name, since the other info is already
3509 known or not useful (like the list of aliases). */
3511 /*ARGSUSED*/
3512 static PyObject *
3513 socket_getservbyport(PyObject *self, PyObject *args)
3515 int port;
3516 char *proto=NULL;
3517 struct servent *sp;
3518 if (!PyArg_ParseTuple(args, "i|s:getservbyport", &port, &proto))
3519 return NULL;
3520 if (port < 0 || port > 0xffff) {
3521 PyErr_SetString(
3522 PyExc_OverflowError,
3523 "getservbyport: port must be 0-65535.");
3524 return NULL;
3526 Py_BEGIN_ALLOW_THREADS
3527 sp = getservbyport(htons((short)port), proto);
3528 Py_END_ALLOW_THREADS
3529 if (sp == NULL) {
3530 PyErr_SetString(socket_error, "port/proto not found");
3531 return NULL;
3533 return PyString_FromString(sp->s_name);
3536 PyDoc_STRVAR(getservbyport_doc,
3537 "getservbyport(port[, protocolname]) -> string\n\
3539 Return the service name from a port number and protocol name.\n\
3540 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3541 otherwise any protocol will match.");
3543 /* Python interface to getprotobyname(name).
3544 This only returns the protocol number, since the other info is
3545 already known or not useful (like the list of aliases). */
3547 /*ARGSUSED*/
3548 static PyObject *
3549 socket_getprotobyname(PyObject *self, PyObject *args)
3551 char *name;
3552 struct protoent *sp;
3553 #ifdef __BEOS__
3554 /* Not available in BeOS yet. - [cjh] */
3555 PyErr_SetString(socket_error, "getprotobyname not supported");
3556 return NULL;
3557 #else
3558 if (!PyArg_ParseTuple(args, "s:getprotobyname", &name))
3559 return NULL;
3560 Py_BEGIN_ALLOW_THREADS
3561 sp = getprotobyname(name);
3562 Py_END_ALLOW_THREADS
3563 if (sp == NULL) {
3564 PyErr_SetString(socket_error, "protocol not found");
3565 return NULL;
3567 return PyInt_FromLong((long) sp->p_proto);
3568 #endif
3571 PyDoc_STRVAR(getprotobyname_doc,
3572 "getprotobyname(name) -> integer\n\
3574 Return the protocol number for the named protocol. (Rarely used.)");
3577 #ifdef HAVE_SOCKETPAIR
3578 /* Create a pair of sockets using the socketpair() function.
3579 Arguments as for socket() except the default family is AF_UNIX if
3580 defined on the platform; otherwise, the default is AF_INET. */
3582 /*ARGSUSED*/
3583 static PyObject *
3584 socket_socketpair(PyObject *self, PyObject *args)
3586 PySocketSockObject *s0 = NULL, *s1 = NULL;
3587 SOCKET_T sv[2];
3588 int family, type = SOCK_STREAM, proto = 0;
3589 PyObject *res = NULL;
3591 #if defined(AF_UNIX)
3592 family = AF_UNIX;
3593 #else
3594 family = AF_INET;
3595 #endif
3596 if (!PyArg_ParseTuple(args, "|iii:socketpair",
3597 &family, &type, &proto))
3598 return NULL;
3599 /* Create a pair of socket fds */
3600 if (socketpair(family, type, proto, sv) < 0)
3601 return set_error();
3602 s0 = new_sockobject(sv[0], family, type, proto);
3603 if (s0 == NULL)
3604 goto finally;
3605 s1 = new_sockobject(sv[1], family, type, proto);
3606 if (s1 == NULL)
3607 goto finally;
3608 res = PyTuple_Pack(2, s0, s1);
3610 finally:
3611 if (res == NULL) {
3612 if (s0 == NULL)
3613 SOCKETCLOSE(sv[0]);
3614 if (s1 == NULL)
3615 SOCKETCLOSE(sv[1]);
3617 Py_XDECREF(s0);
3618 Py_XDECREF(s1);
3619 return res;
3622 PyDoc_STRVAR(socketpair_doc,
3623 "socketpair([family[, type[, proto]]]) -> (socket object, socket object)\n\
3625 Create a pair of socket objects from the sockets returned by the platform\n\
3626 socketpair() function.\n\
3627 The arguments are the same as for socket() except the default family is\n\
3628 AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");
3630 #endif /* HAVE_SOCKETPAIR */
3633 #ifndef NO_DUP
3634 /* Create a socket object from a numeric file description.
3635 Useful e.g. if stdin is a socket.
3636 Additional arguments as for socket(). */
3638 /*ARGSUSED*/
3639 static PyObject *
3640 socket_fromfd(PyObject *self, PyObject *args)
3642 PySocketSockObject *s;
3643 SOCKET_T fd;
3644 int family, type, proto = 0;
3645 if (!PyArg_ParseTuple(args, "iii|i:fromfd",
3646 &fd, &family, &type, &proto))
3647 return NULL;
3648 /* Dup the fd so it and the socket can be closed independently */
3649 fd = dup(fd);
3650 if (fd < 0)
3651 return set_error();
3652 s = new_sockobject(fd, family, type, proto);
3653 return (PyObject *) s;
3656 PyDoc_STRVAR(fromfd_doc,
3657 "fromfd(fd, family, type[, proto]) -> socket object\n\
3659 Create a socket object from a duplicate of the given\n\
3660 file descriptor.\n\
3661 The remaining arguments are the same as for socket().");
3663 #endif /* NO_DUP */
3666 static PyObject *
3667 socket_ntohs(PyObject *self, PyObject *args)
3669 int x1, x2;
3671 if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) {
3672 return NULL;
3674 if (x1 < 0) {
3675 PyErr_SetString(PyExc_OverflowError,
3676 "can't convert negative number to unsigned long");
3677 return NULL;
3679 x2 = (unsigned int)ntohs((unsigned short)x1);
3680 return PyInt_FromLong(x2);
3683 PyDoc_STRVAR(ntohs_doc,
3684 "ntohs(integer) -> integer\n\
3686 Convert a 16-bit integer from network to host byte order.");
3689 static PyObject *
3690 socket_ntohl(PyObject *self, PyObject *arg)
3692 unsigned long x;
3694 if (PyInt_Check(arg)) {
3695 x = PyInt_AS_LONG(arg);
3696 if (x == (unsigned long) -1 && PyErr_Occurred())
3697 return NULL;
3698 if ((long)x < 0) {
3699 PyErr_SetString(PyExc_OverflowError,
3700 "can't convert negative number to unsigned long");
3701 return NULL;
3704 else if (PyLong_Check(arg)) {
3705 x = PyLong_AsUnsignedLong(arg);
3706 if (x == (unsigned long) -1 && PyErr_Occurred())
3707 return NULL;
3708 #if SIZEOF_LONG > 4
3710 unsigned long y;
3711 /* only want the trailing 32 bits */
3712 y = x & 0xFFFFFFFFUL;
3713 if (y ^ x)
3714 return PyErr_Format(PyExc_OverflowError,
3715 "long int larger than 32 bits");
3716 x = y;
3718 #endif
3720 else
3721 return PyErr_Format(PyExc_TypeError,
3722 "expected int/long, %s found",
3723 Py_TYPE(arg)->tp_name);
3724 if (x == (unsigned long) -1 && PyErr_Occurred())
3725 return NULL;
3726 return PyLong_FromUnsignedLong(ntohl(x));
3729 PyDoc_STRVAR(ntohl_doc,
3730 "ntohl(integer) -> integer\n\
3732 Convert a 32-bit integer from network to host byte order.");
3735 static PyObject *
3736 socket_htons(PyObject *self, PyObject *args)
3738 int x1, x2;
3740 if (!PyArg_ParseTuple(args, "i:htons", &x1)) {
3741 return NULL;
3743 if (x1 < 0) {
3744 PyErr_SetString(PyExc_OverflowError,
3745 "can't convert negative number to unsigned long");
3746 return NULL;
3748 x2 = (unsigned int)htons((unsigned short)x1);
3749 return PyInt_FromLong(x2);
3752 PyDoc_STRVAR(htons_doc,
3753 "htons(integer) -> integer\n\
3755 Convert a 16-bit integer from host to network byte order.");
3758 static PyObject *
3759 socket_htonl(PyObject *self, PyObject *arg)
3761 unsigned long x;
3763 if (PyInt_Check(arg)) {
3764 x = PyInt_AS_LONG(arg);
3765 if (x == (unsigned long) -1 && PyErr_Occurred())
3766 return NULL;
3767 if ((long)x < 0) {
3768 PyErr_SetString(PyExc_OverflowError,
3769 "can't convert negative number to unsigned long");
3770 return NULL;
3773 else if (PyLong_Check(arg)) {
3774 x = PyLong_AsUnsignedLong(arg);
3775 if (x == (unsigned long) -1 && PyErr_Occurred())
3776 return NULL;
3777 #if SIZEOF_LONG > 4
3779 unsigned long y;
3780 /* only want the trailing 32 bits */
3781 y = x & 0xFFFFFFFFUL;
3782 if (y ^ x)
3783 return PyErr_Format(PyExc_OverflowError,
3784 "long int larger than 32 bits");
3785 x = y;
3787 #endif
3789 else
3790 return PyErr_Format(PyExc_TypeError,
3791 "expected int/long, %s found",
3792 Py_TYPE(arg)->tp_name);
3793 return PyLong_FromUnsignedLong(htonl((unsigned long)x));
3796 PyDoc_STRVAR(htonl_doc,
3797 "htonl(integer) -> integer\n\
3799 Convert a 32-bit integer from host to network byte order.");
3801 /* socket.inet_aton() and socket.inet_ntoa() functions. */
3803 PyDoc_STRVAR(inet_aton_doc,
3804 "inet_aton(string) -> packed 32-bit IP representation\n\
3806 Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
3807 binary format used in low-level network functions.");
3809 static PyObject*
3810 socket_inet_aton(PyObject *self, PyObject *args)
3812 #ifndef INADDR_NONE
3813 #define INADDR_NONE (-1)
3814 #endif
3815 #ifdef HAVE_INET_ATON
3816 struct in_addr buf;
3817 #endif
3819 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
3820 #if (SIZEOF_INT != 4)
3821 #error "Not sure if in_addr_t exists and int is not 32-bits."
3822 #endif
3823 /* Have to use inet_addr() instead */
3824 unsigned int packed_addr;
3825 #endif
3826 char *ip_addr;
3828 if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr))
3829 return NULL;
3832 #ifdef HAVE_INET_ATON
3834 #ifdef USE_INET_ATON_WEAKLINK
3835 if (inet_aton != NULL) {
3836 #endif
3837 if (inet_aton(ip_addr, &buf))
3838 return PyString_FromStringAndSize((char *)(&buf),
3839 sizeof(buf));
3841 PyErr_SetString(socket_error,
3842 "illegal IP address string passed to inet_aton");
3843 return NULL;
3845 #ifdef USE_INET_ATON_WEAKLINK
3846 } else {
3847 #endif
3849 #endif
3851 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
3853 /* special-case this address as inet_addr might return INADDR_NONE
3854 * for this */
3855 if (strcmp(ip_addr, "255.255.255.255") == 0) {
3856 packed_addr = 0xFFFFFFFF;
3857 } else {
3859 packed_addr = inet_addr(ip_addr);
3861 if (packed_addr == INADDR_NONE) { /* invalid address */
3862 PyErr_SetString(socket_error,
3863 "illegal IP address string passed to inet_aton");
3864 return NULL;
3867 return PyString_FromStringAndSize((char *) &packed_addr,
3868 sizeof(packed_addr));
3870 #ifdef USE_INET_ATON_WEAKLINK
3872 #endif
3874 #endif
3877 PyDoc_STRVAR(inet_ntoa_doc,
3878 "inet_ntoa(packed_ip) -> ip_address_string\n\
3880 Convert an IP address from 32-bit packed binary format to string format");
3882 static PyObject*
3883 socket_inet_ntoa(PyObject *self, PyObject *args)
3885 char *packed_str;
3886 int addr_len;
3887 struct in_addr packed_addr;
3889 if (!PyArg_ParseTuple(args, "s#:inet_ntoa", &packed_str, &addr_len)) {
3890 return NULL;
3893 if (addr_len != sizeof(packed_addr)) {
3894 PyErr_SetString(socket_error,
3895 "packed IP wrong length for inet_ntoa");
3896 return NULL;
3899 memcpy(&packed_addr, packed_str, addr_len);
3901 return PyString_FromString(inet_ntoa(packed_addr));
3904 #ifdef HAVE_INET_PTON
3906 PyDoc_STRVAR(inet_pton_doc,
3907 "inet_pton(af, ip) -> packed IP address string\n\
3909 Convert an IP address from string format to a packed string suitable\n\
3910 for use with low-level network functions.");
3912 static PyObject *
3913 socket_inet_pton(PyObject *self, PyObject *args)
3915 int af;
3916 char* ip;
3917 int retval;
3918 #ifdef ENABLE_IPV6
3919 char packed[MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
3920 #else
3921 char packed[sizeof(struct in_addr)];
3922 #endif
3923 if (!PyArg_ParseTuple(args, "is:inet_pton", &af, &ip)) {
3924 return NULL;
3927 #if !defined(ENABLE_IPV6) && defined(AF_INET6)
3928 if(af == AF_INET6) {
3929 PyErr_SetString(socket_error,
3930 "can't use AF_INET6, IPv6 is disabled");
3931 return NULL;
3933 #endif
3935 retval = inet_pton(af, ip, packed);
3936 if (retval < 0) {
3937 PyErr_SetFromErrno(socket_error);
3938 return NULL;
3939 } else if (retval == 0) {
3940 PyErr_SetString(socket_error,
3941 "illegal IP address string passed to inet_pton");
3942 return NULL;
3943 } else if (af == AF_INET) {
3944 return PyString_FromStringAndSize(packed,
3945 sizeof(struct in_addr));
3946 #ifdef ENABLE_IPV6
3947 } else if (af == AF_INET6) {
3948 return PyString_FromStringAndSize(packed,
3949 sizeof(struct in6_addr));
3950 #endif
3951 } else {
3952 PyErr_SetString(socket_error, "unknown address family");
3953 return NULL;
3957 PyDoc_STRVAR(inet_ntop_doc,
3958 "inet_ntop(af, packed_ip) -> string formatted IP address\n\
3960 Convert a packed IP address of the given family to string format.");
3962 static PyObject *
3963 socket_inet_ntop(PyObject *self, PyObject *args)
3965 int af;
3966 char* packed;
3967 int len;
3968 const char* retval;
3969 #ifdef ENABLE_IPV6
3970 char ip[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) + 1];
3971 #else
3972 char ip[INET_ADDRSTRLEN + 1];
3973 #endif
3975 /* Guarantee NUL-termination for PyString_FromString() below */
3976 memset((void *) &ip[0], '\0', sizeof(ip));
3978 if (!PyArg_ParseTuple(args, "is#:inet_ntop", &af, &packed, &len)) {
3979 return NULL;
3982 if (af == AF_INET) {
3983 if (len != sizeof(struct in_addr)) {
3984 PyErr_SetString(PyExc_ValueError,
3985 "invalid length of packed IP address string");
3986 return NULL;
3988 #ifdef ENABLE_IPV6
3989 } else if (af == AF_INET6) {
3990 if (len != sizeof(struct in6_addr)) {
3991 PyErr_SetString(PyExc_ValueError,
3992 "invalid length of packed IP address string");
3993 return NULL;
3995 #endif
3996 } else {
3997 PyErr_Format(PyExc_ValueError,
3998 "unknown address family %d", af);
3999 return NULL;
4002 retval = inet_ntop(af, packed, ip, sizeof(ip));
4003 if (!retval) {
4004 PyErr_SetFromErrno(socket_error);
4005 return NULL;
4006 } else {
4007 return PyString_FromString(retval);
4010 /* NOTREACHED */
4011 PyErr_SetString(PyExc_RuntimeError, "invalid handling of inet_ntop");
4012 return NULL;
4015 #endif /* HAVE_INET_PTON */
4017 /* Python interface to getaddrinfo(host, port). */
4019 /*ARGSUSED*/
4020 static PyObject *
4021 socket_getaddrinfo(PyObject *self, PyObject *args)
4023 struct addrinfo hints, *res;
4024 struct addrinfo *res0 = NULL;
4025 PyObject *hobj = NULL;
4026 PyObject *pobj = (PyObject *)NULL;
4027 char pbuf[30];
4028 char *hptr, *pptr;
4029 int family, socktype, protocol, flags;
4030 int error;
4031 PyObject *all = (PyObject *)NULL;
4032 PyObject *single = (PyObject *)NULL;
4033 PyObject *idna = NULL;
4035 family = socktype = protocol = flags = 0;
4036 family = AF_UNSPEC;
4037 if (!PyArg_ParseTuple(args, "OO|iiii:getaddrinfo",
4038 &hobj, &pobj, &family, &socktype,
4039 &protocol, &flags)) {
4040 return NULL;
4042 if (hobj == Py_None) {
4043 hptr = NULL;
4044 } else if (PyUnicode_Check(hobj)) {
4045 idna = PyObject_CallMethod(hobj, "encode", "s", "idna");
4046 if (!idna)
4047 return NULL;
4048 hptr = PyString_AsString(idna);
4049 } else if (PyString_Check(hobj)) {
4050 hptr = PyString_AsString(hobj);
4051 } else {
4052 PyErr_SetString(PyExc_TypeError,
4053 "getaddrinfo() argument 1 must be string or None");
4054 return NULL;
4056 if (PyInt_Check(pobj)) {
4057 PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", PyInt_AsLong(pobj));
4058 pptr = pbuf;
4059 } else if (PyString_Check(pobj)) {
4060 pptr = PyString_AsString(pobj);
4061 } else if (pobj == Py_None) {
4062 pptr = (char *)NULL;
4063 } else {
4064 PyErr_SetString(socket_error, "Int or String expected");
4065 goto err;
4067 memset(&hints, 0, sizeof(hints));
4068 hints.ai_family = family;
4069 hints.ai_socktype = socktype;
4070 hints.ai_protocol = protocol;
4071 hints.ai_flags = flags;
4072 Py_BEGIN_ALLOW_THREADS
4073 ACQUIRE_GETADDRINFO_LOCK
4074 error = getaddrinfo(hptr, pptr, &hints, &res0);
4075 Py_END_ALLOW_THREADS
4076 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
4077 if (error) {
4078 set_gaierror(error);
4079 goto err;
4082 if ((all = PyList_New(0)) == NULL)
4083 goto err;
4084 for (res = res0; res; res = res->ai_next) {
4085 PyObject *addr =
4086 makesockaddr(-1, res->ai_addr, res->ai_addrlen, protocol);
4087 if (addr == NULL)
4088 goto err;
4089 single = Py_BuildValue("iiisO", res->ai_family,
4090 res->ai_socktype, res->ai_protocol,
4091 res->ai_canonname ? res->ai_canonname : "",
4092 addr);
4093 Py_DECREF(addr);
4094 if (single == NULL)
4095 goto err;
4097 if (PyList_Append(all, single))
4098 goto err;
4099 Py_XDECREF(single);
4101 Py_XDECREF(idna);
4102 if (res0)
4103 freeaddrinfo(res0);
4104 return all;
4105 err:
4106 Py_XDECREF(single);
4107 Py_XDECREF(all);
4108 Py_XDECREF(idna);
4109 if (res0)
4110 freeaddrinfo(res0);
4111 return (PyObject *)NULL;
4114 PyDoc_STRVAR(getaddrinfo_doc,
4115 "getaddrinfo(host, port [, family, socktype, proto, flags])\n\
4116 -> list of (family, socktype, proto, canonname, sockaddr)\n\
4118 Resolve host and port into addrinfo struct.");
4120 /* Python interface to getnameinfo(sa, flags). */
4122 /*ARGSUSED*/
4123 static PyObject *
4124 socket_getnameinfo(PyObject *self, PyObject *args)
4126 PyObject *sa = (PyObject *)NULL;
4127 int flags;
4128 char *hostp;
4129 int port, flowinfo, scope_id;
4130 char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
4131 struct addrinfo hints, *res = NULL;
4132 int error;
4133 PyObject *ret = (PyObject *)NULL;
4135 flags = flowinfo = scope_id = 0;
4136 if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags))
4137 return NULL;
4138 if (!PyTuple_Check(sa)) {
4139 PyErr_SetString(PyExc_TypeError,
4140 "getnameinfo() argument 1 must be a tuple");
4141 return NULL;
4143 if (!PyArg_ParseTuple(sa, "si|ii",
4144 &hostp, &port, &flowinfo, &scope_id))
4145 return NULL;
4146 PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port);
4147 memset(&hints, 0, sizeof(hints));
4148 hints.ai_family = AF_UNSPEC;
4149 hints.ai_socktype = SOCK_DGRAM; /* make numeric port happy */
4150 Py_BEGIN_ALLOW_THREADS
4151 ACQUIRE_GETADDRINFO_LOCK
4152 error = getaddrinfo(hostp, pbuf, &hints, &res);
4153 Py_END_ALLOW_THREADS
4154 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
4155 if (error) {
4156 set_gaierror(error);
4157 goto fail;
4159 if (res->ai_next) {
4160 PyErr_SetString(socket_error,
4161 "sockaddr resolved to multiple addresses");
4162 goto fail;
4164 switch (res->ai_family) {
4165 case AF_INET:
4167 if (PyTuple_GET_SIZE(sa) != 2) {
4168 PyErr_SetString(socket_error,
4169 "IPv4 sockaddr must be 2 tuple");
4170 goto fail;
4172 break;
4174 #ifdef ENABLE_IPV6
4175 case AF_INET6:
4177 struct sockaddr_in6 *sin6;
4178 sin6 = (struct sockaddr_in6 *)res->ai_addr;
4179 sin6->sin6_flowinfo = flowinfo;
4180 sin6->sin6_scope_id = scope_id;
4181 break;
4183 #endif
4185 error = getnameinfo(res->ai_addr, res->ai_addrlen,
4186 hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags);
4187 if (error) {
4188 set_gaierror(error);
4189 goto fail;
4191 ret = Py_BuildValue("ss", hbuf, pbuf);
4193 fail:
4194 if (res)
4195 freeaddrinfo(res);
4196 return ret;
4199 PyDoc_STRVAR(getnameinfo_doc,
4200 "getnameinfo(sockaddr, flags) --> (host, port)\n\
4202 Get host and port for a sockaddr.");
4205 /* Python API to getting and setting the default timeout value. */
4207 static PyObject *
4208 socket_getdefaulttimeout(PyObject *self)
4210 if (defaulttimeout < 0.0) {
4211 Py_INCREF(Py_None);
4212 return Py_None;
4214 else
4215 return PyFloat_FromDouble(defaulttimeout);
4218 PyDoc_STRVAR(getdefaulttimeout_doc,
4219 "getdefaulttimeout() -> timeout\n\
4221 Returns the default timeout in floating seconds for new socket objects.\n\
4222 A value of None indicates that new socket objects have no timeout.\n\
4223 When the socket module is first imported, the default is None.");
4225 static PyObject *
4226 socket_setdefaulttimeout(PyObject *self, PyObject *arg)
4228 double timeout;
4230 if (arg == Py_None)
4231 timeout = -1.0;
4232 else {
4233 timeout = PyFloat_AsDouble(arg);
4234 if (timeout < 0.0) {
4235 if (!PyErr_Occurred())
4236 PyErr_SetString(PyExc_ValueError,
4237 "Timeout value out of range");
4238 return NULL;
4242 defaulttimeout = timeout;
4244 Py_INCREF(Py_None);
4245 return Py_None;
4248 PyDoc_STRVAR(setdefaulttimeout_doc,
4249 "setdefaulttimeout(timeout)\n\
4251 Set the default timeout in floating seconds for new socket objects.\n\
4252 A value of None indicates that new socket objects have no timeout.\n\
4253 When the socket module is first imported, the default is None.");
4256 /* List of functions exported by this module. */
4258 static PyMethodDef socket_methods[] = {
4259 {"gethostbyname", socket_gethostbyname,
4260 METH_VARARGS, gethostbyname_doc},
4261 {"gethostbyname_ex", socket_gethostbyname_ex,
4262 METH_VARARGS, ghbn_ex_doc},
4263 {"gethostbyaddr", socket_gethostbyaddr,
4264 METH_VARARGS, gethostbyaddr_doc},
4265 {"gethostname", socket_gethostname,
4266 METH_NOARGS, gethostname_doc},
4267 {"getservbyname", socket_getservbyname,
4268 METH_VARARGS, getservbyname_doc},
4269 {"getservbyport", socket_getservbyport,
4270 METH_VARARGS, getservbyport_doc},
4271 {"getprotobyname", socket_getprotobyname,
4272 METH_VARARGS, getprotobyname_doc},
4273 #ifndef NO_DUP
4274 {"fromfd", socket_fromfd,
4275 METH_VARARGS, fromfd_doc},
4276 #endif
4277 #ifdef HAVE_SOCKETPAIR
4278 {"socketpair", socket_socketpair,
4279 METH_VARARGS, socketpair_doc},
4280 #endif
4281 {"ntohs", socket_ntohs,
4282 METH_VARARGS, ntohs_doc},
4283 {"ntohl", socket_ntohl,
4284 METH_O, ntohl_doc},
4285 {"htons", socket_htons,
4286 METH_VARARGS, htons_doc},
4287 {"htonl", socket_htonl,
4288 METH_O, htonl_doc},
4289 {"inet_aton", socket_inet_aton,
4290 METH_VARARGS, inet_aton_doc},
4291 {"inet_ntoa", socket_inet_ntoa,
4292 METH_VARARGS, inet_ntoa_doc},
4293 #ifdef HAVE_INET_PTON
4294 {"inet_pton", socket_inet_pton,
4295 METH_VARARGS, inet_pton_doc},
4296 {"inet_ntop", socket_inet_ntop,
4297 METH_VARARGS, inet_ntop_doc},
4298 #endif
4299 {"getaddrinfo", socket_getaddrinfo,
4300 METH_VARARGS, getaddrinfo_doc},
4301 {"getnameinfo", socket_getnameinfo,
4302 METH_VARARGS, getnameinfo_doc},
4303 {"getdefaulttimeout", (PyCFunction)socket_getdefaulttimeout,
4304 METH_NOARGS, getdefaulttimeout_doc},
4305 {"setdefaulttimeout", socket_setdefaulttimeout,
4306 METH_O, setdefaulttimeout_doc},
4307 {NULL, NULL} /* Sentinel */
4311 #ifdef RISCOS
4312 #define OS_INIT_DEFINED
4314 static int
4315 os_init(void)
4317 _kernel_swi_regs r;
4319 r.r[0] = 0;
4320 _kernel_swi(0x43380, &r, &r);
4321 taskwindow = r.r[0];
4323 return 1;
4326 #endif /* RISCOS */
4329 #ifdef MS_WINDOWS
4330 #define OS_INIT_DEFINED
4332 /* Additional initialization and cleanup for Windows */
4334 static void
4335 os_cleanup(void)
4337 WSACleanup();
4340 static int
4341 os_init(void)
4343 WSADATA WSAData;
4344 int ret;
4345 char buf[100];
4346 ret = WSAStartup(0x0101, &WSAData);
4347 switch (ret) {
4348 case 0: /* No error */
4349 Py_AtExit(os_cleanup);
4350 return 1; /* Success */
4351 case WSASYSNOTREADY:
4352 PyErr_SetString(PyExc_ImportError,
4353 "WSAStartup failed: network not ready");
4354 break;
4355 case WSAVERNOTSUPPORTED:
4356 case WSAEINVAL:
4357 PyErr_SetString(
4358 PyExc_ImportError,
4359 "WSAStartup failed: requested version not supported");
4360 break;
4361 default:
4362 PyOS_snprintf(buf, sizeof(buf),
4363 "WSAStartup failed: error code %d", ret);
4364 PyErr_SetString(PyExc_ImportError, buf);
4365 break;
4367 return 0; /* Failure */
4370 #endif /* MS_WINDOWS */
4373 #ifdef PYOS_OS2
4374 #define OS_INIT_DEFINED
4376 /* Additional initialization for OS/2 */
4378 static int
4379 os_init(void)
4381 #ifndef PYCC_GCC
4382 char reason[64];
4383 int rc = sock_init();
4385 if (rc == 0) {
4386 return 1; /* Success */
4389 PyOS_snprintf(reason, sizeof(reason),
4390 "OS/2 TCP/IP Error# %d", sock_errno());
4391 PyErr_SetString(PyExc_ImportError, reason);
4393 return 0; /* Failure */
4394 #else
4395 /* No need to initialise sockets with GCC/EMX */
4396 return 1; /* Success */
4397 #endif
4400 #endif /* PYOS_OS2 */
4403 #ifndef OS_INIT_DEFINED
4404 static int
4405 os_init(void)
4407 return 1; /* Success */
4409 #endif
4412 /* C API table - always add new things to the end for binary
4413 compatibility. */
4414 static
4415 PySocketModule_APIObject PySocketModuleAPI =
4417 &sock_type,
4418 NULL
4422 /* Initialize the _socket module.
4424 This module is actually called "_socket", and there's a wrapper
4425 "socket.py" which implements some additional functionality. On some
4426 platforms (e.g. Windows and OS/2), socket.py also implements a
4427 wrapper for the socket type that provides missing functionality such
4428 as makefile(), dup() and fromfd(). The import of "_socket" may fail
4429 with an ImportError exception if os-specific initialization fails.
4430 On Windows, this does WINSOCK initialization. When WINSOCK is
4431 initialized succesfully, a call to WSACleanup() is scheduled to be
4432 made at exit time.
4435 PyDoc_STRVAR(socket_doc,
4436 "Implementation module for socket operations.\n\
4438 See the socket module for documentation.");
4440 PyMODINIT_FUNC
4441 init_socket(void)
4443 PyObject *m, *has_ipv6;
4445 if (!os_init())
4446 return;
4448 Py_TYPE(&sock_type) = &PyType_Type;
4449 m = Py_InitModule3(PySocket_MODULE_NAME,
4450 socket_methods,
4451 socket_doc);
4452 if (m == NULL)
4453 return;
4455 socket_error = PyErr_NewException("socket.error",
4456 PyExc_IOError, NULL);
4457 if (socket_error == NULL)
4458 return;
4459 PySocketModuleAPI.error = socket_error;
4460 Py_INCREF(socket_error);
4461 PyModule_AddObject(m, "error", socket_error);
4462 socket_herror = PyErr_NewException("socket.herror",
4463 socket_error, NULL);
4464 if (socket_herror == NULL)
4465 return;
4466 Py_INCREF(socket_herror);
4467 PyModule_AddObject(m, "herror", socket_herror);
4468 socket_gaierror = PyErr_NewException("socket.gaierror", socket_error,
4469 NULL);
4470 if (socket_gaierror == NULL)
4471 return;
4472 Py_INCREF(socket_gaierror);
4473 PyModule_AddObject(m, "gaierror", socket_gaierror);
4474 socket_timeout = PyErr_NewException("socket.timeout",
4475 socket_error, NULL);
4476 if (socket_timeout == NULL)
4477 return;
4478 Py_INCREF(socket_timeout);
4479 PyModule_AddObject(m, "timeout", socket_timeout);
4480 Py_INCREF((PyObject *)&sock_type);
4481 if (PyModule_AddObject(m, "SocketType",
4482 (PyObject *)&sock_type) != 0)
4483 return;
4484 Py_INCREF((PyObject *)&sock_type);
4485 if (PyModule_AddObject(m, "socket",
4486 (PyObject *)&sock_type) != 0)
4487 return;
4489 #ifdef ENABLE_IPV6
4490 has_ipv6 = Py_True;
4491 #else
4492 has_ipv6 = Py_False;
4493 #endif
4494 Py_INCREF(has_ipv6);
4495 PyModule_AddObject(m, "has_ipv6", has_ipv6);
4497 /* Export C API */
4498 if (PyModule_AddObject(m, PySocket_CAPI_NAME,
4499 PyCapsule_New(&PySocketModuleAPI, PySocket_CAPSULE_NAME, NULL)
4500 ) != 0)
4501 return;
4503 /* Address families (we only support AF_INET and AF_UNIX) */
4504 #ifdef AF_UNSPEC
4505 PyModule_AddIntConstant(m, "AF_UNSPEC", AF_UNSPEC);
4506 #endif
4507 PyModule_AddIntConstant(m, "AF_INET", AF_INET);
4508 #ifdef AF_INET6
4509 PyModule_AddIntConstant(m, "AF_INET6", AF_INET6);
4510 #endif /* AF_INET6 */
4511 #if defined(AF_UNIX)
4512 PyModule_AddIntConstant(m, "AF_UNIX", AF_UNIX);
4513 #endif /* AF_UNIX */
4514 #ifdef AF_AX25
4515 /* Amateur Radio AX.25 */
4516 PyModule_AddIntConstant(m, "AF_AX25", AF_AX25);
4517 #endif
4518 #ifdef AF_IPX
4519 PyModule_AddIntConstant(m, "AF_IPX", AF_IPX); /* Novell IPX */
4520 #endif
4521 #ifdef AF_APPLETALK
4522 /* Appletalk DDP */
4523 PyModule_AddIntConstant(m, "AF_APPLETALK", AF_APPLETALK);
4524 #endif
4525 #ifdef AF_NETROM
4526 /* Amateur radio NetROM */
4527 PyModule_AddIntConstant(m, "AF_NETROM", AF_NETROM);
4528 #endif
4529 #ifdef AF_BRIDGE
4530 /* Multiprotocol bridge */
4531 PyModule_AddIntConstant(m, "AF_BRIDGE", AF_BRIDGE);
4532 #endif
4533 #ifdef AF_ATMPVC
4534 /* ATM PVCs */
4535 PyModule_AddIntConstant(m, "AF_ATMPVC", AF_ATMPVC);
4536 #endif
4537 #ifdef AF_AAL5
4538 /* Reserved for Werner's ATM */
4539 PyModule_AddIntConstant(m, "AF_AAL5", AF_AAL5);
4540 #endif
4541 #ifdef AF_X25
4542 /* Reserved for X.25 project */
4543 PyModule_AddIntConstant(m, "AF_X25", AF_X25);
4544 #endif
4545 #ifdef AF_INET6
4546 PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); /* IP version 6 */
4547 #endif
4548 #ifdef AF_ROSE
4549 /* Amateur Radio X.25 PLP */
4550 PyModule_AddIntConstant(m, "AF_ROSE", AF_ROSE);
4551 #endif
4552 #ifdef AF_DECnet
4553 /* Reserved for DECnet project */
4554 PyModule_AddIntConstant(m, "AF_DECnet", AF_DECnet);
4555 #endif
4556 #ifdef AF_NETBEUI
4557 /* Reserved for 802.2LLC project */
4558 PyModule_AddIntConstant(m, "AF_NETBEUI", AF_NETBEUI);
4559 #endif
4560 #ifdef AF_SECURITY
4561 /* Security callback pseudo AF */
4562 PyModule_AddIntConstant(m, "AF_SECURITY", AF_SECURITY);
4563 #endif
4564 #ifdef AF_KEY
4565 /* PF_KEY key management API */
4566 PyModule_AddIntConstant(m, "AF_KEY", AF_KEY);
4567 #endif
4568 #ifdef AF_NETLINK
4569 /* */
4570 PyModule_AddIntConstant(m, "AF_NETLINK", AF_NETLINK);
4571 PyModule_AddIntConstant(m, "NETLINK_ROUTE", NETLINK_ROUTE);
4572 #ifdef NETLINK_SKIP
4573 PyModule_AddIntConstant(m, "NETLINK_SKIP", NETLINK_SKIP);
4574 #endif
4575 #ifdef NETLINK_W1
4576 PyModule_AddIntConstant(m, "NETLINK_W1", NETLINK_W1);
4577 #endif
4578 PyModule_AddIntConstant(m, "NETLINK_USERSOCK", NETLINK_USERSOCK);
4579 PyModule_AddIntConstant(m, "NETLINK_FIREWALL", NETLINK_FIREWALL);
4580 #ifdef NETLINK_TCPDIAG
4581 PyModule_AddIntConstant(m, "NETLINK_TCPDIAG", NETLINK_TCPDIAG);
4582 #endif
4583 #ifdef NETLINK_NFLOG
4584 PyModule_AddIntConstant(m, "NETLINK_NFLOG", NETLINK_NFLOG);
4585 #endif
4586 #ifdef NETLINK_XFRM
4587 PyModule_AddIntConstant(m, "NETLINK_XFRM", NETLINK_XFRM);
4588 #endif
4589 #ifdef NETLINK_ARPD
4590 PyModule_AddIntConstant(m, "NETLINK_ARPD", NETLINK_ARPD);
4591 #endif
4592 #ifdef NETLINK_ROUTE6
4593 PyModule_AddIntConstant(m, "NETLINK_ROUTE6", NETLINK_ROUTE6);
4594 #endif
4595 PyModule_AddIntConstant(m, "NETLINK_IP6_FW", NETLINK_IP6_FW);
4596 #ifdef NETLINK_DNRTMSG
4597 PyModule_AddIntConstant(m, "NETLINK_DNRTMSG", NETLINK_DNRTMSG);
4598 #endif
4599 #ifdef NETLINK_TAPBASE
4600 PyModule_AddIntConstant(m, "NETLINK_TAPBASE", NETLINK_TAPBASE);
4601 #endif
4602 #endif /* AF_NETLINK */
4603 #ifdef AF_ROUTE
4604 /* Alias to emulate 4.4BSD */
4605 PyModule_AddIntConstant(m, "AF_ROUTE", AF_ROUTE);
4606 #endif
4607 #ifdef AF_ASH
4608 /* Ash */
4609 PyModule_AddIntConstant(m, "AF_ASH", AF_ASH);
4610 #endif
4611 #ifdef AF_ECONET
4612 /* Acorn Econet */
4613 PyModule_AddIntConstant(m, "AF_ECONET", AF_ECONET);
4614 #endif
4615 #ifdef AF_ATMSVC
4616 /* ATM SVCs */
4617 PyModule_AddIntConstant(m, "AF_ATMSVC", AF_ATMSVC);
4618 #endif
4619 #ifdef AF_SNA
4620 /* Linux SNA Project (nutters!) */
4621 PyModule_AddIntConstant(m, "AF_SNA", AF_SNA);
4622 #endif
4623 #ifdef AF_IRDA
4624 /* IRDA sockets */
4625 PyModule_AddIntConstant(m, "AF_IRDA", AF_IRDA);
4626 #endif
4627 #ifdef AF_PPPOX
4628 /* PPPoX sockets */
4629 PyModule_AddIntConstant(m, "AF_PPPOX", AF_PPPOX);
4630 #endif
4631 #ifdef AF_WANPIPE
4632 /* Wanpipe API Sockets */
4633 PyModule_AddIntConstant(m, "AF_WANPIPE", AF_WANPIPE);
4634 #endif
4635 #ifdef AF_LLC
4636 /* Linux LLC */
4637 PyModule_AddIntConstant(m, "AF_LLC", AF_LLC);
4638 #endif
4640 #ifdef USE_BLUETOOTH
4641 PyModule_AddIntConstant(m, "AF_BLUETOOTH", AF_BLUETOOTH);
4642 PyModule_AddIntConstant(m, "BTPROTO_L2CAP", BTPROTO_L2CAP);
4643 PyModule_AddIntConstant(m, "BTPROTO_HCI", BTPROTO_HCI);
4644 PyModule_AddIntConstant(m, "SOL_HCI", SOL_HCI);
4645 PyModule_AddIntConstant(m, "HCI_FILTER", HCI_FILTER);
4646 #if !defined(__FreeBSD__)
4647 PyModule_AddIntConstant(m, "HCI_TIME_STAMP", HCI_TIME_STAMP);
4648 PyModule_AddIntConstant(m, "HCI_DATA_DIR", HCI_DATA_DIR);
4649 PyModule_AddIntConstant(m, "BTPROTO_SCO", BTPROTO_SCO);
4650 #endif
4651 PyModule_AddIntConstant(m, "BTPROTO_RFCOMM", BTPROTO_RFCOMM);
4652 PyModule_AddStringConstant(m, "BDADDR_ANY", "00:00:00:00:00:00");
4653 PyModule_AddStringConstant(m, "BDADDR_LOCAL", "00:00:00:FF:FF:FF");
4654 #endif
4656 #ifdef HAVE_NETPACKET_PACKET_H
4657 PyModule_AddIntConstant(m, "AF_PACKET", AF_PACKET);
4658 PyModule_AddIntConstant(m, "PF_PACKET", PF_PACKET);
4659 PyModule_AddIntConstant(m, "PACKET_HOST", PACKET_HOST);
4660 PyModule_AddIntConstant(m, "PACKET_BROADCAST", PACKET_BROADCAST);
4661 PyModule_AddIntConstant(m, "PACKET_MULTICAST", PACKET_MULTICAST);
4662 PyModule_AddIntConstant(m, "PACKET_OTHERHOST", PACKET_OTHERHOST);
4663 PyModule_AddIntConstant(m, "PACKET_OUTGOING", PACKET_OUTGOING);
4664 PyModule_AddIntConstant(m, "PACKET_LOOPBACK", PACKET_LOOPBACK);
4665 PyModule_AddIntConstant(m, "PACKET_FASTROUTE", PACKET_FASTROUTE);
4666 #endif
4668 #ifdef HAVE_LINUX_TIPC_H
4669 PyModule_AddIntConstant(m, "AF_TIPC", AF_TIPC);
4671 /* for addresses */
4672 PyModule_AddIntConstant(m, "TIPC_ADDR_NAMESEQ", TIPC_ADDR_NAMESEQ);
4673 PyModule_AddIntConstant(m, "TIPC_ADDR_NAME", TIPC_ADDR_NAME);
4674 PyModule_AddIntConstant(m, "TIPC_ADDR_ID", TIPC_ADDR_ID);
4676 PyModule_AddIntConstant(m, "TIPC_ZONE_SCOPE", TIPC_ZONE_SCOPE);
4677 PyModule_AddIntConstant(m, "TIPC_CLUSTER_SCOPE", TIPC_CLUSTER_SCOPE);
4678 PyModule_AddIntConstant(m, "TIPC_NODE_SCOPE", TIPC_NODE_SCOPE);
4680 /* for setsockopt() */
4681 PyModule_AddIntConstant(m, "SOL_TIPC", SOL_TIPC);
4682 PyModule_AddIntConstant(m, "TIPC_IMPORTANCE", TIPC_IMPORTANCE);
4683 PyModule_AddIntConstant(m, "TIPC_SRC_DROPPABLE", TIPC_SRC_DROPPABLE);
4684 PyModule_AddIntConstant(m, "TIPC_DEST_DROPPABLE",
4685 TIPC_DEST_DROPPABLE);
4686 PyModule_AddIntConstant(m, "TIPC_CONN_TIMEOUT", TIPC_CONN_TIMEOUT);
4688 PyModule_AddIntConstant(m, "TIPC_LOW_IMPORTANCE",
4689 TIPC_LOW_IMPORTANCE);
4690 PyModule_AddIntConstant(m, "TIPC_MEDIUM_IMPORTANCE",
4691 TIPC_MEDIUM_IMPORTANCE);
4692 PyModule_AddIntConstant(m, "TIPC_HIGH_IMPORTANCE",
4693 TIPC_HIGH_IMPORTANCE);
4694 PyModule_AddIntConstant(m, "TIPC_CRITICAL_IMPORTANCE",
4695 TIPC_CRITICAL_IMPORTANCE);
4697 /* for subscriptions */
4698 PyModule_AddIntConstant(m, "TIPC_SUB_PORTS", TIPC_SUB_PORTS);
4699 PyModule_AddIntConstant(m, "TIPC_SUB_SERVICE", TIPC_SUB_SERVICE);
4700 #ifdef TIPC_SUB_CANCEL
4701 /* doesn't seem to be available everywhere */
4702 PyModule_AddIntConstant(m, "TIPC_SUB_CANCEL", TIPC_SUB_CANCEL);
4703 #endif
4704 PyModule_AddIntConstant(m, "TIPC_WAIT_FOREVER", TIPC_WAIT_FOREVER);
4705 PyModule_AddIntConstant(m, "TIPC_PUBLISHED", TIPC_PUBLISHED);
4706 PyModule_AddIntConstant(m, "TIPC_WITHDRAWN", TIPC_WITHDRAWN);
4707 PyModule_AddIntConstant(m, "TIPC_SUBSCR_TIMEOUT", TIPC_SUBSCR_TIMEOUT);
4708 PyModule_AddIntConstant(m, "TIPC_CFG_SRV", TIPC_CFG_SRV);
4709 PyModule_AddIntConstant(m, "TIPC_TOP_SRV", TIPC_TOP_SRV);
4710 #endif
4712 /* Socket types */
4713 PyModule_AddIntConstant(m, "SOCK_STREAM", SOCK_STREAM);
4714 PyModule_AddIntConstant(m, "SOCK_DGRAM", SOCK_DGRAM);
4715 #ifndef __BEOS__
4716 /* We have incomplete socket support. */
4717 PyModule_AddIntConstant(m, "SOCK_RAW", SOCK_RAW);
4718 PyModule_AddIntConstant(m, "SOCK_SEQPACKET", SOCK_SEQPACKET);
4719 #if defined(SOCK_RDM)
4720 PyModule_AddIntConstant(m, "SOCK_RDM", SOCK_RDM);
4721 #endif
4722 #endif
4724 #ifdef SO_DEBUG
4725 PyModule_AddIntConstant(m, "SO_DEBUG", SO_DEBUG);
4726 #endif
4727 #ifdef SO_ACCEPTCONN
4728 PyModule_AddIntConstant(m, "SO_ACCEPTCONN", SO_ACCEPTCONN);
4729 #endif
4730 #ifdef SO_REUSEADDR
4731 PyModule_AddIntConstant(m, "SO_REUSEADDR", SO_REUSEADDR);
4732 #endif
4733 #ifdef SO_EXCLUSIVEADDRUSE
4734 PyModule_AddIntConstant(m, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE);
4735 #endif
4737 #ifdef SO_KEEPALIVE
4738 PyModule_AddIntConstant(m, "SO_KEEPALIVE", SO_KEEPALIVE);
4739 #endif
4740 #ifdef SO_DONTROUTE
4741 PyModule_AddIntConstant(m, "SO_DONTROUTE", SO_DONTROUTE);
4742 #endif
4743 #ifdef SO_BROADCAST
4744 PyModule_AddIntConstant(m, "SO_BROADCAST", SO_BROADCAST);
4745 #endif
4746 #ifdef SO_USELOOPBACK
4747 PyModule_AddIntConstant(m, "SO_USELOOPBACK", SO_USELOOPBACK);
4748 #endif
4749 #ifdef SO_LINGER
4750 PyModule_AddIntConstant(m, "SO_LINGER", SO_LINGER);
4751 #endif
4752 #ifdef SO_OOBINLINE
4753 PyModule_AddIntConstant(m, "SO_OOBINLINE", SO_OOBINLINE);
4754 #endif
4755 #ifdef SO_REUSEPORT
4756 PyModule_AddIntConstant(m, "SO_REUSEPORT", SO_REUSEPORT);
4757 #endif
4758 #ifdef SO_SNDBUF
4759 PyModule_AddIntConstant(m, "SO_SNDBUF", SO_SNDBUF);
4760 #endif
4761 #ifdef SO_RCVBUF
4762 PyModule_AddIntConstant(m, "SO_RCVBUF", SO_RCVBUF);
4763 #endif
4764 #ifdef SO_SNDLOWAT
4765 PyModule_AddIntConstant(m, "SO_SNDLOWAT", SO_SNDLOWAT);
4766 #endif
4767 #ifdef SO_RCVLOWAT
4768 PyModule_AddIntConstant(m, "SO_RCVLOWAT", SO_RCVLOWAT);
4769 #endif
4770 #ifdef SO_SNDTIMEO
4771 PyModule_AddIntConstant(m, "SO_SNDTIMEO", SO_SNDTIMEO);
4772 #endif
4773 #ifdef SO_RCVTIMEO
4774 PyModule_AddIntConstant(m, "SO_RCVTIMEO", SO_RCVTIMEO);
4775 #endif
4776 #ifdef SO_ERROR
4777 PyModule_AddIntConstant(m, "SO_ERROR", SO_ERROR);
4778 #endif
4779 #ifdef SO_TYPE
4780 PyModule_AddIntConstant(m, "SO_TYPE", SO_TYPE);
4781 #endif
4782 #ifdef SO_SETFIB
4783 PyModule_AddIntConstant(m, "SO_SETFIB", SO_SETFIB);
4784 #endif
4786 /* Maximum number of connections for "listen" */
4787 #ifdef SOMAXCONN
4788 PyModule_AddIntConstant(m, "SOMAXCONN", SOMAXCONN);
4789 #else
4790 PyModule_AddIntConstant(m, "SOMAXCONN", 5); /* Common value */
4791 #endif
4793 /* Flags for send, recv */
4794 #ifdef MSG_OOB
4795 PyModule_AddIntConstant(m, "MSG_OOB", MSG_OOB);
4796 #endif
4797 #ifdef MSG_PEEK
4798 PyModule_AddIntConstant(m, "MSG_PEEK", MSG_PEEK);
4799 #endif
4800 #ifdef MSG_DONTROUTE
4801 PyModule_AddIntConstant(m, "MSG_DONTROUTE", MSG_DONTROUTE);
4802 #endif
4803 #ifdef MSG_DONTWAIT
4804 PyModule_AddIntConstant(m, "MSG_DONTWAIT", MSG_DONTWAIT);
4805 #endif
4806 #ifdef MSG_EOR
4807 PyModule_AddIntConstant(m, "MSG_EOR", MSG_EOR);
4808 #endif
4809 #ifdef MSG_TRUNC
4810 PyModule_AddIntConstant(m, "MSG_TRUNC", MSG_TRUNC);
4811 #endif
4812 #ifdef MSG_CTRUNC
4813 PyModule_AddIntConstant(m, "MSG_CTRUNC", MSG_CTRUNC);
4814 #endif
4815 #ifdef MSG_WAITALL
4816 PyModule_AddIntConstant(m, "MSG_WAITALL", MSG_WAITALL);
4817 #endif
4818 #ifdef MSG_BTAG
4819 PyModule_AddIntConstant(m, "MSG_BTAG", MSG_BTAG);
4820 #endif
4821 #ifdef MSG_ETAG
4822 PyModule_AddIntConstant(m, "MSG_ETAG", MSG_ETAG);
4823 #endif
4825 /* Protocol level and numbers, usable for [gs]etsockopt */
4826 #ifdef SOL_SOCKET
4827 PyModule_AddIntConstant(m, "SOL_SOCKET", SOL_SOCKET);
4828 #endif
4829 #ifdef SOL_IP
4830 PyModule_AddIntConstant(m, "SOL_IP", SOL_IP);
4831 #else
4832 PyModule_AddIntConstant(m, "SOL_IP", 0);
4833 #endif
4834 #ifdef SOL_IPX
4835 PyModule_AddIntConstant(m, "SOL_IPX", SOL_IPX);
4836 #endif
4837 #ifdef SOL_AX25
4838 PyModule_AddIntConstant(m, "SOL_AX25", SOL_AX25);
4839 #endif
4840 #ifdef SOL_ATALK
4841 PyModule_AddIntConstant(m, "SOL_ATALK", SOL_ATALK);
4842 #endif
4843 #ifdef SOL_NETROM
4844 PyModule_AddIntConstant(m, "SOL_NETROM", SOL_NETROM);
4845 #endif
4846 #ifdef SOL_ROSE
4847 PyModule_AddIntConstant(m, "SOL_ROSE", SOL_ROSE);
4848 #endif
4849 #ifdef SOL_TCP
4850 PyModule_AddIntConstant(m, "SOL_TCP", SOL_TCP);
4851 #else
4852 PyModule_AddIntConstant(m, "SOL_TCP", 6);
4853 #endif
4854 #ifdef SOL_UDP
4855 PyModule_AddIntConstant(m, "SOL_UDP", SOL_UDP);
4856 #else
4857 PyModule_AddIntConstant(m, "SOL_UDP", 17);
4858 #endif
4859 #ifdef IPPROTO_IP
4860 PyModule_AddIntConstant(m, "IPPROTO_IP", IPPROTO_IP);
4861 #else
4862 PyModule_AddIntConstant(m, "IPPROTO_IP", 0);
4863 #endif
4864 #ifdef IPPROTO_HOPOPTS
4865 PyModule_AddIntConstant(m, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS);
4866 #endif
4867 #ifdef IPPROTO_ICMP
4868 PyModule_AddIntConstant(m, "IPPROTO_ICMP", IPPROTO_ICMP);
4869 #else
4870 PyModule_AddIntConstant(m, "IPPROTO_ICMP", 1);
4871 #endif
4872 #ifdef IPPROTO_IGMP
4873 PyModule_AddIntConstant(m, "IPPROTO_IGMP", IPPROTO_IGMP);
4874 #endif
4875 #ifdef IPPROTO_GGP
4876 PyModule_AddIntConstant(m, "IPPROTO_GGP", IPPROTO_GGP);
4877 #endif
4878 #ifdef IPPROTO_IPV4
4879 PyModule_AddIntConstant(m, "IPPROTO_IPV4", IPPROTO_IPV4);
4880 #endif
4881 #ifdef IPPROTO_IPV6
4882 PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
4883 #endif
4884 #ifdef IPPROTO_IPIP
4885 PyModule_AddIntConstant(m, "IPPROTO_IPIP", IPPROTO_IPIP);
4886 #endif
4887 #ifdef IPPROTO_TCP
4888 PyModule_AddIntConstant(m, "IPPROTO_TCP", IPPROTO_TCP);
4889 #else
4890 PyModule_AddIntConstant(m, "IPPROTO_TCP", 6);
4891 #endif
4892 #ifdef IPPROTO_EGP
4893 PyModule_AddIntConstant(m, "IPPROTO_EGP", IPPROTO_EGP);
4894 #endif
4895 #ifdef IPPROTO_PUP
4896 PyModule_AddIntConstant(m, "IPPROTO_PUP", IPPROTO_PUP);
4897 #endif
4898 #ifdef IPPROTO_UDP
4899 PyModule_AddIntConstant(m, "IPPROTO_UDP", IPPROTO_UDP);
4900 #else
4901 PyModule_AddIntConstant(m, "IPPROTO_UDP", 17);
4902 #endif
4903 #ifdef IPPROTO_IDP
4904 PyModule_AddIntConstant(m, "IPPROTO_IDP", IPPROTO_IDP);
4905 #endif
4906 #ifdef IPPROTO_HELLO
4907 PyModule_AddIntConstant(m, "IPPROTO_HELLO", IPPROTO_HELLO);
4908 #endif
4909 #ifdef IPPROTO_ND
4910 PyModule_AddIntConstant(m, "IPPROTO_ND", IPPROTO_ND);
4911 #endif
4912 #ifdef IPPROTO_TP
4913 PyModule_AddIntConstant(m, "IPPROTO_TP", IPPROTO_TP);
4914 #endif
4915 #ifdef IPPROTO_IPV6
4916 PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
4917 #endif
4918 #ifdef IPPROTO_ROUTING
4919 PyModule_AddIntConstant(m, "IPPROTO_ROUTING", IPPROTO_ROUTING);
4920 #endif
4921 #ifdef IPPROTO_FRAGMENT
4922 PyModule_AddIntConstant(m, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT);
4923 #endif
4924 #ifdef IPPROTO_RSVP
4925 PyModule_AddIntConstant(m, "IPPROTO_RSVP", IPPROTO_RSVP);
4926 #endif
4927 #ifdef IPPROTO_GRE
4928 PyModule_AddIntConstant(m, "IPPROTO_GRE", IPPROTO_GRE);
4929 #endif
4930 #ifdef IPPROTO_ESP
4931 PyModule_AddIntConstant(m, "IPPROTO_ESP", IPPROTO_ESP);
4932 #endif
4933 #ifdef IPPROTO_AH
4934 PyModule_AddIntConstant(m, "IPPROTO_AH", IPPROTO_AH);
4935 #endif
4936 #ifdef IPPROTO_MOBILE
4937 PyModule_AddIntConstant(m, "IPPROTO_MOBILE", IPPROTO_MOBILE);
4938 #endif
4939 #ifdef IPPROTO_ICMPV6
4940 PyModule_AddIntConstant(m, "IPPROTO_ICMPV6", IPPROTO_ICMPV6);
4941 #endif
4942 #ifdef IPPROTO_NONE
4943 PyModule_AddIntConstant(m, "IPPROTO_NONE", IPPROTO_NONE);
4944 #endif
4945 #ifdef IPPROTO_DSTOPTS
4946 PyModule_AddIntConstant(m, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS);
4947 #endif
4948 #ifdef IPPROTO_XTP
4949 PyModule_AddIntConstant(m, "IPPROTO_XTP", IPPROTO_XTP);
4950 #endif
4951 #ifdef IPPROTO_EON
4952 PyModule_AddIntConstant(m, "IPPROTO_EON", IPPROTO_EON);
4953 #endif
4954 #ifdef IPPROTO_PIM
4955 PyModule_AddIntConstant(m, "IPPROTO_PIM", IPPROTO_PIM);
4956 #endif
4957 #ifdef IPPROTO_IPCOMP
4958 PyModule_AddIntConstant(m, "IPPROTO_IPCOMP", IPPROTO_IPCOMP);
4959 #endif
4960 #ifdef IPPROTO_VRRP
4961 PyModule_AddIntConstant(m, "IPPROTO_VRRP", IPPROTO_VRRP);
4962 #endif
4963 #ifdef IPPROTO_BIP
4964 PyModule_AddIntConstant(m, "IPPROTO_BIP", IPPROTO_BIP);
4965 #endif
4966 /**/
4967 #ifdef IPPROTO_RAW
4968 PyModule_AddIntConstant(m, "IPPROTO_RAW", IPPROTO_RAW);
4969 #else
4970 PyModule_AddIntConstant(m, "IPPROTO_RAW", 255);
4971 #endif
4972 #ifdef IPPROTO_MAX
4973 PyModule_AddIntConstant(m, "IPPROTO_MAX", IPPROTO_MAX);
4974 #endif
4976 /* Some port configuration */
4977 #ifdef IPPORT_RESERVED
4978 PyModule_AddIntConstant(m, "IPPORT_RESERVED", IPPORT_RESERVED);
4979 #else
4980 PyModule_AddIntConstant(m, "IPPORT_RESERVED", 1024);
4981 #endif
4982 #ifdef IPPORT_USERRESERVED
4983 PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", IPPORT_USERRESERVED);
4984 #else
4985 PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", 5000);
4986 #endif
4988 /* Some reserved IP v.4 addresses */
4989 #ifdef INADDR_ANY
4990 PyModule_AddIntConstant(m, "INADDR_ANY", INADDR_ANY);
4991 #else
4992 PyModule_AddIntConstant(m, "INADDR_ANY", 0x00000000);
4993 #endif
4994 #ifdef INADDR_BROADCAST
4995 PyModule_AddIntConstant(m, "INADDR_BROADCAST", INADDR_BROADCAST);
4996 #else
4997 PyModule_AddIntConstant(m, "INADDR_BROADCAST", 0xffffffff);
4998 #endif
4999 #ifdef INADDR_LOOPBACK
5000 PyModule_AddIntConstant(m, "INADDR_LOOPBACK", INADDR_LOOPBACK);
5001 #else
5002 PyModule_AddIntConstant(m, "INADDR_LOOPBACK", 0x7F000001);
5003 #endif
5004 #ifdef INADDR_UNSPEC_GROUP
5005 PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
5006 #else
5007 PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", 0xe0000000);
5008 #endif
5009 #ifdef INADDR_ALLHOSTS_GROUP
5010 PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP",
5011 INADDR_ALLHOSTS_GROUP);
5012 #else
5013 PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
5014 #endif
5015 #ifdef INADDR_MAX_LOCAL_GROUP
5016 PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP",
5017 INADDR_MAX_LOCAL_GROUP);
5018 #else
5019 PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
5020 #endif
5021 #ifdef INADDR_NONE
5022 PyModule_AddIntConstant(m, "INADDR_NONE", INADDR_NONE);
5023 #else
5024 PyModule_AddIntConstant(m, "INADDR_NONE", 0xffffffff);
5025 #endif
5027 /* IPv4 [gs]etsockopt options */
5028 #ifdef IP_OPTIONS
5029 PyModule_AddIntConstant(m, "IP_OPTIONS", IP_OPTIONS);
5030 #endif
5031 #ifdef IP_HDRINCL
5032 PyModule_AddIntConstant(m, "IP_HDRINCL", IP_HDRINCL);
5033 #endif
5034 #ifdef IP_TOS
5035 PyModule_AddIntConstant(m, "IP_TOS", IP_TOS);
5036 #endif
5037 #ifdef IP_TTL
5038 PyModule_AddIntConstant(m, "IP_TTL", IP_TTL);
5039 #endif
5040 #ifdef IP_RECVOPTS
5041 PyModule_AddIntConstant(m, "IP_RECVOPTS", IP_RECVOPTS);
5042 #endif
5043 #ifdef IP_RECVRETOPTS
5044 PyModule_AddIntConstant(m, "IP_RECVRETOPTS", IP_RECVRETOPTS);
5045 #endif
5046 #ifdef IP_RECVDSTADDR
5047 PyModule_AddIntConstant(m, "IP_RECVDSTADDR", IP_RECVDSTADDR);
5048 #endif
5049 #ifdef IP_RETOPTS
5050 PyModule_AddIntConstant(m, "IP_RETOPTS", IP_RETOPTS);
5051 #endif
5052 #ifdef IP_MULTICAST_IF
5053 PyModule_AddIntConstant(m, "IP_MULTICAST_IF", IP_MULTICAST_IF);
5054 #endif
5055 #ifdef IP_MULTICAST_TTL
5056 PyModule_AddIntConstant(m, "IP_MULTICAST_TTL", IP_MULTICAST_TTL);
5057 #endif
5058 #ifdef IP_MULTICAST_LOOP
5059 PyModule_AddIntConstant(m, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
5060 #endif
5061 #ifdef IP_ADD_MEMBERSHIP
5062 PyModule_AddIntConstant(m, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
5063 #endif
5064 #ifdef IP_DROP_MEMBERSHIP
5065 PyModule_AddIntConstant(m, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
5066 #endif
5067 #ifdef IP_DEFAULT_MULTICAST_TTL
5068 PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_TTL",
5069 IP_DEFAULT_MULTICAST_TTL);
5070 #endif
5071 #ifdef IP_DEFAULT_MULTICAST_LOOP
5072 PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_LOOP",
5073 IP_DEFAULT_MULTICAST_LOOP);
5074 #endif
5075 #ifdef IP_MAX_MEMBERSHIPS
5076 PyModule_AddIntConstant(m, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS);
5077 #endif
5079 /* IPv6 [gs]etsockopt options, defined in RFC2553 */
5080 #ifdef IPV6_JOIN_GROUP
5081 PyModule_AddIntConstant(m, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP);
5082 #endif
5083 #ifdef IPV6_LEAVE_GROUP
5084 PyModule_AddIntConstant(m, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP);
5085 #endif
5086 #ifdef IPV6_MULTICAST_HOPS
5087 PyModule_AddIntConstant(m, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS);
5088 #endif
5089 #ifdef IPV6_MULTICAST_IF
5090 PyModule_AddIntConstant(m, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF);
5091 #endif
5092 #ifdef IPV6_MULTICAST_LOOP
5093 PyModule_AddIntConstant(m, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP);
5094 #endif
5095 #ifdef IPV6_UNICAST_HOPS
5096 PyModule_AddIntConstant(m, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS);
5097 #endif
5098 /* Additional IPV6 socket options, defined in RFC 3493 */
5099 #ifdef IPV6_V6ONLY
5100 PyModule_AddIntConstant(m, "IPV6_V6ONLY", IPV6_V6ONLY);
5101 #endif
5102 /* Advanced IPV6 socket options, from RFC 3542 */
5103 #ifdef IPV6_CHECKSUM
5104 PyModule_AddIntConstant(m, "IPV6_CHECKSUM", IPV6_CHECKSUM);
5105 #endif
5106 #ifdef IPV6_DONTFRAG
5107 PyModule_AddIntConstant(m, "IPV6_DONTFRAG", IPV6_DONTFRAG);
5108 #endif
5109 #ifdef IPV6_DSTOPTS
5110 PyModule_AddIntConstant(m, "IPV6_DSTOPTS", IPV6_DSTOPTS);
5111 #endif
5112 #ifdef IPV6_HOPLIMIT
5113 PyModule_AddIntConstant(m, "IPV6_HOPLIMIT", IPV6_HOPLIMIT);
5114 #endif
5115 #ifdef IPV6_HOPOPTS
5116 PyModule_AddIntConstant(m, "IPV6_HOPOPTS", IPV6_HOPOPTS);
5117 #endif
5118 #ifdef IPV6_NEXTHOP
5119 PyModule_AddIntConstant(m, "IPV6_NEXTHOP", IPV6_NEXTHOP);
5120 #endif
5121 #ifdef IPV6_PATHMTU
5122 PyModule_AddIntConstant(m, "IPV6_PATHMTU", IPV6_PATHMTU);
5123 #endif
5124 #ifdef IPV6_PKTINFO
5125 PyModule_AddIntConstant(m, "IPV6_PKTINFO", IPV6_PKTINFO);
5126 #endif
5127 #ifdef IPV6_RECVDSTOPTS
5128 PyModule_AddIntConstant(m, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS);
5129 #endif
5130 #ifdef IPV6_RECVHOPLIMIT
5131 PyModule_AddIntConstant(m, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT);
5132 #endif
5133 #ifdef IPV6_RECVHOPOPTS
5134 PyModule_AddIntConstant(m, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS);
5135 #endif
5136 #ifdef IPV6_RECVPKTINFO
5137 PyModule_AddIntConstant(m, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO);
5138 #endif
5139 #ifdef IPV6_RECVRTHDR
5140 PyModule_AddIntConstant(m, "IPV6_RECVRTHDR", IPV6_RECVRTHDR);
5141 #endif
5142 #ifdef IPV6_RECVTCLASS
5143 PyModule_AddIntConstant(m, "IPV6_RECVTCLASS", IPV6_RECVTCLASS);
5144 #endif
5145 #ifdef IPV6_RTHDR
5146 PyModule_AddIntConstant(m, "IPV6_RTHDR", IPV6_RTHDR);
5147 #endif
5148 #ifdef IPV6_RTHDRDSTOPTS
5149 PyModule_AddIntConstant(m, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS);
5150 #endif
5151 #ifdef IPV6_RTHDR_TYPE_0
5152 PyModule_AddIntConstant(m, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0);
5153 #endif
5154 #ifdef IPV6_RECVPATHMTU
5155 PyModule_AddIntConstant(m, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU);
5156 #endif
5157 #ifdef IPV6_TCLASS
5158 PyModule_AddIntConstant(m, "IPV6_TCLASS", IPV6_TCLASS);
5159 #endif
5160 #ifdef IPV6_USE_MIN_MTU
5161 PyModule_AddIntConstant(m, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU);
5162 #endif
5164 /* TCP options */
5165 #ifdef TCP_NODELAY
5166 PyModule_AddIntConstant(m, "TCP_NODELAY", TCP_NODELAY);
5167 #endif
5168 #ifdef TCP_MAXSEG
5169 PyModule_AddIntConstant(m, "TCP_MAXSEG", TCP_MAXSEG);
5170 #endif
5171 #ifdef TCP_CORK
5172 PyModule_AddIntConstant(m, "TCP_CORK", TCP_CORK);
5173 #endif
5174 #ifdef TCP_KEEPIDLE
5175 PyModule_AddIntConstant(m, "TCP_KEEPIDLE", TCP_KEEPIDLE);
5176 #endif
5177 #ifdef TCP_KEEPINTVL
5178 PyModule_AddIntConstant(m, "TCP_KEEPINTVL", TCP_KEEPINTVL);
5179 #endif
5180 #ifdef TCP_KEEPCNT
5181 PyModule_AddIntConstant(m, "TCP_KEEPCNT", TCP_KEEPCNT);
5182 #endif
5183 #ifdef TCP_SYNCNT
5184 PyModule_AddIntConstant(m, "TCP_SYNCNT", TCP_SYNCNT);
5185 #endif
5186 #ifdef TCP_LINGER2
5187 PyModule_AddIntConstant(m, "TCP_LINGER2", TCP_LINGER2);
5188 #endif
5189 #ifdef TCP_DEFER_ACCEPT
5190 PyModule_AddIntConstant(m, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT);
5191 #endif
5192 #ifdef TCP_WINDOW_CLAMP
5193 PyModule_AddIntConstant(m, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP);
5194 #endif
5195 #ifdef TCP_INFO
5196 PyModule_AddIntConstant(m, "TCP_INFO", TCP_INFO);
5197 #endif
5198 #ifdef TCP_QUICKACK
5199 PyModule_AddIntConstant(m, "TCP_QUICKACK", TCP_QUICKACK);
5200 #endif
5203 /* IPX options */
5204 #ifdef IPX_TYPE
5205 PyModule_AddIntConstant(m, "IPX_TYPE", IPX_TYPE);
5206 #endif
5208 /* get{addr,name}info parameters */
5209 #ifdef EAI_ADDRFAMILY
5210 PyModule_AddIntConstant(m, "EAI_ADDRFAMILY", EAI_ADDRFAMILY);
5211 #endif
5212 #ifdef EAI_AGAIN
5213 PyModule_AddIntConstant(m, "EAI_AGAIN", EAI_AGAIN);
5214 #endif
5215 #ifdef EAI_BADFLAGS
5216 PyModule_AddIntConstant(m, "EAI_BADFLAGS", EAI_BADFLAGS);
5217 #endif
5218 #ifdef EAI_FAIL
5219 PyModule_AddIntConstant(m, "EAI_FAIL", EAI_FAIL);
5220 #endif
5221 #ifdef EAI_FAMILY
5222 PyModule_AddIntConstant(m, "EAI_FAMILY", EAI_FAMILY);
5223 #endif
5224 #ifdef EAI_MEMORY
5225 PyModule_AddIntConstant(m, "EAI_MEMORY", EAI_MEMORY);
5226 #endif
5227 #ifdef EAI_NODATA
5228 PyModule_AddIntConstant(m, "EAI_NODATA", EAI_NODATA);
5229 #endif
5230 #ifdef EAI_NONAME
5231 PyModule_AddIntConstant(m, "EAI_NONAME", EAI_NONAME);
5232 #endif
5233 #ifdef EAI_OVERFLOW
5234 PyModule_AddIntConstant(m, "EAI_OVERFLOW", EAI_OVERFLOW);
5235 #endif
5236 #ifdef EAI_SERVICE
5237 PyModule_AddIntConstant(m, "EAI_SERVICE", EAI_SERVICE);
5238 #endif
5239 #ifdef EAI_SOCKTYPE
5240 PyModule_AddIntConstant(m, "EAI_SOCKTYPE", EAI_SOCKTYPE);
5241 #endif
5242 #ifdef EAI_SYSTEM
5243 PyModule_AddIntConstant(m, "EAI_SYSTEM", EAI_SYSTEM);
5244 #endif
5245 #ifdef EAI_BADHINTS
5246 PyModule_AddIntConstant(m, "EAI_BADHINTS", EAI_BADHINTS);
5247 #endif
5248 #ifdef EAI_PROTOCOL
5249 PyModule_AddIntConstant(m, "EAI_PROTOCOL", EAI_PROTOCOL);
5250 #endif
5251 #ifdef EAI_MAX
5252 PyModule_AddIntConstant(m, "EAI_MAX", EAI_MAX);
5253 #endif
5254 #ifdef AI_PASSIVE
5255 PyModule_AddIntConstant(m, "AI_PASSIVE", AI_PASSIVE);
5256 #endif
5257 #ifdef AI_CANONNAME
5258 PyModule_AddIntConstant(m, "AI_CANONNAME", AI_CANONNAME);
5259 #endif
5260 #ifdef AI_NUMERICHOST
5261 PyModule_AddIntConstant(m, "AI_NUMERICHOST", AI_NUMERICHOST);
5262 #endif
5263 #ifdef AI_NUMERICSERV
5264 PyModule_AddIntConstant(m, "AI_NUMERICSERV", AI_NUMERICSERV);
5265 #endif
5266 #ifdef AI_MASK
5267 PyModule_AddIntConstant(m, "AI_MASK", AI_MASK);
5268 #endif
5269 #ifdef AI_ALL
5270 PyModule_AddIntConstant(m, "AI_ALL", AI_ALL);
5271 #endif
5272 #ifdef AI_V4MAPPED_CFG
5273 PyModule_AddIntConstant(m, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG);
5274 #endif
5275 #ifdef AI_ADDRCONFIG
5276 PyModule_AddIntConstant(m, "AI_ADDRCONFIG", AI_ADDRCONFIG);
5277 #endif
5278 #ifdef AI_V4MAPPED
5279 PyModule_AddIntConstant(m, "AI_V4MAPPED", AI_V4MAPPED);
5280 #endif
5281 #ifdef AI_DEFAULT
5282 PyModule_AddIntConstant(m, "AI_DEFAULT", AI_DEFAULT);
5283 #endif
5284 #ifdef NI_MAXHOST
5285 PyModule_AddIntConstant(m, "NI_MAXHOST", NI_MAXHOST);
5286 #endif
5287 #ifdef NI_MAXSERV
5288 PyModule_AddIntConstant(m, "NI_MAXSERV", NI_MAXSERV);
5289 #endif
5290 #ifdef NI_NOFQDN
5291 PyModule_AddIntConstant(m, "NI_NOFQDN", NI_NOFQDN);
5292 #endif
5293 #ifdef NI_NUMERICHOST
5294 PyModule_AddIntConstant(m, "NI_NUMERICHOST", NI_NUMERICHOST);
5295 #endif
5296 #ifdef NI_NAMEREQD
5297 PyModule_AddIntConstant(m, "NI_NAMEREQD", NI_NAMEREQD);
5298 #endif
5299 #ifdef NI_NUMERICSERV
5300 PyModule_AddIntConstant(m, "NI_NUMERICSERV", NI_NUMERICSERV);
5301 #endif
5302 #ifdef NI_DGRAM
5303 PyModule_AddIntConstant(m, "NI_DGRAM", NI_DGRAM);
5304 #endif
5306 /* shutdown() parameters */
5307 #ifdef SHUT_RD
5308 PyModule_AddIntConstant(m, "SHUT_RD", SHUT_RD);
5309 #elif defined(SD_RECEIVE)
5310 PyModule_AddIntConstant(m, "SHUT_RD", SD_RECEIVE);
5311 #else
5312 PyModule_AddIntConstant(m, "SHUT_RD", 0);
5313 #endif
5314 #ifdef SHUT_WR
5315 PyModule_AddIntConstant(m, "SHUT_WR", SHUT_WR);
5316 #elif defined(SD_SEND)
5317 PyModule_AddIntConstant(m, "SHUT_WR", SD_SEND);
5318 #else
5319 PyModule_AddIntConstant(m, "SHUT_WR", 1);
5320 #endif
5321 #ifdef SHUT_RDWR
5322 PyModule_AddIntConstant(m, "SHUT_RDWR", SHUT_RDWR);
5323 #elif defined(SD_BOTH)
5324 PyModule_AddIntConstant(m, "SHUT_RDWR", SD_BOTH);
5325 #else
5326 PyModule_AddIntConstant(m, "SHUT_RDWR", 2);
5327 #endif
5329 #ifdef SIO_RCVALL
5331 DWORD codes[] = {SIO_RCVALL, SIO_KEEPALIVE_VALS};
5332 const char *names[] = {"SIO_RCVALL", "SIO_KEEPALIVE_VALS"};
5333 int i;
5334 for(i = 0; i<sizeof(codes)/sizeof(*codes); ++i) {
5335 PyObject *tmp;
5336 tmp = PyLong_FromUnsignedLong(codes[i]);
5337 if (tmp == NULL)
5338 return;
5339 PyModule_AddObject(m, names[i], tmp);
5342 PyModule_AddIntConstant(m, "RCVALL_OFF", RCVALL_OFF);
5343 PyModule_AddIntConstant(m, "RCVALL_ON", RCVALL_ON);
5344 PyModule_AddIntConstant(m, "RCVALL_SOCKETLEVELONLY", RCVALL_SOCKETLEVELONLY);
5345 #ifdef RCVALL_IPLEVEL
5346 PyModule_AddIntConstant(m, "RCVALL_IPLEVEL", RCVALL_IPLEVEL);
5347 #endif
5348 #ifdef RCVALL_MAX
5349 PyModule_AddIntConstant(m, "RCVALL_MAX", RCVALL_MAX);
5350 #endif
5351 #endif /* _MSTCPIP_ */
5353 /* Initialize gethostbyname lock */
5354 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
5355 netdb_lock = PyThread_allocate_lock();
5356 #endif
5360 #ifndef HAVE_INET_PTON
5361 #if !defined(NTDDI_VERSION) || (NTDDI_VERSION < NTDDI_LONGHORN)
5363 /* Simplistic emulation code for inet_pton that only works for IPv4 */
5364 /* These are not exposed because they do not set errno properly */
5367 inet_pton(int af, const char *src, void *dst)
5369 if (af == AF_INET) {
5370 #if (SIZEOF_INT != 4)
5371 #error "Not sure if in_addr_t exists and int is not 32-bits."
5372 #endif
5373 unsigned int packed_addr;
5374 packed_addr = inet_addr(src);
5375 if (packed_addr == INADDR_NONE)
5376 return 0;
5377 memcpy(dst, &packed_addr, 4);
5378 return 1;
5380 /* Should set errno to EAFNOSUPPORT */
5381 return -1;
5384 const char *
5385 inet_ntop(int af, const void *src, char *dst, socklen_t size)
5387 if (af == AF_INET) {
5388 struct in_addr packed_addr;
5389 if (size < 16)
5390 /* Should set errno to ENOSPC. */
5391 return NULL;
5392 memcpy(&packed_addr, src, sizeof(packed_addr));
5393 return strncpy(dst, inet_ntoa(packed_addr), size);
5395 /* Should set errno to EAFNOSUPPORT */
5396 return NULL;
5399 #endif
5400 #endif