Silence the DeprecationWarning raised by importing mimetools in BaseHTTPServer.
[python.git] / Modules / socketmodule.c
blobdeff28a1be9a13b255ec3f49af60c614cbb75a6c
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)
383 #define USE_BLUETOOTH 1
384 #if defined(__FreeBSD__)
385 #define BTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP
386 #define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM
387 #define BTPROTO_HCI BLUETOOTH_PROTO_HCI
388 #define SOL_HCI SOL_HCI_RAW
389 #define HCI_FILTER SO_HCI_RAW_FILTER
390 #define sockaddr_l2 sockaddr_l2cap
391 #define sockaddr_rc sockaddr_rfcomm
392 #define hci_dev hci_node
393 #define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb)
394 #define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)
395 #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
396 #elif defined(__NetBSD__)
397 #define sockaddr_l2 sockaddr_bt
398 #define sockaddr_rc sockaddr_bt
399 #define sockaddr_hci sockaddr_bt
400 #define sockaddr_sco sockaddr_bt
401 #define _BT_L2_MEMB(sa, memb) ((sa)->bt_##memb)
402 #define _BT_RC_MEMB(sa, memb) ((sa)->bt_##memb)
403 #define _BT_HCI_MEMB(sa, memb) ((sa)->bt_##memb)
404 #define _BT_SCO_MEMB(sa, memb) ((sa)->bt_##memb)
405 #else
406 #define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb)
407 #define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb)
408 #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
409 #define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)
410 #endif
411 #endif
413 #ifdef __VMS
414 /* TCP/IP Services for VMS uses a maximum send/recv buffer length */
415 #define SEGMENT_SIZE (32 * 1024 -1)
416 #endif
418 #define SAS2SA(x) ((struct sockaddr *)(x))
421 * Constants for getnameinfo()
423 #if !defined(NI_MAXHOST)
424 #define NI_MAXHOST 1025
425 #endif
426 #if !defined(NI_MAXSERV)
427 #define NI_MAXSERV 32
428 #endif
430 /* XXX There's a problem here: *static* functions are not supposed to have
431 a Py prefix (or use CapitalizedWords). Later... */
433 /* Global variable holding the exception type for errors detected
434 by this module (but not argument type or memory errors, etc.). */
435 static PyObject *socket_error;
436 static PyObject *socket_herror;
437 static PyObject *socket_gaierror;
438 static PyObject *socket_timeout;
440 #ifdef RISCOS
441 /* Global variable which is !=0 if Python is running in a RISC OS taskwindow */
442 static int taskwindow;
443 #endif
445 /* A forward reference to the socket type object.
446 The sock_type variable contains pointers to various functions,
447 some of which call new_sockobject(), which uses sock_type, so
448 there has to be a circular reference. */
449 static PyTypeObject sock_type;
451 #if defined(HAVE_POLL_H)
452 #include <poll.h>
453 #elif defined(HAVE_SYS_POLL_H)
454 #include <sys/poll.h>
455 #endif
457 #ifdef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
458 /* Platform can select file descriptors beyond FD_SETSIZE */
459 #define IS_SELECTABLE(s) 1
460 #elif defined(HAVE_POLL)
461 /* Instead of select(), we'll use poll() since poll() works on any fd. */
462 #define IS_SELECTABLE(s) 1
463 /* Can we call select() with this socket without a buffer overrun? */
464 #else
465 /* POSIX says selecting file descriptors beyond FD_SETSIZE
466 has undefined behaviour. If there's no timeout left, we don't have to
467 call select, so it's a safe, little white lie. */
468 #define IS_SELECTABLE(s) ((s)->sock_fd < FD_SETSIZE || s->sock_timeout <= 0.0)
469 #endif
471 static PyObject*
472 select_error(void)
474 PyErr_SetString(socket_error, "unable to select on socket");
475 return NULL;
478 /* Convenience function to raise an error according to errno
479 and return a NULL pointer from a function. */
481 static PyObject *
482 set_error(void)
484 #ifdef MS_WINDOWS
485 int err_no = WSAGetLastError();
486 /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which
487 recognizes the error codes used by both GetLastError() and
488 WSAGetLastError */
489 if (err_no)
490 return PyErr_SetExcFromWindowsErr(socket_error, err_no);
491 #endif
493 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
494 if (sock_errno() != NO_ERROR) {
495 APIRET rc;
496 ULONG msglen;
497 char outbuf[100];
498 int myerrorcode = sock_errno();
500 /* Retrieve socket-related error message from MPTN.MSG file */
501 rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf),
502 myerrorcode - SOCBASEERR + 26,
503 "mptn.msg",
504 &msglen);
505 if (rc == NO_ERROR) {
506 PyObject *v;
508 /* OS/2 doesn't guarantee a terminator */
509 outbuf[msglen] = '\0';
510 if (strlen(outbuf) > 0) {
511 /* If non-empty msg, trim CRLF */
512 char *lastc = &outbuf[ strlen(outbuf)-1 ];
513 while (lastc > outbuf &&
514 isspace(Py_CHARMASK(*lastc))) {
515 /* Trim trailing whitespace (CRLF) */
516 *lastc-- = '\0';
519 v = Py_BuildValue("(is)", myerrorcode, outbuf);
520 if (v != NULL) {
521 PyErr_SetObject(socket_error, v);
522 Py_DECREF(v);
524 return NULL;
527 #endif
529 #if defined(RISCOS)
530 if (_inet_error.errnum != NULL) {
531 PyObject *v;
532 v = Py_BuildValue("(is)", errno, _inet_err());
533 if (v != NULL) {
534 PyErr_SetObject(socket_error, v);
535 Py_DECREF(v);
537 return NULL;
539 #endif
541 return PyErr_SetFromErrno(socket_error);
545 static PyObject *
546 set_herror(int h_error)
548 PyObject *v;
550 #ifdef HAVE_HSTRERROR
551 v = Py_BuildValue("(is)", h_error, (char *)hstrerror(h_error));
552 #else
553 v = Py_BuildValue("(is)", h_error, "host not found");
554 #endif
555 if (v != NULL) {
556 PyErr_SetObject(socket_herror, v);
557 Py_DECREF(v);
560 return NULL;
564 static PyObject *
565 set_gaierror(int error)
567 PyObject *v;
569 #ifdef EAI_SYSTEM
570 /* EAI_SYSTEM is not available on Windows XP. */
571 if (error == EAI_SYSTEM)
572 return set_error();
573 #endif
575 #ifdef HAVE_GAI_STRERROR
576 v = Py_BuildValue("(is)", error, gai_strerror(error));
577 #else
578 v = Py_BuildValue("(is)", error, "getaddrinfo failed");
579 #endif
580 if (v != NULL) {
581 PyErr_SetObject(socket_gaierror, v);
582 Py_DECREF(v);
585 return NULL;
588 #ifdef __VMS
589 /* Function to send in segments */
590 static int
591 sendsegmented(int sock_fd, char *buf, int len, int flags)
593 int n = 0;
594 int remaining = len;
596 while (remaining > 0) {
597 unsigned int segment;
599 segment = (remaining >= SEGMENT_SIZE ? SEGMENT_SIZE : remaining);
600 n = send(sock_fd, buf, segment, flags);
601 if (n < 0) {
602 return n;
604 remaining -= segment;
605 buf += segment;
606 } /* end while */
608 return len;
610 #endif
612 /* Function to perform the setting of socket blocking mode
613 internally. block = (1 | 0). */
614 static int
615 internal_setblocking(PySocketSockObject *s, int block)
617 #ifndef RISCOS
618 #ifndef MS_WINDOWS
619 int delay_flag;
620 #endif
621 #endif
623 Py_BEGIN_ALLOW_THREADS
624 #ifdef __BEOS__
625 block = !block;
626 setsockopt(s->sock_fd, SOL_SOCKET, SO_NONBLOCK,
627 (void *)(&block), sizeof(int));
628 #else
629 #ifndef RISCOS
630 #ifndef MS_WINDOWS
631 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
632 block = !block;
633 ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block));
634 #elif defined(__VMS)
635 block = !block;
636 ioctl(s->sock_fd, FIONBIO, (unsigned int *)&block);
637 #else /* !PYOS_OS2 && !__VMS */
638 delay_flag = fcntl(s->sock_fd, F_GETFL, 0);
639 if (block)
640 delay_flag &= (~O_NONBLOCK);
641 else
642 delay_flag |= O_NONBLOCK;
643 fcntl(s->sock_fd, F_SETFL, delay_flag);
644 #endif /* !PYOS_OS2 */
645 #else /* MS_WINDOWS */
646 block = !block;
647 ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
648 #endif /* MS_WINDOWS */
649 #else /* RISCOS */
650 block = !block;
651 socketioctl(s->sock_fd, FIONBIO, (u_long*)&block);
652 #endif /* RISCOS */
653 #endif /* __BEOS__ */
654 Py_END_ALLOW_THREADS
656 /* Since these don't return anything */
657 return 1;
660 /* Do a select()/poll() on the socket, if necessary (sock_timeout > 0).
661 The argument writing indicates the direction.
662 This does not raise an exception; we'll let our caller do that
663 after they've reacquired the interpreter lock.
664 Returns 1 on timeout, -1 on error, 0 otherwise. */
665 static int
666 internal_select(PySocketSockObject *s, int writing)
668 int n;
670 /* Nothing to do unless we're in timeout mode (not non-blocking) */
671 if (s->sock_timeout <= 0.0)
672 return 0;
674 /* Guard against closed socket */
675 if (s->sock_fd < 0)
676 return 0;
678 /* Prefer poll, if available, since you can poll() any fd
679 * which can't be done with select(). */
680 #ifdef HAVE_POLL
682 struct pollfd pollfd;
683 int timeout;
685 pollfd.fd = s->sock_fd;
686 pollfd.events = writing ? POLLOUT : POLLIN;
688 /* s->sock_timeout is in seconds, timeout in ms */
689 timeout = (int)(s->sock_timeout * 1000 + 0.5);
690 n = poll(&pollfd, 1, timeout);
692 #else
694 /* Construct the arguments to select */
695 fd_set fds;
696 struct timeval tv;
697 tv.tv_sec = (int)s->sock_timeout;
698 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
699 FD_ZERO(&fds);
700 FD_SET(s->sock_fd, &fds);
702 /* See if the socket is ready */
703 if (writing)
704 n = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
705 else
706 n = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
708 #endif
710 if (n < 0)
711 return -1;
712 if (n == 0)
713 return 1;
714 return 0;
717 /* Initialize a new socket object. */
719 static double defaulttimeout = -1.0; /* Default timeout for new sockets */
721 PyMODINIT_FUNC
722 init_sockobject(PySocketSockObject *s,
723 SOCKET_T fd, int family, int type, int proto)
725 #ifdef RISCOS
726 int block = 1;
727 #endif
728 s->sock_fd = fd;
729 s->sock_family = family;
730 s->sock_type = type;
731 s->sock_proto = proto;
732 s->sock_timeout = defaulttimeout;
734 s->errorhandler = &set_error;
736 if (defaulttimeout >= 0.0)
737 internal_setblocking(s, 0);
739 #ifdef RISCOS
740 if (taskwindow)
741 socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
742 #endif
746 /* Create a new socket object.
747 This just creates the object and initializes it.
748 If the creation fails, return NULL and set an exception (implicit
749 in NEWOBJ()). */
751 static PySocketSockObject *
752 new_sockobject(SOCKET_T fd, int family, int type, int proto)
754 PySocketSockObject *s;
755 s = (PySocketSockObject *)
756 PyType_GenericNew(&sock_type, NULL, NULL);
757 if (s != NULL)
758 init_sockobject(s, fd, family, type, proto);
759 return s;
763 /* Lock to allow python interpreter to continue, but only allow one
764 thread to be in gethostbyname or getaddrinfo */
765 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
766 PyThread_type_lock netdb_lock;
767 #endif
770 /* Convert a string specifying a host name or one of a few symbolic
771 names to a numeric IP address. This usually calls gethostbyname()
772 to do the work; the names "" and "<broadcast>" are special.
773 Return the length (IPv4 should be 4 bytes), or negative if
774 an error occurred; then an exception is raised. */
776 static int
777 setipaddr(char *name, struct sockaddr *addr_ret, size_t addr_ret_size, int af)
779 struct addrinfo hints, *res;
780 int error;
781 int d1, d2, d3, d4;
782 char ch;
784 memset((void *) addr_ret, '\0', sizeof(*addr_ret));
785 if (name[0] == '\0') {
786 int siz;
787 memset(&hints, 0, sizeof(hints));
788 hints.ai_family = af;
789 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
790 hints.ai_flags = AI_PASSIVE;
791 Py_BEGIN_ALLOW_THREADS
792 ACQUIRE_GETADDRINFO_LOCK
793 error = getaddrinfo(NULL, "0", &hints, &res);
794 Py_END_ALLOW_THREADS
795 /* We assume that those thread-unsafe getaddrinfo() versions
796 *are* safe regarding their return value, ie. that a
797 subsequent call to getaddrinfo() does not destroy the
798 outcome of the first call. */
799 RELEASE_GETADDRINFO_LOCK
800 if (error) {
801 set_gaierror(error);
802 return -1;
804 switch (res->ai_family) {
805 case AF_INET:
806 siz = 4;
807 break;
808 #ifdef ENABLE_IPV6
809 case AF_INET6:
810 siz = 16;
811 break;
812 #endif
813 default:
814 freeaddrinfo(res);
815 PyErr_SetString(socket_error,
816 "unsupported address family");
817 return -1;
819 if (res->ai_next) {
820 freeaddrinfo(res);
821 PyErr_SetString(socket_error,
822 "wildcard resolved to multiple address");
823 return -1;
825 if (res->ai_addrlen < addr_ret_size)
826 addr_ret_size = res->ai_addrlen;
827 memcpy(addr_ret, res->ai_addr, addr_ret_size);
828 freeaddrinfo(res);
829 return siz;
831 if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
832 struct sockaddr_in *sin;
833 if (af != AF_INET && af != AF_UNSPEC) {
834 PyErr_SetString(socket_error,
835 "address family mismatched");
836 return -1;
838 sin = (struct sockaddr_in *)addr_ret;
839 memset((void *) sin, '\0', sizeof(*sin));
840 sin->sin_family = AF_INET;
841 #ifdef HAVE_SOCKADDR_SA_LEN
842 sin->sin_len = sizeof(*sin);
843 #endif
844 sin->sin_addr.s_addr = INADDR_BROADCAST;
845 return sizeof(sin->sin_addr);
847 if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 &&
848 0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 &&
849 0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) {
850 struct sockaddr_in *sin;
851 sin = (struct sockaddr_in *)addr_ret;
852 sin->sin_addr.s_addr = htonl(
853 ((long) d1 << 24) | ((long) d2 << 16) |
854 ((long) d3 << 8) | ((long) d4 << 0));
855 sin->sin_family = AF_INET;
856 #ifdef HAVE_SOCKADDR_SA_LEN
857 sin->sin_len = sizeof(*sin);
858 #endif
859 return 4;
861 memset(&hints, 0, sizeof(hints));
862 hints.ai_family = af;
863 Py_BEGIN_ALLOW_THREADS
864 ACQUIRE_GETADDRINFO_LOCK
865 error = getaddrinfo(name, NULL, &hints, &res);
866 #if defined(__digital__) && defined(__unix__)
867 if (error == EAI_NONAME && af == AF_UNSPEC) {
868 /* On Tru64 V5.1, numeric-to-addr conversion fails
869 if no address family is given. Assume IPv4 for now.*/
870 hints.ai_family = AF_INET;
871 error = getaddrinfo(name, NULL, &hints, &res);
873 #endif
874 Py_END_ALLOW_THREADS
875 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
876 if (error) {
877 set_gaierror(error);
878 return -1;
880 if (res->ai_addrlen < addr_ret_size)
881 addr_ret_size = res->ai_addrlen;
882 memcpy((char *) addr_ret, res->ai_addr, addr_ret_size);
883 freeaddrinfo(res);
884 switch (addr_ret->sa_family) {
885 case AF_INET:
886 return 4;
887 #ifdef ENABLE_IPV6
888 case AF_INET6:
889 return 16;
890 #endif
891 default:
892 PyErr_SetString(socket_error, "unknown address family");
893 return -1;
898 /* Create a string object representing an IP address.
899 This is always a string of the form 'dd.dd.dd.dd' (with variable
900 size numbers). */
902 static PyObject *
903 makeipaddr(struct sockaddr *addr, int addrlen)
905 char buf[NI_MAXHOST];
906 int error;
908 error = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0,
909 NI_NUMERICHOST);
910 if (error) {
911 set_gaierror(error);
912 return NULL;
914 return PyString_FromString(buf);
918 #ifdef USE_BLUETOOTH
919 /* Convert a string representation of a Bluetooth address into a numeric
920 address. Returns the length (6), or raises an exception and returns -1 if
921 an error occurred. */
923 static int
924 setbdaddr(char *name, bdaddr_t *bdaddr)
926 unsigned int b0, b1, b2, b3, b4, b5;
927 char ch;
928 int n;
930 n = sscanf(name, "%X:%X:%X:%X:%X:%X%c",
931 &b5, &b4, &b3, &b2, &b1, &b0, &ch);
932 if (n == 6 && (b0 | b1 | b2 | b3 | b4 | b5) < 256) {
933 bdaddr->b[0] = b0;
934 bdaddr->b[1] = b1;
935 bdaddr->b[2] = b2;
936 bdaddr->b[3] = b3;
937 bdaddr->b[4] = b4;
938 bdaddr->b[5] = b5;
939 return 6;
940 } else {
941 PyErr_SetString(socket_error, "bad bluetooth address");
942 return -1;
946 /* Create a string representation of the Bluetooth address. This is always a
947 string of the form 'XX:XX:XX:XX:XX:XX' where XX is a two digit hexadecimal
948 value (zero padded if necessary). */
950 static PyObject *
951 makebdaddr(bdaddr_t *bdaddr)
953 char buf[(6 * 2) + 5 + 1];
955 sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
956 bdaddr->b[5], bdaddr->b[4], bdaddr->b[3],
957 bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]);
958 return PyString_FromString(buf);
960 #endif
963 /* Create an object representing the given socket address,
964 suitable for passing it back to bind(), connect() etc.
965 The family field of the sockaddr structure is inspected
966 to determine what kind of address it really is. */
968 /*ARGSUSED*/
969 static PyObject *
970 makesockaddr(int sockfd, struct sockaddr *addr, int addrlen, int proto)
972 if (addrlen == 0) {
973 /* No address -- may be recvfrom() from known socket */
974 Py_INCREF(Py_None);
975 return Py_None;
978 #ifdef __BEOS__
979 /* XXX: BeOS version of accept() doesn't set family correctly */
980 addr->sa_family = AF_INET;
981 #endif
983 switch (addr->sa_family) {
985 case AF_INET:
987 struct sockaddr_in *a;
988 PyObject *addrobj = makeipaddr(addr, sizeof(*a));
989 PyObject *ret = NULL;
990 if (addrobj) {
991 a = (struct sockaddr_in *)addr;
992 ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
993 Py_DECREF(addrobj);
995 return ret;
998 #if defined(AF_UNIX)
999 case AF_UNIX:
1001 struct sockaddr_un *a = (struct sockaddr_un *) addr;
1002 #ifdef linux
1003 if (a->sun_path[0] == 0) { /* Linux abstract namespace */
1004 addrlen -= offsetof(struct sockaddr_un, sun_path);
1005 return PyString_FromStringAndSize(a->sun_path,
1006 addrlen);
1008 else
1009 #endif /* linux */
1011 /* regular NULL-terminated string */
1012 return PyString_FromString(a->sun_path);
1015 #endif /* AF_UNIX */
1017 #if defined(AF_NETLINK)
1018 case AF_NETLINK:
1020 struct sockaddr_nl *a = (struct sockaddr_nl *) addr;
1021 return Py_BuildValue("II", a->nl_pid, a->nl_groups);
1023 #endif /* AF_NETLINK */
1025 #ifdef ENABLE_IPV6
1026 case AF_INET6:
1028 struct sockaddr_in6 *a;
1029 PyObject *addrobj = makeipaddr(addr, sizeof(*a));
1030 PyObject *ret = NULL;
1031 if (addrobj) {
1032 a = (struct sockaddr_in6 *)addr;
1033 ret = Py_BuildValue("Oiii",
1034 addrobj,
1035 ntohs(a->sin6_port),
1036 a->sin6_flowinfo,
1037 a->sin6_scope_id);
1038 Py_DECREF(addrobj);
1040 return ret;
1042 #endif
1044 #ifdef USE_BLUETOOTH
1045 case AF_BLUETOOTH:
1046 switch (proto) {
1048 case BTPROTO_L2CAP:
1050 struct sockaddr_l2 *a = (struct sockaddr_l2 *) addr;
1051 PyObject *addrobj = makebdaddr(&_BT_L2_MEMB(a, bdaddr));
1052 PyObject *ret = NULL;
1053 if (addrobj) {
1054 ret = Py_BuildValue("Oi",
1055 addrobj,
1056 _BT_L2_MEMB(a, psm));
1057 Py_DECREF(addrobj);
1059 return ret;
1062 case BTPROTO_RFCOMM:
1064 struct sockaddr_rc *a = (struct sockaddr_rc *) addr;
1065 PyObject *addrobj = makebdaddr(&_BT_RC_MEMB(a, bdaddr));
1066 PyObject *ret = NULL;
1067 if (addrobj) {
1068 ret = Py_BuildValue("Oi",
1069 addrobj,
1070 _BT_RC_MEMB(a, channel));
1071 Py_DECREF(addrobj);
1073 return ret;
1076 case BTPROTO_HCI:
1078 struct sockaddr_hci *a = (struct sockaddr_hci *) addr;
1079 PyObject *ret = NULL;
1080 ret = Py_BuildValue("i", _BT_HCI_MEMB(a, dev));
1081 return ret;
1084 #if !defined(__FreeBSD__)
1085 case BTPROTO_SCO:
1087 struct sockaddr_sco *a = (struct sockaddr_sco *) addr;
1088 return makebdaddr(&_BT_SCO_MEMB(a, bdaddr));
1090 #endif
1093 #endif
1095 #ifdef HAVE_NETPACKET_PACKET_H
1096 case AF_PACKET:
1098 struct sockaddr_ll *a = (struct sockaddr_ll *)addr;
1099 char *ifname = "";
1100 struct ifreq ifr;
1101 /* need to look up interface name give index */
1102 if (a->sll_ifindex) {
1103 ifr.ifr_ifindex = a->sll_ifindex;
1104 if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0)
1105 ifname = ifr.ifr_name;
1107 return Py_BuildValue("shbhs#",
1108 ifname,
1109 ntohs(a->sll_protocol),
1110 a->sll_pkttype,
1111 a->sll_hatype,
1112 a->sll_addr,
1113 a->sll_halen);
1115 #endif
1117 #ifdef HAVE_LINUX_TIPC_H
1118 case AF_TIPC:
1120 struct sockaddr_tipc *a = (struct sockaddr_tipc *) addr;
1121 if (a->addrtype == TIPC_ADDR_NAMESEQ) {
1122 return Py_BuildValue("IIIII",
1123 a->addrtype,
1124 a->addr.nameseq.type,
1125 a->addr.nameseq.lower,
1126 a->addr.nameseq.upper,
1127 a->scope);
1128 } else if (a->addrtype == TIPC_ADDR_NAME) {
1129 return Py_BuildValue("IIIII",
1130 a->addrtype,
1131 a->addr.name.name.type,
1132 a->addr.name.name.instance,
1133 a->addr.name.name.instance,
1134 a->scope);
1135 } else if (a->addrtype == TIPC_ADDR_ID) {
1136 return Py_BuildValue("IIIII",
1137 a->addrtype,
1138 a->addr.id.node,
1139 a->addr.id.ref,
1141 a->scope);
1142 } else {
1143 PyErr_SetString(PyExc_TypeError,
1144 "Invalid address type");
1145 return NULL;
1148 #endif
1150 /* More cases here... */
1152 default:
1153 /* If we don't know the address family, don't raise an
1154 exception -- return it as a tuple. */
1155 return Py_BuildValue("is#",
1156 addr->sa_family,
1157 addr->sa_data,
1158 sizeof(addr->sa_data));
1164 /* Parse a socket address argument according to the socket object's
1165 address family. Return 1 if the address was in the proper format,
1166 0 of not. The address is returned through addr_ret, its length
1167 through len_ret. */
1169 static int
1170 getsockaddrarg(PySocketSockObject *s, PyObject *args,
1171 struct sockaddr *addr_ret, int *len_ret)
1173 switch (s->sock_family) {
1175 #if defined(AF_UNIX)
1176 case AF_UNIX:
1178 struct sockaddr_un* addr;
1179 char *path;
1180 int len;
1181 if (!PyArg_Parse(args, "t#", &path, &len))
1182 return 0;
1184 addr = (struct sockaddr_un*)addr_ret;
1185 #ifdef linux
1186 if (len > 0 && path[0] == 0) {
1187 /* Linux abstract namespace extension */
1188 if (len > sizeof addr->sun_path) {
1189 PyErr_SetString(socket_error,
1190 "AF_UNIX path too long");
1191 return 0;
1194 else
1195 #endif /* linux */
1197 /* regular NULL-terminated string */
1198 if (len >= sizeof addr->sun_path) {
1199 PyErr_SetString(socket_error,
1200 "AF_UNIX path too long");
1201 return 0;
1203 addr->sun_path[len] = 0;
1205 addr->sun_family = s->sock_family;
1206 memcpy(addr->sun_path, path, len);
1207 #if defined(PYOS_OS2)
1208 *len_ret = sizeof(*addr);
1209 #else
1210 *len_ret = len + offsetof(struct sockaddr_un, sun_path);
1211 #endif
1212 return 1;
1214 #endif /* AF_UNIX */
1216 #if defined(AF_NETLINK)
1217 case AF_NETLINK:
1219 struct sockaddr_nl* addr;
1220 int pid, groups;
1221 addr = (struct sockaddr_nl *)addr_ret;
1222 if (!PyTuple_Check(args)) {
1223 PyErr_Format(
1224 PyExc_TypeError,
1225 "getsockaddrarg: "
1226 "AF_NETLINK address must be tuple, not %.500s",
1227 Py_TYPE(args)->tp_name);
1228 return 0;
1230 if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &pid, &groups))
1231 return 0;
1232 addr->nl_family = AF_NETLINK;
1233 addr->nl_pid = pid;
1234 addr->nl_groups = groups;
1235 *len_ret = sizeof(*addr);
1236 return 1;
1238 #endif
1240 case AF_INET:
1242 struct sockaddr_in* addr;
1243 char *host;
1244 int port, result;
1245 if (!PyTuple_Check(args)) {
1246 PyErr_Format(
1247 PyExc_TypeError,
1248 "getsockaddrarg: "
1249 "AF_INET address must be tuple, not %.500s",
1250 Py_TYPE(args)->tp_name);
1251 return 0;
1253 if (!PyArg_ParseTuple(args, "eti:getsockaddrarg",
1254 "idna", &host, &port))
1255 return 0;
1256 addr=(struct sockaddr_in*)addr_ret;
1257 result = setipaddr(host, (struct sockaddr *)addr,
1258 sizeof(*addr), AF_INET);
1259 PyMem_Free(host);
1260 if (result < 0)
1261 return 0;
1262 addr->sin_family = AF_INET;
1263 addr->sin_port = htons((short)port);
1264 *len_ret = sizeof *addr;
1265 return 1;
1268 #ifdef ENABLE_IPV6
1269 case AF_INET6:
1271 struct sockaddr_in6* addr;
1272 char *host;
1273 int port, flowinfo, scope_id, result;
1274 flowinfo = scope_id = 0;
1275 if (!PyTuple_Check(args)) {
1276 PyErr_Format(
1277 PyExc_TypeError,
1278 "getsockaddrarg: "
1279 "AF_INET6 address must be tuple, not %.500s",
1280 Py_TYPE(args)->tp_name);
1281 return 0;
1283 if (!PyArg_ParseTuple(args, "eti|ii",
1284 "idna", &host, &port, &flowinfo,
1285 &scope_id)) {
1286 return 0;
1288 addr = (struct sockaddr_in6*)addr_ret;
1289 result = setipaddr(host, (struct sockaddr *)addr,
1290 sizeof(*addr), AF_INET6);
1291 PyMem_Free(host);
1292 if (result < 0)
1293 return 0;
1294 addr->sin6_family = s->sock_family;
1295 addr->sin6_port = htons((short)port);
1296 addr->sin6_flowinfo = flowinfo;
1297 addr->sin6_scope_id = scope_id;
1298 *len_ret = sizeof *addr;
1299 return 1;
1301 #endif
1303 #ifdef USE_BLUETOOTH
1304 case AF_BLUETOOTH:
1306 switch (s->sock_proto) {
1307 case BTPROTO_L2CAP:
1309 struct sockaddr_l2 *addr;
1310 char *straddr;
1312 addr = (struct sockaddr_l2 *)addr_ret;
1313 _BT_L2_MEMB(addr, family) = AF_BLUETOOTH;
1314 if (!PyArg_ParseTuple(args, "si", &straddr,
1315 &_BT_L2_MEMB(addr, psm))) {
1316 PyErr_SetString(socket_error, "getsockaddrarg: "
1317 "wrong format");
1318 return 0;
1320 if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0)
1321 return 0;
1323 *len_ret = sizeof *addr;
1324 return 1;
1326 case BTPROTO_RFCOMM:
1328 struct sockaddr_rc *addr;
1329 char *straddr;
1331 addr = (struct sockaddr_rc *)addr_ret;
1332 _BT_RC_MEMB(addr, family) = AF_BLUETOOTH;
1333 if (!PyArg_ParseTuple(args, "si", &straddr,
1334 &_BT_RC_MEMB(addr, channel))) {
1335 PyErr_SetString(socket_error, "getsockaddrarg: "
1336 "wrong format");
1337 return 0;
1339 if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0)
1340 return 0;
1342 *len_ret = sizeof *addr;
1343 return 1;
1345 case BTPROTO_HCI:
1347 struct sockaddr_hci *addr = (struct sockaddr_hci *)addr_ret;
1348 _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH;
1349 if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) {
1350 PyErr_SetString(socket_error, "getsockaddrarg: "
1351 "wrong format");
1352 return 0;
1354 *len_ret = sizeof *addr;
1355 return 1;
1357 #if !defined(__FreeBSD__)
1358 case BTPROTO_SCO:
1360 struct sockaddr_sco *addr;
1361 char *straddr;
1363 addr = (struct sockaddr_sco *)addr_ret;
1364 _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH;
1365 straddr = PyString_AsString(args);
1366 if (straddr == NULL) {
1367 PyErr_SetString(socket_error, "getsockaddrarg: "
1368 "wrong format");
1369 return 0;
1371 if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0)
1372 return 0;
1374 *len_ret = sizeof *addr;
1375 return 1;
1377 #endif
1378 default:
1379 PyErr_SetString(socket_error, "getsockaddrarg: unknown Bluetooth protocol");
1380 return 0;
1383 #endif
1385 #ifdef HAVE_NETPACKET_PACKET_H
1386 case AF_PACKET:
1388 struct sockaddr_ll* addr;
1389 struct ifreq ifr;
1390 char *interfaceName;
1391 int protoNumber;
1392 int hatype = 0;
1393 int pkttype = 0;
1394 char *haddr = NULL;
1395 unsigned int halen = 0;
1397 if (!PyTuple_Check(args)) {
1398 PyErr_Format(
1399 PyExc_TypeError,
1400 "getsockaddrarg: "
1401 "AF_PACKET address must be tuple, not %.500s",
1402 Py_TYPE(args)->tp_name);
1403 return 0;
1405 if (!PyArg_ParseTuple(args, "si|iis#", &interfaceName,
1406 &protoNumber, &pkttype, &hatype,
1407 &haddr, &halen))
1408 return 0;
1409 strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name));
1410 ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
1411 if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
1412 s->errorhandler();
1413 return 0;
1415 if (halen > 8) {
1416 PyErr_SetString(PyExc_ValueError,
1417 "Hardware address must be 8 bytes or less");
1418 return 0;
1420 addr = (struct sockaddr_ll*)addr_ret;
1421 addr->sll_family = AF_PACKET;
1422 addr->sll_protocol = htons((short)protoNumber);
1423 addr->sll_ifindex = ifr.ifr_ifindex;
1424 addr->sll_pkttype = pkttype;
1425 addr->sll_hatype = hatype;
1426 if (halen != 0) {
1427 memcpy(&addr->sll_addr, haddr, halen);
1429 addr->sll_halen = halen;
1430 *len_ret = sizeof *addr;
1431 return 1;
1433 #endif
1435 #ifdef HAVE_LINUX_TIPC_H
1436 case AF_TIPC:
1438 unsigned int atype, v1, v2, v3;
1439 unsigned int scope = TIPC_CLUSTER_SCOPE;
1440 struct sockaddr_tipc *addr;
1442 if (!PyTuple_Check(args)) {
1443 PyErr_Format(
1444 PyExc_TypeError,
1445 "getsockaddrarg: "
1446 "AF_TIPC address must be tuple, not %.500s",
1447 Py_TYPE(args)->tp_name);
1448 return 0;
1451 if (!PyArg_ParseTuple(args,
1452 "IIII|I;Invalid TIPC address format",
1453 &atype, &v1, &v2, &v3, &scope))
1454 return 0;
1456 addr = (struct sockaddr_tipc *) addr_ret;
1457 memset(addr, 0, sizeof(struct sockaddr_tipc));
1459 addr->family = AF_TIPC;
1460 addr->scope = scope;
1461 addr->addrtype = atype;
1463 if (atype == TIPC_ADDR_NAMESEQ) {
1464 addr->addr.nameseq.type = v1;
1465 addr->addr.nameseq.lower = v2;
1466 addr->addr.nameseq.upper = v3;
1467 } else if (atype == TIPC_ADDR_NAME) {
1468 addr->addr.name.name.type = v1;
1469 addr->addr.name.name.instance = v2;
1470 } else if (atype == TIPC_ADDR_ID) {
1471 addr->addr.id.node = v1;
1472 addr->addr.id.ref = v2;
1473 } else {
1474 /* Shouldn't happen */
1475 PyErr_SetString(PyExc_TypeError, "Invalid address type");
1476 return 0;
1479 *len_ret = sizeof(*addr);
1481 return 1;
1483 #endif
1485 /* More cases here... */
1487 default:
1488 PyErr_SetString(socket_error, "getsockaddrarg: bad family");
1489 return 0;
1495 /* Get the address length according to the socket object's address family.
1496 Return 1 if the family is known, 0 otherwise. The length is returned
1497 through len_ret. */
1499 static int
1500 getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
1502 switch (s->sock_family) {
1504 #if defined(AF_UNIX)
1505 case AF_UNIX:
1507 *len_ret = sizeof (struct sockaddr_un);
1508 return 1;
1510 #endif /* AF_UNIX */
1511 #if defined(AF_NETLINK)
1512 case AF_NETLINK:
1514 *len_ret = sizeof (struct sockaddr_nl);
1515 return 1;
1517 #endif
1519 case AF_INET:
1521 *len_ret = sizeof (struct sockaddr_in);
1522 return 1;
1525 #ifdef ENABLE_IPV6
1526 case AF_INET6:
1528 *len_ret = sizeof (struct sockaddr_in6);
1529 return 1;
1531 #endif
1533 #ifdef USE_BLUETOOTH
1534 case AF_BLUETOOTH:
1536 switch(s->sock_proto)
1539 case BTPROTO_L2CAP:
1540 *len_ret = sizeof (struct sockaddr_l2);
1541 return 1;
1542 case BTPROTO_RFCOMM:
1543 *len_ret = sizeof (struct sockaddr_rc);
1544 return 1;
1545 case BTPROTO_HCI:
1546 *len_ret = sizeof (struct sockaddr_hci);
1547 return 1;
1548 #if !defined(__FreeBSD__)
1549 case BTPROTO_SCO:
1550 *len_ret = sizeof (struct sockaddr_sco);
1551 return 1;
1552 #endif
1553 default:
1554 PyErr_SetString(socket_error, "getsockaddrlen: "
1555 "unknown BT protocol");
1556 return 0;
1560 #endif
1562 #ifdef HAVE_NETPACKET_PACKET_H
1563 case AF_PACKET:
1565 *len_ret = sizeof (struct sockaddr_ll);
1566 return 1;
1568 #endif
1570 #ifdef HAVE_LINUX_TIPC_H
1571 case AF_TIPC:
1573 *len_ret = sizeof (struct sockaddr_tipc);
1574 return 1;
1576 #endif
1578 /* More cases here... */
1580 default:
1581 PyErr_SetString(socket_error, "getsockaddrlen: bad family");
1582 return 0;
1588 /* s.accept() method */
1590 static PyObject *
1591 sock_accept(PySocketSockObject *s)
1593 sock_addr_t addrbuf;
1594 SOCKET_T newfd;
1595 socklen_t addrlen;
1596 PyObject *sock = NULL;
1597 PyObject *addr = NULL;
1598 PyObject *res = NULL;
1599 int timeout;
1601 if (!getsockaddrlen(s, &addrlen))
1602 return NULL;
1603 memset(&addrbuf, 0, addrlen);
1605 #ifdef MS_WINDOWS
1606 newfd = INVALID_SOCKET;
1607 #else
1608 newfd = -1;
1609 #endif
1611 if (!IS_SELECTABLE(s))
1612 return select_error();
1614 Py_BEGIN_ALLOW_THREADS
1615 timeout = internal_select(s, 0);
1616 if (!timeout)
1617 newfd = accept(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
1618 Py_END_ALLOW_THREADS
1620 if (timeout == 1) {
1621 PyErr_SetString(socket_timeout, "timed out");
1622 return NULL;
1625 #ifdef MS_WINDOWS
1626 if (newfd == INVALID_SOCKET)
1627 #else
1628 if (newfd < 0)
1629 #endif
1630 return s->errorhandler();
1632 /* Create the new object with unspecified family,
1633 to avoid calls to bind() etc. on it. */
1634 sock = (PyObject *) new_sockobject(newfd,
1635 s->sock_family,
1636 s->sock_type,
1637 s->sock_proto);
1639 if (sock == NULL) {
1640 SOCKETCLOSE(newfd);
1641 goto finally;
1643 addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
1644 addrlen, s->sock_proto);
1645 if (addr == NULL)
1646 goto finally;
1648 res = PyTuple_Pack(2, sock, addr);
1650 finally:
1651 Py_XDECREF(sock);
1652 Py_XDECREF(addr);
1653 return res;
1656 PyDoc_STRVAR(accept_doc,
1657 "accept() -> (socket object, address info)\n\
1659 Wait for an incoming connection. Return a new socket representing the\n\
1660 connection, and the address of the client. For IP sockets, the address\n\
1661 info is a pair (hostaddr, port).");
1663 /* s.setblocking(flag) method. Argument:
1664 False -- non-blocking mode; same as settimeout(0)
1665 True -- blocking mode; same as settimeout(None)
1668 static PyObject *
1669 sock_setblocking(PySocketSockObject *s, PyObject *arg)
1671 int block;
1673 block = PyInt_AsLong(arg);
1674 if (block == -1 && PyErr_Occurred())
1675 return NULL;
1677 s->sock_timeout = block ? -1.0 : 0.0;
1678 internal_setblocking(s, block);
1680 Py_INCREF(Py_None);
1681 return Py_None;
1684 PyDoc_STRVAR(setblocking_doc,
1685 "setblocking(flag)\n\
1687 Set the socket to blocking (flag is true) or non-blocking (false).\n\
1688 setblocking(True) is equivalent to settimeout(None);\n\
1689 setblocking(False) is equivalent to settimeout(0.0).");
1691 /* s.settimeout(timeout) method. Argument:
1692 None -- no timeout, blocking mode; same as setblocking(True)
1693 0.0 -- non-blocking mode; same as setblocking(False)
1694 > 0 -- timeout mode; operations time out after timeout seconds
1695 < 0 -- illegal; raises an exception
1697 static PyObject *
1698 sock_settimeout(PySocketSockObject *s, PyObject *arg)
1700 double timeout;
1702 if (arg == Py_None)
1703 timeout = -1.0;
1704 else {
1705 timeout = PyFloat_AsDouble(arg);
1706 if (timeout < 0.0) {
1707 if (!PyErr_Occurred())
1708 PyErr_SetString(PyExc_ValueError,
1709 "Timeout value out of range");
1710 return NULL;
1714 s->sock_timeout = timeout;
1715 internal_setblocking(s, timeout < 0.0);
1717 Py_INCREF(Py_None);
1718 return Py_None;
1721 PyDoc_STRVAR(settimeout_doc,
1722 "settimeout(timeout)\n\
1724 Set a timeout on socket operations. 'timeout' can be a float,\n\
1725 giving in seconds, or None. Setting a timeout of None disables\n\
1726 the timeout feature and is equivalent to setblocking(1).\n\
1727 Setting a timeout of zero is the same as setblocking(0).");
1729 /* s.gettimeout() method.
1730 Returns the timeout associated with a socket. */
1731 static PyObject *
1732 sock_gettimeout(PySocketSockObject *s)
1734 if (s->sock_timeout < 0.0) {
1735 Py_INCREF(Py_None);
1736 return Py_None;
1738 else
1739 return PyFloat_FromDouble(s->sock_timeout);
1742 PyDoc_STRVAR(gettimeout_doc,
1743 "gettimeout() -> timeout\n\
1745 Returns the timeout in floating seconds associated with socket \n\
1746 operations. A timeout of None indicates that timeouts on socket \n\
1747 operations are disabled.");
1749 #ifdef RISCOS
1750 /* s.sleeptaskw(1 | 0) method */
1752 static PyObject *
1753 sock_sleeptaskw(PySocketSockObject *s,PyObject *arg)
1755 int block;
1756 block = PyInt_AsLong(arg);
1757 if (block == -1 && PyErr_Occurred())
1758 return NULL;
1759 Py_BEGIN_ALLOW_THREADS
1760 socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
1761 Py_END_ALLOW_THREADS
1763 Py_INCREF(Py_None);
1764 return Py_None;
1766 PyDoc_STRVAR(sleeptaskw_doc,
1767 "sleeptaskw(flag)\n\
1769 Allow sleeps in taskwindows.");
1770 #endif
1773 /* s.setsockopt() method.
1774 With an integer third argument, sets an integer option.
1775 With a string third argument, sets an option from a buffer;
1776 use optional built-in module 'struct' to encode the string. */
1778 static PyObject *
1779 sock_setsockopt(PySocketSockObject *s, PyObject *args)
1781 int level;
1782 int optname;
1783 int res;
1784 char *buf;
1785 int buflen;
1786 int flag;
1788 if (PyArg_ParseTuple(args, "iii:setsockopt",
1789 &level, &optname, &flag)) {
1790 buf = (char *) &flag;
1791 buflen = sizeof flag;
1793 else {
1794 PyErr_Clear();
1795 if (!PyArg_ParseTuple(args, "iis#:setsockopt",
1796 &level, &optname, &buf, &buflen))
1797 return NULL;
1799 res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen);
1800 if (res < 0)
1801 return s->errorhandler();
1802 Py_INCREF(Py_None);
1803 return Py_None;
1806 PyDoc_STRVAR(setsockopt_doc,
1807 "setsockopt(level, option, value)\n\
1809 Set a socket option. See the Unix manual for level and option.\n\
1810 The value argument can either be an integer or a string.");
1813 /* s.getsockopt() method.
1814 With two arguments, retrieves an integer option.
1815 With a third integer argument, retrieves a string buffer of that size;
1816 use optional built-in module 'struct' to decode the string. */
1818 static PyObject *
1819 sock_getsockopt(PySocketSockObject *s, PyObject *args)
1821 int level;
1822 int optname;
1823 int res;
1824 PyObject *buf;
1825 socklen_t buflen = 0;
1827 #ifdef __BEOS__
1828 /* We have incomplete socket support. */
1829 PyErr_SetString(socket_error, "getsockopt not supported");
1830 return NULL;
1831 #else
1833 if (!PyArg_ParseTuple(args, "ii|i:getsockopt",
1834 &level, &optname, &buflen))
1835 return NULL;
1837 if (buflen == 0) {
1838 int flag = 0;
1839 socklen_t flagsize = sizeof flag;
1840 res = getsockopt(s->sock_fd, level, optname,
1841 (void *)&flag, &flagsize);
1842 if (res < 0)
1843 return s->errorhandler();
1844 return PyInt_FromLong(flag);
1846 #ifdef __VMS
1847 /* socklen_t is unsigned so no negative test is needed,
1848 test buflen == 0 is previously done */
1849 if (buflen > 1024) {
1850 #else
1851 if (buflen <= 0 || buflen > 1024) {
1852 #endif
1853 PyErr_SetString(socket_error,
1854 "getsockopt buflen out of range");
1855 return NULL;
1857 buf = PyString_FromStringAndSize((char *)NULL, buflen);
1858 if (buf == NULL)
1859 return NULL;
1860 res = getsockopt(s->sock_fd, level, optname,
1861 (void *)PyString_AS_STRING(buf), &buflen);
1862 if (res < 0) {
1863 Py_DECREF(buf);
1864 return s->errorhandler();
1866 _PyString_Resize(&buf, buflen);
1867 return buf;
1868 #endif /* __BEOS__ */
1871 PyDoc_STRVAR(getsockopt_doc,
1872 "getsockopt(level, option[, buffersize]) -> value\n\
1874 Get a socket option. See the Unix manual for level and option.\n\
1875 If a nonzero buffersize argument is given, the return value is a\n\
1876 string of that length; otherwise it is an integer.");
1879 /* s.bind(sockaddr) method */
1881 static PyObject *
1882 sock_bind(PySocketSockObject *s, PyObject *addro)
1884 sock_addr_t addrbuf;
1885 int addrlen;
1886 int res;
1888 if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
1889 return NULL;
1890 Py_BEGIN_ALLOW_THREADS
1891 res = bind(s->sock_fd, SAS2SA(&addrbuf), addrlen);
1892 Py_END_ALLOW_THREADS
1893 if (res < 0)
1894 return s->errorhandler();
1895 Py_INCREF(Py_None);
1896 return Py_None;
1899 PyDoc_STRVAR(bind_doc,
1900 "bind(address)\n\
1902 Bind the socket to a local address. For IP sockets, the address is a\n\
1903 pair (host, port); the host must refer to the local host. For raw packet\n\
1904 sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");
1907 /* s.close() method.
1908 Set the file descriptor to -1 so operations tried subsequently
1909 will surely fail. */
1911 static PyObject *
1912 sock_close(PySocketSockObject *s)
1914 SOCKET_T fd;
1916 if ((fd = s->sock_fd) != -1) {
1917 s->sock_fd = -1;
1918 Py_BEGIN_ALLOW_THREADS
1919 (void) SOCKETCLOSE(fd);
1920 Py_END_ALLOW_THREADS
1922 Py_INCREF(Py_None);
1923 return Py_None;
1926 PyDoc_STRVAR(close_doc,
1927 "close()\n\
1929 Close the socket. It cannot be used after this call.");
1931 static int
1932 internal_connect(PySocketSockObject *s, struct sockaddr *addr, int addrlen,
1933 int *timeoutp)
1935 int res, timeout;
1937 timeout = 0;
1938 res = connect(s->sock_fd, addr, addrlen);
1940 #ifdef MS_WINDOWS
1942 if (s->sock_timeout > 0.0) {
1943 if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK &&
1944 IS_SELECTABLE(s)) {
1945 /* This is a mess. Best solution: trust select */
1946 fd_set fds;
1947 fd_set fds_exc;
1948 struct timeval tv;
1949 tv.tv_sec = (int)s->sock_timeout;
1950 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1951 FD_ZERO(&fds);
1952 FD_SET(s->sock_fd, &fds);
1953 FD_ZERO(&fds_exc);
1954 FD_SET(s->sock_fd, &fds_exc);
1955 res = select(s->sock_fd+1, NULL, &fds, &fds_exc, &tv);
1956 if (res == 0) {
1957 res = WSAEWOULDBLOCK;
1958 timeout = 1;
1959 } else if (res > 0) {
1960 if (FD_ISSET(s->sock_fd, &fds))
1961 /* The socket is in the writeable set - this
1962 means connected */
1963 res = 0;
1964 else {
1965 /* As per MS docs, we need to call getsockopt()
1966 to get the underlying error */
1967 int res_size = sizeof res;
1968 /* It must be in the exception set */
1969 assert(FD_ISSET(s->sock_fd, &fds_exc));
1970 if (0 == getsockopt(s->sock_fd, SOL_SOCKET, SO_ERROR,
1971 (char *)&res, &res_size))
1972 /* getsockopt also clears WSAGetLastError,
1973 so reset it back. */
1974 WSASetLastError(res);
1975 else
1976 res = WSAGetLastError();
1979 /* else if (res < 0) an error occurred */
1983 if (res < 0)
1984 res = WSAGetLastError();
1986 #else
1988 if (s->sock_timeout > 0.0) {
1989 if (res < 0 && errno == EINPROGRESS && IS_SELECTABLE(s)) {
1990 timeout = internal_select(s, 1);
1991 if (timeout == 0) {
1992 /* Bug #1019808: in case of an EINPROGRESS,
1993 use getsockopt(SO_ERROR) to get the real
1994 error. */
1995 socklen_t res_size = sizeof res;
1996 (void)getsockopt(s->sock_fd, SOL_SOCKET,
1997 SO_ERROR, &res, &res_size);
1998 if (res == EISCONN)
1999 res = 0;
2000 errno = res;
2002 else if (timeout == -1) {
2003 res = errno; /* had error */
2005 else
2006 res = EWOULDBLOCK; /* timed out */
2010 if (res < 0)
2011 res = errno;
2013 #endif
2014 *timeoutp = timeout;
2016 return res;
2019 /* s.connect(sockaddr) method */
2021 static PyObject *
2022 sock_connect(PySocketSockObject *s, PyObject *addro)
2024 sock_addr_t addrbuf;
2025 int addrlen;
2026 int res;
2027 int timeout;
2029 if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
2030 return NULL;
2032 Py_BEGIN_ALLOW_THREADS
2033 res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
2034 Py_END_ALLOW_THREADS
2036 if (timeout == 1) {
2037 PyErr_SetString(socket_timeout, "timed out");
2038 return NULL;
2040 if (res != 0)
2041 return s->errorhandler();
2042 Py_INCREF(Py_None);
2043 return Py_None;
2046 PyDoc_STRVAR(connect_doc,
2047 "connect(address)\n\
2049 Connect the socket to a remote address. For IP sockets, the address\n\
2050 is a pair (host, port).");
2053 /* s.connect_ex(sockaddr) method */
2055 static PyObject *
2056 sock_connect_ex(PySocketSockObject *s, PyObject *addro)
2058 sock_addr_t addrbuf;
2059 int addrlen;
2060 int res;
2061 int timeout;
2063 if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
2064 return NULL;
2066 Py_BEGIN_ALLOW_THREADS
2067 res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
2068 Py_END_ALLOW_THREADS
2070 /* Signals are not errors (though they may raise exceptions). Adapted
2071 from PyErr_SetFromErrnoWithFilenameObject(). */
2072 #ifdef EINTR
2073 if (res == EINTR && PyErr_CheckSignals())
2074 return NULL;
2075 #endif
2077 return PyInt_FromLong((long) res);
2080 PyDoc_STRVAR(connect_ex_doc,
2081 "connect_ex(address) -> errno\n\
2083 This is like connect(address), but returns an error code (the errno value)\n\
2084 instead of raising an exception when an error occurs.");
2087 /* s.fileno() method */
2089 static PyObject *
2090 sock_fileno(PySocketSockObject *s)
2092 #if SIZEOF_SOCKET_T <= SIZEOF_LONG
2093 return PyInt_FromLong((long) s->sock_fd);
2094 #else
2095 return PyLong_FromLongLong((PY_LONG_LONG)s->sock_fd);
2096 #endif
2099 PyDoc_STRVAR(fileno_doc,
2100 "fileno() -> integer\n\
2102 Return the integer file descriptor of the socket.");
2105 #ifndef NO_DUP
2106 /* s.dup() method */
2108 static PyObject *
2109 sock_dup(PySocketSockObject *s)
2111 SOCKET_T newfd;
2112 PyObject *sock;
2114 newfd = dup(s->sock_fd);
2115 if (newfd < 0)
2116 return s->errorhandler();
2117 sock = (PyObject *) new_sockobject(newfd,
2118 s->sock_family,
2119 s->sock_type,
2120 s->sock_proto);
2121 if (sock == NULL)
2122 SOCKETCLOSE(newfd);
2123 return sock;
2126 PyDoc_STRVAR(dup_doc,
2127 "dup() -> socket object\n\
2129 Return a new socket object connected to the same system resource.");
2131 #endif
2134 /* s.getsockname() method */
2136 static PyObject *
2137 sock_getsockname(PySocketSockObject *s)
2139 sock_addr_t addrbuf;
2140 int res;
2141 socklen_t addrlen;
2143 if (!getsockaddrlen(s, &addrlen))
2144 return NULL;
2145 memset(&addrbuf, 0, addrlen);
2146 Py_BEGIN_ALLOW_THREADS
2147 res = getsockname(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
2148 Py_END_ALLOW_THREADS
2149 if (res < 0)
2150 return s->errorhandler();
2151 return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
2152 s->sock_proto);
2155 PyDoc_STRVAR(getsockname_doc,
2156 "getsockname() -> address info\n\
2158 Return the address of the local endpoint. For IP sockets, the address\n\
2159 info is a pair (hostaddr, port).");
2162 #ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
2163 /* s.getpeername() method */
2165 static PyObject *
2166 sock_getpeername(PySocketSockObject *s)
2168 sock_addr_t addrbuf;
2169 int res;
2170 socklen_t addrlen;
2172 if (!getsockaddrlen(s, &addrlen))
2173 return NULL;
2174 memset(&addrbuf, 0, addrlen);
2175 Py_BEGIN_ALLOW_THREADS
2176 res = getpeername(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
2177 Py_END_ALLOW_THREADS
2178 if (res < 0)
2179 return s->errorhandler();
2180 return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
2181 s->sock_proto);
2184 PyDoc_STRVAR(getpeername_doc,
2185 "getpeername() -> address info\n\
2187 Return the address of the remote endpoint. For IP sockets, the address\n\
2188 info is a pair (hostaddr, port).");
2190 #endif /* HAVE_GETPEERNAME */
2193 /* s.listen(n) method */
2195 static PyObject *
2196 sock_listen(PySocketSockObject *s, PyObject *arg)
2198 int backlog;
2199 int res;
2201 backlog = PyInt_AsLong(arg);
2202 if (backlog == -1 && PyErr_Occurred())
2203 return NULL;
2204 Py_BEGIN_ALLOW_THREADS
2205 if (backlog < 1)
2206 backlog = 1;
2207 res = listen(s->sock_fd, backlog);
2208 Py_END_ALLOW_THREADS
2209 if (res < 0)
2210 return s->errorhandler();
2211 Py_INCREF(Py_None);
2212 return Py_None;
2215 PyDoc_STRVAR(listen_doc,
2216 "listen(backlog)\n\
2218 Enable a server to accept connections. The backlog argument must be at\n\
2219 least 1; it specifies the number of unaccepted connection that the system\n\
2220 will allow before refusing new connections.");
2223 #ifndef NO_DUP
2224 /* s.makefile(mode) method.
2225 Create a new open file object referring to a dupped version of
2226 the socket's file descriptor. (The dup() call is necessary so
2227 that the open file and socket objects may be closed independent
2228 of each other.)
2229 The mode argument specifies 'r' or 'w' passed to fdopen(). */
2231 static PyObject *
2232 sock_makefile(PySocketSockObject *s, PyObject *args)
2234 extern int fclose(FILE *);
2235 char *mode = "r";
2236 int bufsize = -1;
2237 #ifdef MS_WIN32
2238 Py_intptr_t fd;
2239 #else
2240 int fd;
2241 #endif
2242 FILE *fp;
2243 PyObject *f;
2244 #ifdef __VMS
2245 char *mode_r = "r";
2246 char *mode_w = "w";
2247 #endif
2249 if (!PyArg_ParseTuple(args, "|si:makefile", &mode, &bufsize))
2250 return NULL;
2251 #ifdef __VMS
2252 if (strcmp(mode,"rb") == 0) {
2253 mode = mode_r;
2255 else {
2256 if (strcmp(mode,"wb") == 0) {
2257 mode = mode_w;
2260 #endif
2261 #ifdef MS_WIN32
2262 if (((fd = _open_osfhandle(s->sock_fd, _O_BINARY)) < 0) ||
2263 ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL))
2264 #else
2265 if ((fd = dup(s->sock_fd)) < 0 || (fp = fdopen(fd, mode)) == NULL)
2266 #endif
2268 if (fd >= 0)
2269 SOCKETCLOSE(fd);
2270 return s->errorhandler();
2272 f = PyFile_FromFile(fp, "<socket>", mode, fclose);
2273 if (f != NULL)
2274 PyFile_SetBufSize(f, bufsize);
2275 return f;
2278 PyDoc_STRVAR(makefile_doc,
2279 "makefile([mode[, buffersize]]) -> file object\n\
2281 Return a regular file object corresponding to the socket.\n\
2282 The mode and buffersize arguments are as for the built-in open() function.");
2284 #endif /* NO_DUP */
2287 * This is the guts of the recv() and recv_into() methods, which reads into a
2288 * char buffer. If you have any inc/dec ref to do to the objects that contain
2289 * the buffer, do it in the caller. This function returns the number of bytes
2290 * succesfully read. If there was an error, it returns -1. Note that it is
2291 * also possible that we return a number of bytes smaller than the request
2292 * bytes.
2294 static ssize_t
2295 sock_recv_guts(PySocketSockObject *s, char* cbuf, int len, int flags)
2297 ssize_t outlen = -1;
2298 int timeout;
2299 #ifdef __VMS
2300 int remaining;
2301 char *read_buf;
2302 #endif
2304 if (!IS_SELECTABLE(s)) {
2305 select_error();
2306 return -1;
2309 #ifndef __VMS
2310 Py_BEGIN_ALLOW_THREADS
2311 timeout = internal_select(s, 0);
2312 if (!timeout)
2313 outlen = recv(s->sock_fd, cbuf, len, flags);
2314 Py_END_ALLOW_THREADS
2316 if (timeout == 1) {
2317 PyErr_SetString(socket_timeout, "timed out");
2318 return -1;
2320 if (outlen < 0) {
2321 /* Note: the call to errorhandler() ALWAYS indirectly returned
2322 NULL, so ignore its return value */
2323 s->errorhandler();
2324 return -1;
2326 #else
2327 read_buf = cbuf;
2328 remaining = len;
2329 while (remaining != 0) {
2330 unsigned int segment;
2331 int nread = -1;
2333 segment = remaining /SEGMENT_SIZE;
2334 if (segment != 0) {
2335 segment = SEGMENT_SIZE;
2337 else {
2338 segment = remaining;
2341 Py_BEGIN_ALLOW_THREADS
2342 timeout = internal_select(s, 0);
2343 if (!timeout)
2344 nread = recv(s->sock_fd, read_buf, segment, flags);
2345 Py_END_ALLOW_THREADS
2347 if (timeout == 1) {
2348 PyErr_SetString(socket_timeout, "timed out");
2349 return -1;
2351 if (nread < 0) {
2352 s->errorhandler();
2353 return -1;
2355 if (nread != remaining) {
2356 read_buf += nread;
2357 break;
2360 remaining -= segment;
2361 read_buf += segment;
2363 outlen = read_buf - cbuf;
2364 #endif /* !__VMS */
2366 return outlen;
2370 /* s.recv(nbytes [,flags]) method */
2372 static PyObject *
2373 sock_recv(PySocketSockObject *s, PyObject *args)
2375 int recvlen, flags = 0;
2376 ssize_t outlen;
2377 PyObject *buf;
2379 if (!PyArg_ParseTuple(args, "i|i:recv", &recvlen, &flags))
2380 return NULL;
2382 if (recvlen < 0) {
2383 PyErr_SetString(PyExc_ValueError,
2384 "negative buffersize in recv");
2385 return NULL;
2388 /* Allocate a new string. */
2389 buf = PyString_FromStringAndSize((char *) 0, recvlen);
2390 if (buf == NULL)
2391 return NULL;
2393 /* Call the guts */
2394 outlen = sock_recv_guts(s, PyString_AS_STRING(buf), recvlen, flags);
2395 if (outlen < 0) {
2396 /* An error occurred, release the string and return an
2397 error. */
2398 Py_DECREF(buf);
2399 return NULL;
2401 if (outlen != recvlen) {
2402 /* We did not read as many bytes as we anticipated, resize the
2403 string if possible and be succesful. */
2404 if (_PyString_Resize(&buf, outlen) < 0)
2405 /* Oopsy, not so succesful after all. */
2406 return NULL;
2409 return buf;
2412 PyDoc_STRVAR(recv_doc,
2413 "recv(buffersize[, flags]) -> data\n\
2415 Receive up to buffersize bytes from the socket. For the optional flags\n\
2416 argument, see the Unix manual. When no data is available, block until\n\
2417 at least one byte is available or until the remote end is closed. When\n\
2418 the remote end is closed and all data is read, return the empty string.");
2421 /* s.recv_into(buffer, [nbytes [,flags]]) method */
2423 static PyObject*
2424 sock_recv_into(PySocketSockObject *s, PyObject *args, PyObject *kwds)
2426 static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
2428 int recvlen = 0, flags = 0;
2429 ssize_t readlen;
2430 char *buf;
2431 int buflen;
2433 /* Get the buffer's memory */
2434 if (!PyArg_ParseTupleAndKeywords(args, kwds, "w#|ii:recv_into", kwlist,
2435 &buf, &buflen, &recvlen, &flags))
2436 return NULL;
2437 assert(buf != 0 && buflen > 0);
2439 if (recvlen < 0) {
2440 PyErr_SetString(PyExc_ValueError,
2441 "negative buffersize in recv_into");
2442 return NULL;
2444 if (recvlen == 0) {
2445 /* If nbytes was not specified, use the buffer's length */
2446 recvlen = buflen;
2449 /* Check if the buffer is large enough */
2450 if (buflen < recvlen) {
2451 PyErr_SetString(PyExc_ValueError,
2452 "buffer too small for requested bytes");
2453 return NULL;
2456 /* Call the guts */
2457 readlen = sock_recv_guts(s, buf, recvlen, flags);
2458 if (readlen < 0) {
2459 /* Return an error. */
2460 return NULL;
2463 /* Return the number of bytes read. Note that we do not do anything
2464 special here in the case that readlen < recvlen. */
2465 return PyInt_FromSsize_t(readlen);
2468 PyDoc_STRVAR(recv_into_doc,
2469 "recv_into(buffer, [nbytes[, flags]]) -> nbytes_read\n\
2471 A version of recv() that stores its data into a buffer rather than creating \n\
2472 a new string. Receive up to buffersize bytes from the socket. If buffersize \n\
2473 is not specified (or 0), receive up to the size available in the given buffer.\n\
2475 See recv() for documentation about the flags.");
2479 * This is the guts of the recvfrom() and recvfrom_into() methods, which reads
2480 * into a char buffer. If you have any inc/def ref to do to the objects that
2481 * contain the buffer, do it in the caller. This function returns the number
2482 * of bytes succesfully read. If there was an error, it returns -1. Note
2483 * that it is also possible that we return a number of bytes smaller than the
2484 * request bytes.
2486 * 'addr' is a return value for the address object. Note that you must decref
2487 * it yourself.
2489 static ssize_t
2490 sock_recvfrom_guts(PySocketSockObject *s, char* cbuf, int len, int flags,
2491 PyObject** addr)
2493 sock_addr_t addrbuf;
2494 int timeout;
2495 ssize_t n = -1;
2496 socklen_t addrlen;
2498 *addr = NULL;
2500 if (!getsockaddrlen(s, &addrlen))
2501 return -1;
2503 if (!IS_SELECTABLE(s)) {
2504 select_error();
2505 return -1;
2508 Py_BEGIN_ALLOW_THREADS
2509 memset(&addrbuf, 0, addrlen);
2510 timeout = internal_select(s, 0);
2511 if (!timeout) {
2512 #ifndef MS_WINDOWS
2513 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
2514 n = recvfrom(s->sock_fd, cbuf, len, flags,
2515 SAS2SA(&addrbuf), &addrlen);
2516 #else
2517 n = recvfrom(s->sock_fd, cbuf, len, flags,
2518 (void *) &addrbuf, &addrlen);
2519 #endif
2520 #else
2521 n = recvfrom(s->sock_fd, cbuf, len, flags,
2522 SAS2SA(&addrbuf), &addrlen);
2523 #endif
2525 Py_END_ALLOW_THREADS
2527 if (timeout == 1) {
2528 PyErr_SetString(socket_timeout, "timed out");
2529 return -1;
2531 if (n < 0) {
2532 s->errorhandler();
2533 return -1;
2536 if (!(*addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
2537 addrlen, s->sock_proto)))
2538 return -1;
2540 return n;
2543 /* s.recvfrom(nbytes [,flags]) method */
2545 static PyObject *
2546 sock_recvfrom(PySocketSockObject *s, PyObject *args)
2548 PyObject *buf = NULL;
2549 PyObject *addr = NULL;
2550 PyObject *ret = NULL;
2551 int recvlen, flags = 0;
2552 ssize_t outlen;
2554 if (!PyArg_ParseTuple(args, "i|i:recvfrom", &recvlen, &flags))
2555 return NULL;
2557 if (recvlen < 0) {
2558 PyErr_SetString(PyExc_ValueError,
2559 "negative buffersize in recvfrom");
2560 return NULL;
2563 buf = PyString_FromStringAndSize((char *) 0, recvlen);
2564 if (buf == NULL)
2565 return NULL;
2567 outlen = sock_recvfrom_guts(s, PyString_AS_STRING(buf),
2568 recvlen, flags, &addr);
2569 if (outlen < 0) {
2570 goto finally;
2573 if (outlen != recvlen) {
2574 /* We did not read as many bytes as we anticipated, resize the
2575 string if possible and be succesful. */
2576 if (_PyString_Resize(&buf, outlen) < 0)
2577 /* Oopsy, not so succesful after all. */
2578 goto finally;
2581 ret = PyTuple_Pack(2, buf, addr);
2583 finally:
2584 Py_XDECREF(buf);
2585 Py_XDECREF(addr);
2586 return ret;
2589 PyDoc_STRVAR(recvfrom_doc,
2590 "recvfrom(buffersize[, flags]) -> (data, address info)\n\
2592 Like recv(buffersize, flags) but also return the sender's address info.");
2595 /* s.recvfrom_into(buffer[, nbytes [,flags]]) method */
2597 static PyObject *
2598 sock_recvfrom_into(PySocketSockObject *s, PyObject *args, PyObject* kwds)
2600 static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
2602 int recvlen = 0, flags = 0;
2603 ssize_t readlen;
2604 char *buf;
2605 int buflen;
2607 PyObject *addr = NULL;
2609 if (!PyArg_ParseTupleAndKeywords(args, kwds, "w#|ii:recvfrom_into",
2610 kwlist, &buf, &buflen,
2611 &recvlen, &flags))
2612 return NULL;
2613 assert(buf != 0 && buflen > 0);
2615 if (recvlen < 0) {
2616 PyErr_SetString(PyExc_ValueError,
2617 "negative buffersize in recvfrom_into");
2618 return NULL;
2620 if (recvlen == 0) {
2621 /* If nbytes was not specified, use the buffer's length */
2622 recvlen = buflen;
2625 readlen = sock_recvfrom_guts(s, buf, recvlen, flags, &addr);
2626 if (readlen < 0) {
2627 /* Return an error */
2628 Py_XDECREF(addr);
2629 return NULL;
2632 /* Return the number of bytes read and the address. Note that we do
2633 not do anything special here in the case that readlen < recvlen. */
2634 return Py_BuildValue("lN", readlen, addr);
2637 PyDoc_STRVAR(recvfrom_into_doc,
2638 "recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)\n\
2640 Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.");
2643 /* s.send(data [,flags]) method */
2645 static PyObject *
2646 sock_send(PySocketSockObject *s, PyObject *args)
2648 char *buf;
2649 int len, n = -1, flags = 0, timeout;
2650 Py_buffer pbuf;
2652 if (!PyArg_ParseTuple(args, "s*|i:send", &pbuf, &flags))
2653 return NULL;
2655 if (!IS_SELECTABLE(s)) {
2656 PyBuffer_Release(&pbuf);
2657 return select_error();
2659 buf = pbuf.buf;
2660 len = pbuf.len;
2662 Py_BEGIN_ALLOW_THREADS
2663 timeout = internal_select(s, 1);
2664 if (!timeout)
2665 #ifdef __VMS
2666 n = sendsegmented(s->sock_fd, buf, len, flags);
2667 #else
2668 n = send(s->sock_fd, buf, len, flags);
2669 #endif
2670 Py_END_ALLOW_THREADS
2672 PyBuffer_Release(&pbuf);
2674 if (timeout == 1) {
2675 PyErr_SetString(socket_timeout, "timed out");
2676 return NULL;
2678 if (n < 0)
2679 return s->errorhandler();
2680 return PyInt_FromLong((long)n);
2683 PyDoc_STRVAR(send_doc,
2684 "send(data[, flags]) -> count\n\
2686 Send a data string to the socket. For the optional flags\n\
2687 argument, see the Unix manual. Return the number of bytes\n\
2688 sent; this may be less than len(data) if the network is busy.");
2691 /* s.sendall(data [,flags]) method */
2693 static PyObject *
2694 sock_sendall(PySocketSockObject *s, PyObject *args)
2696 char *buf;
2697 int len, n = -1, flags = 0, timeout;
2698 Py_buffer pbuf;
2700 if (!PyArg_ParseTuple(args, "s*|i:sendall", &pbuf, &flags))
2701 return NULL;
2702 buf = pbuf.buf;
2703 len = pbuf.len;
2705 if (!IS_SELECTABLE(s)) {
2706 PyBuffer_Release(&pbuf);
2707 return select_error();
2710 Py_BEGIN_ALLOW_THREADS
2711 do {
2712 timeout = internal_select(s, 1);
2713 n = -1;
2714 if (timeout)
2715 break;
2716 #ifdef __VMS
2717 n = sendsegmented(s->sock_fd, buf, len, flags);
2718 #else
2719 n = send(s->sock_fd, buf, len, flags);
2720 #endif
2721 if (n < 0)
2722 break;
2723 buf += n;
2724 len -= n;
2725 } while (len > 0);
2726 Py_END_ALLOW_THREADS
2727 PyBuffer_Release(&pbuf);
2729 if (timeout == 1) {
2730 PyErr_SetString(socket_timeout, "timed out");
2731 return NULL;
2733 if (n < 0)
2734 return s->errorhandler();
2736 Py_INCREF(Py_None);
2737 return Py_None;
2740 PyDoc_STRVAR(sendall_doc,
2741 "sendall(data[, flags])\n\
2743 Send a data string to the socket. For the optional flags\n\
2744 argument, see the Unix manual. This calls send() repeatedly\n\
2745 until all data is sent. If an error occurs, it's impossible\n\
2746 to tell how much data has been sent.");
2749 /* s.sendto(data, [flags,] sockaddr) method */
2751 static PyObject *
2752 sock_sendto(PySocketSockObject *s, PyObject *args)
2754 Py_buffer pbuf;
2755 PyObject *addro;
2756 char *buf;
2757 Py_ssize_t len;
2758 sock_addr_t addrbuf;
2759 int addrlen, n = -1, flags, timeout;
2761 flags = 0;
2762 if (!PyArg_ParseTuple(args, "s*O:sendto", &pbuf, &addro)) {
2763 PyErr_Clear();
2764 if (!PyArg_ParseTuple(args, "s*iO:sendto",
2765 &pbuf, &flags, &addro))
2766 return NULL;
2768 buf = pbuf.buf;
2769 len = pbuf.len;
2771 if (!IS_SELECTABLE(s)) {
2772 PyBuffer_Release(&pbuf);
2773 return select_error();
2776 if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) {
2777 PyBuffer_Release(&pbuf);
2778 return NULL;
2781 Py_BEGIN_ALLOW_THREADS
2782 timeout = internal_select(s, 1);
2783 if (!timeout)
2784 n = sendto(s->sock_fd, buf, len, flags, SAS2SA(&addrbuf), addrlen);
2785 Py_END_ALLOW_THREADS
2787 PyBuffer_Release(&pbuf);
2788 if (timeout == 1) {
2789 PyErr_SetString(socket_timeout, "timed out");
2790 return NULL;
2792 if (n < 0)
2793 return s->errorhandler();
2794 return PyInt_FromLong((long)n);
2797 PyDoc_STRVAR(sendto_doc,
2798 "sendto(data[, flags], address) -> count\n\
2800 Like send(data, flags) but allows specifying the destination address.\n\
2801 For IP sockets, the address is a pair (hostaddr, port).");
2804 /* s.shutdown(how) method */
2806 static PyObject *
2807 sock_shutdown(PySocketSockObject *s, PyObject *arg)
2809 int how;
2810 int res;
2812 how = PyInt_AsLong(arg);
2813 if (how == -1 && PyErr_Occurred())
2814 return NULL;
2815 Py_BEGIN_ALLOW_THREADS
2816 res = shutdown(s->sock_fd, how);
2817 Py_END_ALLOW_THREADS
2818 if (res < 0)
2819 return s->errorhandler();
2820 Py_INCREF(Py_None);
2821 return Py_None;
2824 PyDoc_STRVAR(shutdown_doc,
2825 "shutdown(flag)\n\
2827 Shut down the reading side of the socket (flag == SHUT_RD), the writing side\n\
2828 of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).");
2830 #if defined(MS_WINDOWS) && defined(SIO_RCVALL)
2831 static PyObject*
2832 sock_ioctl(PySocketSockObject *s, PyObject *arg)
2834 unsigned long cmd = SIO_RCVALL;
2835 unsigned int option = RCVALL_ON;
2836 DWORD recv;
2838 if (!PyArg_ParseTuple(arg, "kI:ioctl", &cmd, &option))
2839 return NULL;
2841 if (WSAIoctl(s->sock_fd, cmd, &option, sizeof(option),
2842 NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
2843 return set_error();
2845 return PyLong_FromUnsignedLong(recv);
2847 PyDoc_STRVAR(sock_ioctl_doc,
2848 "ioctl(cmd, option) -> long\n\
2850 Control the socket with WSAIoctl syscall. Currently only socket.SIO_RCVALL\n\
2851 is supported as control. Options must be one of the socket.RCVALL_*\n\
2852 constants.");
2854 #endif
2856 /* List of methods for socket objects */
2858 static PyMethodDef sock_methods[] = {
2859 {"accept", (PyCFunction)sock_accept, METH_NOARGS,
2860 accept_doc},
2861 {"bind", (PyCFunction)sock_bind, METH_O,
2862 bind_doc},
2863 {"close", (PyCFunction)sock_close, METH_NOARGS,
2864 close_doc},
2865 {"connect", (PyCFunction)sock_connect, METH_O,
2866 connect_doc},
2867 {"connect_ex", (PyCFunction)sock_connect_ex, METH_O,
2868 connect_ex_doc},
2869 #ifndef NO_DUP
2870 {"dup", (PyCFunction)sock_dup, METH_NOARGS,
2871 dup_doc},
2872 #endif
2873 {"fileno", (PyCFunction)sock_fileno, METH_NOARGS,
2874 fileno_doc},
2875 #ifdef HAVE_GETPEERNAME
2876 {"getpeername", (PyCFunction)sock_getpeername,
2877 METH_NOARGS, getpeername_doc},
2878 #endif
2879 {"getsockname", (PyCFunction)sock_getsockname,
2880 METH_NOARGS, getsockname_doc},
2881 {"getsockopt", (PyCFunction)sock_getsockopt, METH_VARARGS,
2882 getsockopt_doc},
2883 #if defined(MS_WINDOWS) && defined(SIO_RCVALL)
2884 {"ioctl", (PyCFunction)sock_ioctl, METH_VARARGS,
2885 sock_ioctl_doc},
2886 #endif
2887 {"listen", (PyCFunction)sock_listen, METH_O,
2888 listen_doc},
2889 #ifndef NO_DUP
2890 {"makefile", (PyCFunction)sock_makefile, METH_VARARGS,
2891 makefile_doc},
2892 #endif
2893 {"recv", (PyCFunction)sock_recv, METH_VARARGS,
2894 recv_doc},
2895 {"recv_into", (PyCFunction)sock_recv_into, METH_VARARGS | METH_KEYWORDS,
2896 recv_into_doc},
2897 {"recvfrom", (PyCFunction)sock_recvfrom, METH_VARARGS,
2898 recvfrom_doc},
2899 {"recvfrom_into", (PyCFunction)sock_recvfrom_into, METH_VARARGS | METH_KEYWORDS,
2900 recvfrom_into_doc},
2901 {"send", (PyCFunction)sock_send, METH_VARARGS,
2902 send_doc},
2903 {"sendall", (PyCFunction)sock_sendall, METH_VARARGS,
2904 sendall_doc},
2905 {"sendto", (PyCFunction)sock_sendto, METH_VARARGS,
2906 sendto_doc},
2907 {"setblocking", (PyCFunction)sock_setblocking, METH_O,
2908 setblocking_doc},
2909 {"settimeout", (PyCFunction)sock_settimeout, METH_O,
2910 settimeout_doc},
2911 {"gettimeout", (PyCFunction)sock_gettimeout, METH_NOARGS,
2912 gettimeout_doc},
2913 {"setsockopt", (PyCFunction)sock_setsockopt, METH_VARARGS,
2914 setsockopt_doc},
2915 {"shutdown", (PyCFunction)sock_shutdown, METH_O,
2916 shutdown_doc},
2917 #ifdef RISCOS
2918 {"sleeptaskw", (PyCFunction)sock_sleeptaskw, METH_O,
2919 sleeptaskw_doc},
2920 #endif
2921 {NULL, NULL} /* sentinel */
2924 /* SockObject members */
2925 static PyMemberDef sock_memberlist[] = {
2926 {"family", T_INT, offsetof(PySocketSockObject, sock_family), READONLY, "the socket family"},
2927 {"type", T_INT, offsetof(PySocketSockObject, sock_type), READONLY, "the socket type"},
2928 {"proto", T_INT, offsetof(PySocketSockObject, sock_proto), READONLY, "the socket protocol"},
2929 {"timeout", T_DOUBLE, offsetof(PySocketSockObject, sock_timeout), READONLY, "the socket timeout"},
2930 {0},
2933 /* Deallocate a socket object in response to the last Py_DECREF().
2934 First close the file description. */
2936 static void
2937 sock_dealloc(PySocketSockObject *s)
2939 if (s->sock_fd != -1)
2940 (void) SOCKETCLOSE(s->sock_fd);
2941 Py_TYPE(s)->tp_free((PyObject *)s);
2945 static PyObject *
2946 sock_repr(PySocketSockObject *s)
2948 char buf[512];
2949 #if SIZEOF_SOCKET_T > SIZEOF_LONG
2950 if (s->sock_fd > LONG_MAX) {
2951 /* this can occur on Win64, and actually there is a special
2952 ugly printf formatter for decimal pointer length integer
2953 printing, only bother if necessary*/
2954 PyErr_SetString(PyExc_OverflowError,
2955 "no printf formatter to display "
2956 "the socket descriptor in decimal");
2957 return NULL;
2959 #endif
2960 PyOS_snprintf(
2961 buf, sizeof(buf),
2962 "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
2963 (long)s->sock_fd, s->sock_family,
2964 s->sock_type,
2965 s->sock_proto);
2966 return PyString_FromString(buf);
2970 /* Create a new, uninitialized socket object. */
2972 static PyObject *
2973 sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2975 PyObject *new;
2977 new = type->tp_alloc(type, 0);
2978 if (new != NULL) {
2979 ((PySocketSockObject *)new)->sock_fd = -1;
2980 ((PySocketSockObject *)new)->sock_timeout = -1.0;
2981 ((PySocketSockObject *)new)->errorhandler = &set_error;
2983 return new;
2987 /* Initialize a new socket object. */
2989 /*ARGSUSED*/
2990 static int
2991 sock_initobj(PyObject *self, PyObject *args, PyObject *kwds)
2993 PySocketSockObject *s = (PySocketSockObject *)self;
2994 SOCKET_T fd;
2995 int family = AF_INET, type = SOCK_STREAM, proto = 0;
2996 static char *keywords[] = {"family", "type", "proto", 0};
2998 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2999 "|iii:socket", keywords,
3000 &family, &type, &proto))
3001 return -1;
3003 Py_BEGIN_ALLOW_THREADS
3004 fd = socket(family, type, proto);
3005 Py_END_ALLOW_THREADS
3007 #ifdef MS_WINDOWS
3008 if (fd == INVALID_SOCKET)
3009 #else
3010 if (fd < 0)
3011 #endif
3013 set_error();
3014 return -1;
3016 init_sockobject(s, fd, family, type, proto);
3018 return 0;
3023 /* Type object for socket objects. */
3025 static PyTypeObject sock_type = {
3026 PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */
3027 "_socket.socket", /* tp_name */
3028 sizeof(PySocketSockObject), /* tp_basicsize */
3029 0, /* tp_itemsize */
3030 (destructor)sock_dealloc, /* tp_dealloc */
3031 0, /* tp_print */
3032 0, /* tp_getattr */
3033 0, /* tp_setattr */
3034 0, /* tp_compare */
3035 (reprfunc)sock_repr, /* tp_repr */
3036 0, /* tp_as_number */
3037 0, /* tp_as_sequence */
3038 0, /* tp_as_mapping */
3039 0, /* tp_hash */
3040 0, /* tp_call */
3041 0, /* tp_str */
3042 PyObject_GenericGetAttr, /* tp_getattro */
3043 0, /* tp_setattro */
3044 0, /* tp_as_buffer */
3045 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3046 sock_doc, /* tp_doc */
3047 0, /* tp_traverse */
3048 0, /* tp_clear */
3049 0, /* tp_richcompare */
3050 0, /* tp_weaklistoffset */
3051 0, /* tp_iter */
3052 0, /* tp_iternext */
3053 sock_methods, /* tp_methods */
3054 sock_memberlist, /* tp_members */
3055 0, /* tp_getset */
3056 0, /* tp_base */
3057 0, /* tp_dict */
3058 0, /* tp_descr_get */
3059 0, /* tp_descr_set */
3060 0, /* tp_dictoffset */
3061 sock_initobj, /* tp_init */
3062 PyType_GenericAlloc, /* tp_alloc */
3063 sock_new, /* tp_new */
3064 PyObject_Del, /* tp_free */
3068 /* Python interface to gethostname(). */
3070 /*ARGSUSED*/
3071 static PyObject *
3072 socket_gethostname(PyObject *self, PyObject *unused)
3074 char buf[1024];
3075 int res;
3076 Py_BEGIN_ALLOW_THREADS
3077 res = gethostname(buf, (int) sizeof buf - 1);
3078 Py_END_ALLOW_THREADS
3079 if (res < 0)
3080 return set_error();
3081 buf[sizeof buf - 1] = '\0';
3082 return PyString_FromString(buf);
3085 PyDoc_STRVAR(gethostname_doc,
3086 "gethostname() -> string\n\
3088 Return the current host name.");
3091 /* Python interface to gethostbyname(name). */
3093 /*ARGSUSED*/
3094 static PyObject *
3095 socket_gethostbyname(PyObject *self, PyObject *args)
3097 char *name;
3098 sock_addr_t addrbuf;
3100 if (!PyArg_ParseTuple(args, "s:gethostbyname", &name))
3101 return NULL;
3102 if (setipaddr(name, SAS2SA(&addrbuf), sizeof(addrbuf), AF_INET) < 0)
3103 return NULL;
3104 return makeipaddr(SAS2SA(&addrbuf), sizeof(struct sockaddr_in));
3107 PyDoc_STRVAR(gethostbyname_doc,
3108 "gethostbyname(host) -> address\n\
3110 Return the IP address (a string of the form '255.255.255.255') for a host.");
3113 /* Convenience function common to gethostbyname_ex and gethostbyaddr */
3115 static PyObject *
3116 gethost_common(struct hostent *h, struct sockaddr *addr, int alen, int af)
3118 char **pch;
3119 PyObject *rtn_tuple = (PyObject *)NULL;
3120 PyObject *name_list = (PyObject *)NULL;
3121 PyObject *addr_list = (PyObject *)NULL;
3122 PyObject *tmp;
3124 if (h == NULL) {
3125 /* Let's get real error message to return */
3126 #ifndef RISCOS
3127 set_herror(h_errno);
3128 #else
3129 PyErr_SetString(socket_error, "host not found");
3130 #endif
3131 return NULL;
3134 if (h->h_addrtype != af) {
3135 /* Let's get real error message to return */
3136 PyErr_SetString(socket_error,
3137 (char *)strerror(EAFNOSUPPORT));
3139 return NULL;
3142 switch (af) {
3144 case AF_INET:
3145 if (alen < sizeof(struct sockaddr_in))
3146 return NULL;
3147 break;
3149 #ifdef ENABLE_IPV6
3150 case AF_INET6:
3151 if (alen < sizeof(struct sockaddr_in6))
3152 return NULL;
3153 break;
3154 #endif
3158 if ((name_list = PyList_New(0)) == NULL)
3159 goto err;
3161 if ((addr_list = PyList_New(0)) == NULL)
3162 goto err;
3164 /* SF #1511317: h_aliases can be NULL */
3165 if (h->h_aliases) {
3166 for (pch = h->h_aliases; *pch != NULL; pch++) {
3167 int status;
3168 tmp = PyString_FromString(*pch);
3169 if (tmp == NULL)
3170 goto err;
3172 status = PyList_Append(name_list, tmp);
3173 Py_DECREF(tmp);
3175 if (status)
3176 goto err;
3180 for (pch = h->h_addr_list; *pch != NULL; pch++) {
3181 int status;
3183 switch (af) {
3185 case AF_INET:
3187 struct sockaddr_in sin;
3188 memset(&sin, 0, sizeof(sin));
3189 sin.sin_family = af;
3190 #ifdef HAVE_SOCKADDR_SA_LEN
3191 sin.sin_len = sizeof(sin);
3192 #endif
3193 memcpy(&sin.sin_addr, *pch, sizeof(sin.sin_addr));
3194 tmp = makeipaddr((struct sockaddr *)&sin, sizeof(sin));
3196 if (pch == h->h_addr_list && alen >= sizeof(sin))
3197 memcpy((char *) addr, &sin, sizeof(sin));
3198 break;
3201 #ifdef ENABLE_IPV6
3202 case AF_INET6:
3204 struct sockaddr_in6 sin6;
3205 memset(&sin6, 0, sizeof(sin6));
3206 sin6.sin6_family = af;
3207 #ifdef HAVE_SOCKADDR_SA_LEN
3208 sin6.sin6_len = sizeof(sin6);
3209 #endif
3210 memcpy(&sin6.sin6_addr, *pch, sizeof(sin6.sin6_addr));
3211 tmp = makeipaddr((struct sockaddr *)&sin6,
3212 sizeof(sin6));
3214 if (pch == h->h_addr_list && alen >= sizeof(sin6))
3215 memcpy((char *) addr, &sin6, sizeof(sin6));
3216 break;
3218 #endif
3220 default: /* can't happen */
3221 PyErr_SetString(socket_error,
3222 "unsupported address family");
3223 return NULL;
3226 if (tmp == NULL)
3227 goto err;
3229 status = PyList_Append(addr_list, tmp);
3230 Py_DECREF(tmp);
3232 if (status)
3233 goto err;
3236 rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list);
3238 err:
3239 Py_XDECREF(name_list);
3240 Py_XDECREF(addr_list);
3241 return rtn_tuple;
3245 /* Python interface to gethostbyname_ex(name). */
3247 /*ARGSUSED*/
3248 static PyObject *
3249 socket_gethostbyname_ex(PyObject *self, PyObject *args)
3251 char *name;
3252 struct hostent *h;
3253 #ifdef ENABLE_IPV6
3254 struct sockaddr_storage addr;
3255 #else
3256 struct sockaddr_in addr;
3257 #endif
3258 struct sockaddr *sa;
3259 PyObject *ret;
3260 #ifdef HAVE_GETHOSTBYNAME_R
3261 struct hostent hp_allocated;
3262 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
3263 struct hostent_data data;
3264 #else
3265 char buf[16384];
3266 int buf_len = (sizeof buf) - 1;
3267 int errnop;
3268 #endif
3269 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3270 int result;
3271 #endif
3272 #endif /* HAVE_GETHOSTBYNAME_R */
3274 if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name))
3275 return NULL;
3276 if (setipaddr(name, (struct sockaddr *)&addr, sizeof(addr), AF_INET) < 0)
3277 return NULL;
3278 Py_BEGIN_ALLOW_THREADS
3279 #ifdef HAVE_GETHOSTBYNAME_R
3280 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3281 result = gethostbyname_r(name, &hp_allocated, buf, buf_len,
3282 &h, &errnop);
3283 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
3284 h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
3285 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
3286 memset((void *) &data, '\0', sizeof(data));
3287 result = gethostbyname_r(name, &hp_allocated, &data);
3288 h = (result != 0) ? NULL : &hp_allocated;
3289 #endif
3290 #else /* not HAVE_GETHOSTBYNAME_R */
3291 #ifdef USE_GETHOSTBYNAME_LOCK
3292 PyThread_acquire_lock(netdb_lock, 1);
3293 #endif
3294 h = gethostbyname(name);
3295 #endif /* HAVE_GETHOSTBYNAME_R */
3296 Py_END_ALLOW_THREADS
3297 /* Some C libraries would require addr.__ss_family instead of
3298 addr.ss_family.
3299 Therefore, we cast the sockaddr_storage into sockaddr to
3300 access sa_family. */
3301 sa = (struct sockaddr*)&addr;
3302 ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr),
3303 sa->sa_family);
3304 #ifdef USE_GETHOSTBYNAME_LOCK
3305 PyThread_release_lock(netdb_lock);
3306 #endif
3307 return ret;
3310 PyDoc_STRVAR(ghbn_ex_doc,
3311 "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
3313 Return the true host name, a list of aliases, and a list of IP addresses,\n\
3314 for a host. The host argument is a string giving a host name or IP number.");
3317 /* Python interface to gethostbyaddr(IP). */
3319 /*ARGSUSED*/
3320 static PyObject *
3321 socket_gethostbyaddr(PyObject *self, PyObject *args)
3323 #ifdef ENABLE_IPV6
3324 struct sockaddr_storage addr;
3325 #else
3326 struct sockaddr_in addr;
3327 #endif
3328 struct sockaddr *sa = (struct sockaddr *)&addr;
3329 char *ip_num;
3330 struct hostent *h;
3331 PyObject *ret;
3332 #ifdef HAVE_GETHOSTBYNAME_R
3333 struct hostent hp_allocated;
3334 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
3335 struct hostent_data data;
3336 #else
3337 char buf[16384];
3338 int buf_len = (sizeof buf) - 1;
3339 int errnop;
3340 #endif
3341 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3342 int result;
3343 #endif
3344 #endif /* HAVE_GETHOSTBYNAME_R */
3345 char *ap;
3346 int al;
3347 int af;
3349 if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num))
3350 return NULL;
3351 af = AF_UNSPEC;
3352 if (setipaddr(ip_num, sa, sizeof(addr), af) < 0)
3353 return NULL;
3354 af = sa->sa_family;
3355 ap = NULL;
3356 al = 0;
3357 switch (af) {
3358 case AF_INET:
3359 ap = (char *)&((struct sockaddr_in *)sa)->sin_addr;
3360 al = sizeof(((struct sockaddr_in *)sa)->sin_addr);
3361 break;
3362 #ifdef ENABLE_IPV6
3363 case AF_INET6:
3364 ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr;
3365 al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr);
3366 break;
3367 #endif
3368 default:
3369 PyErr_SetString(socket_error, "unsupported address family");
3370 return NULL;
3372 Py_BEGIN_ALLOW_THREADS
3373 #ifdef HAVE_GETHOSTBYNAME_R
3374 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3375 result = gethostbyaddr_r(ap, al, af,
3376 &hp_allocated, buf, buf_len,
3377 &h, &errnop);
3378 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
3379 h = gethostbyaddr_r(ap, al, af,
3380 &hp_allocated, buf, buf_len, &errnop);
3381 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
3382 memset((void *) &data, '\0', sizeof(data));
3383 result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data);
3384 h = (result != 0) ? NULL : &hp_allocated;
3385 #endif
3386 #else /* not HAVE_GETHOSTBYNAME_R */
3387 #ifdef USE_GETHOSTBYNAME_LOCK
3388 PyThread_acquire_lock(netdb_lock, 1);
3389 #endif
3390 h = gethostbyaddr(ap, al, af);
3391 #endif /* HAVE_GETHOSTBYNAME_R */
3392 Py_END_ALLOW_THREADS
3393 ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), af);
3394 #ifdef USE_GETHOSTBYNAME_LOCK
3395 PyThread_release_lock(netdb_lock);
3396 #endif
3397 return ret;
3400 PyDoc_STRVAR(gethostbyaddr_doc,
3401 "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
3403 Return the true host name, a list of aliases, and a list of IP addresses,\n\
3404 for a host. The host argument is a string giving a host name or IP number.");
3407 /* Python interface to getservbyname(name).
3408 This only returns the port number, since the other info is already
3409 known or not useful (like the list of aliases). */
3411 /*ARGSUSED*/
3412 static PyObject *
3413 socket_getservbyname(PyObject *self, PyObject *args)
3415 char *name, *proto=NULL;
3416 struct servent *sp;
3417 if (!PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto))
3418 return NULL;
3419 Py_BEGIN_ALLOW_THREADS
3420 sp = getservbyname(name, proto);
3421 Py_END_ALLOW_THREADS
3422 if (sp == NULL) {
3423 PyErr_SetString(socket_error, "service/proto not found");
3424 return NULL;
3426 return PyInt_FromLong((long) ntohs(sp->s_port));
3429 PyDoc_STRVAR(getservbyname_doc,
3430 "getservbyname(servicename[, protocolname]) -> integer\n\
3432 Return a port number from a service name and protocol name.\n\
3433 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3434 otherwise any protocol will match.");
3437 /* Python interface to getservbyport(port).
3438 This only returns the service name, since the other info is already
3439 known or not useful (like the list of aliases). */
3441 /*ARGSUSED*/
3442 static PyObject *
3443 socket_getservbyport(PyObject *self, PyObject *args)
3445 unsigned short port;
3446 char *proto=NULL;
3447 struct servent *sp;
3448 if (!PyArg_ParseTuple(args, "H|s:getservbyport", &port, &proto))
3449 return NULL;
3450 Py_BEGIN_ALLOW_THREADS
3451 sp = getservbyport(htons(port), proto);
3452 Py_END_ALLOW_THREADS
3453 if (sp == NULL) {
3454 PyErr_SetString(socket_error, "port/proto not found");
3455 return NULL;
3457 return PyString_FromString(sp->s_name);
3460 PyDoc_STRVAR(getservbyport_doc,
3461 "getservbyport(port[, protocolname]) -> string\n\
3463 Return the service name from a port number and protocol name.\n\
3464 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3465 otherwise any protocol will match.");
3467 /* Python interface to getprotobyname(name).
3468 This only returns the protocol number, since the other info is
3469 already known or not useful (like the list of aliases). */
3471 /*ARGSUSED*/
3472 static PyObject *
3473 socket_getprotobyname(PyObject *self, PyObject *args)
3475 char *name;
3476 struct protoent *sp;
3477 #ifdef __BEOS__
3478 /* Not available in BeOS yet. - [cjh] */
3479 PyErr_SetString(socket_error, "getprotobyname not supported");
3480 return NULL;
3481 #else
3482 if (!PyArg_ParseTuple(args, "s:getprotobyname", &name))
3483 return NULL;
3484 Py_BEGIN_ALLOW_THREADS
3485 sp = getprotobyname(name);
3486 Py_END_ALLOW_THREADS
3487 if (sp == NULL) {
3488 PyErr_SetString(socket_error, "protocol not found");
3489 return NULL;
3491 return PyInt_FromLong((long) sp->p_proto);
3492 #endif
3495 PyDoc_STRVAR(getprotobyname_doc,
3496 "getprotobyname(name) -> integer\n\
3498 Return the protocol number for the named protocol. (Rarely used.)");
3501 #ifdef HAVE_SOCKETPAIR
3502 /* Create a pair of sockets using the socketpair() function.
3503 Arguments as for socket() except the default family is AF_UNIX if
3504 defined on the platform; otherwise, the default is AF_INET. */
3506 /*ARGSUSED*/
3507 static PyObject *
3508 socket_socketpair(PyObject *self, PyObject *args)
3510 PySocketSockObject *s0 = NULL, *s1 = NULL;
3511 SOCKET_T sv[2];
3512 int family, type = SOCK_STREAM, proto = 0;
3513 PyObject *res = NULL;
3515 #if defined(AF_UNIX)
3516 family = AF_UNIX;
3517 #else
3518 family = AF_INET;
3519 #endif
3520 if (!PyArg_ParseTuple(args, "|iii:socketpair",
3521 &family, &type, &proto))
3522 return NULL;
3523 /* Create a pair of socket fds */
3524 if (socketpair(family, type, proto, sv) < 0)
3525 return set_error();
3526 s0 = new_sockobject(sv[0], family, type, proto);
3527 if (s0 == NULL)
3528 goto finally;
3529 s1 = new_sockobject(sv[1], family, type, proto);
3530 if (s1 == NULL)
3531 goto finally;
3532 res = PyTuple_Pack(2, s0, s1);
3534 finally:
3535 if (res == NULL) {
3536 if (s0 == NULL)
3537 SOCKETCLOSE(sv[0]);
3538 if (s1 == NULL)
3539 SOCKETCLOSE(sv[1]);
3541 Py_XDECREF(s0);
3542 Py_XDECREF(s1);
3543 return res;
3546 PyDoc_STRVAR(socketpair_doc,
3547 "socketpair([family[, type[, proto]]]) -> (socket object, socket object)\n\
3549 Create a pair of socket objects from the sockets returned by the platform\n\
3550 socketpair() function.\n\
3551 The arguments are the same as for socket() except the default family is\n\
3552 AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");
3554 #endif /* HAVE_SOCKETPAIR */
3557 #ifndef NO_DUP
3558 /* Create a socket object from a numeric file description.
3559 Useful e.g. if stdin is a socket.
3560 Additional arguments as for socket(). */
3562 /*ARGSUSED*/
3563 static PyObject *
3564 socket_fromfd(PyObject *self, PyObject *args)
3566 PySocketSockObject *s;
3567 SOCKET_T fd;
3568 int family, type, proto = 0;
3569 if (!PyArg_ParseTuple(args, "iii|i:fromfd",
3570 &fd, &family, &type, &proto))
3571 return NULL;
3572 /* Dup the fd so it and the socket can be closed independently */
3573 fd = dup(fd);
3574 if (fd < 0)
3575 return set_error();
3576 s = new_sockobject(fd, family, type, proto);
3577 return (PyObject *) s;
3580 PyDoc_STRVAR(fromfd_doc,
3581 "fromfd(fd, family, type[, proto]) -> socket object\n\
3583 Create a socket object from a duplicate of the given\n\
3584 file descriptor.\n\
3585 The remaining arguments are the same as for socket().");
3587 #endif /* NO_DUP */
3590 static PyObject *
3591 socket_ntohs(PyObject *self, PyObject *args)
3593 int x1, x2;
3595 if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) {
3596 return NULL;
3598 if (x1 < 0) {
3599 PyErr_SetString(PyExc_OverflowError,
3600 "can't convert negative number to unsigned long");
3601 return NULL;
3603 x2 = (unsigned int)ntohs((unsigned short)x1);
3604 return PyInt_FromLong(x2);
3607 PyDoc_STRVAR(ntohs_doc,
3608 "ntohs(integer) -> integer\n\
3610 Convert a 16-bit integer from network to host byte order.");
3613 static PyObject *
3614 socket_ntohl(PyObject *self, PyObject *arg)
3616 unsigned long x;
3618 if (PyInt_Check(arg)) {
3619 x = PyInt_AS_LONG(arg);
3620 if (x == (unsigned long) -1 && PyErr_Occurred())
3621 return NULL;
3622 if ((long)x < 0) {
3623 PyErr_SetString(PyExc_OverflowError,
3624 "can't convert negative number to unsigned long");
3625 return NULL;
3628 else if (PyLong_Check(arg)) {
3629 x = PyLong_AsUnsignedLong(arg);
3630 if (x == (unsigned long) -1 && PyErr_Occurred())
3631 return NULL;
3632 #if SIZEOF_LONG > 4
3634 unsigned long y;
3635 /* only want the trailing 32 bits */
3636 y = x & 0xFFFFFFFFUL;
3637 if (y ^ x)
3638 return PyErr_Format(PyExc_OverflowError,
3639 "long int larger than 32 bits");
3640 x = y;
3642 #endif
3644 else
3645 return PyErr_Format(PyExc_TypeError,
3646 "expected int/long, %s found",
3647 Py_TYPE(arg)->tp_name);
3648 if (x == (unsigned long) -1 && PyErr_Occurred())
3649 return NULL;
3650 return PyLong_FromUnsignedLong(ntohl(x));
3653 PyDoc_STRVAR(ntohl_doc,
3654 "ntohl(integer) -> integer\n\
3656 Convert a 32-bit integer from network to host byte order.");
3659 static PyObject *
3660 socket_htons(PyObject *self, PyObject *args)
3662 int x1, x2;
3664 if (!PyArg_ParseTuple(args, "i:htons", &x1)) {
3665 return NULL;
3667 if (x1 < 0) {
3668 PyErr_SetString(PyExc_OverflowError,
3669 "can't convert negative number to unsigned long");
3670 return NULL;
3672 x2 = (unsigned int)htons((unsigned short)x1);
3673 return PyInt_FromLong(x2);
3676 PyDoc_STRVAR(htons_doc,
3677 "htons(integer) -> integer\n\
3679 Convert a 16-bit integer from host to network byte order.");
3682 static PyObject *
3683 socket_htonl(PyObject *self, PyObject *arg)
3685 unsigned long x;
3687 if (PyInt_Check(arg)) {
3688 x = PyInt_AS_LONG(arg);
3689 if (x == (unsigned long) -1 && PyErr_Occurred())
3690 return NULL;
3691 if ((long)x < 0) {
3692 PyErr_SetString(PyExc_OverflowError,
3693 "can't convert negative number to unsigned long");
3694 return NULL;
3697 else if (PyLong_Check(arg)) {
3698 x = PyLong_AsUnsignedLong(arg);
3699 if (x == (unsigned long) -1 && PyErr_Occurred())
3700 return NULL;
3701 #if SIZEOF_LONG > 4
3703 unsigned long y;
3704 /* only want the trailing 32 bits */
3705 y = x & 0xFFFFFFFFUL;
3706 if (y ^ x)
3707 return PyErr_Format(PyExc_OverflowError,
3708 "long int larger than 32 bits");
3709 x = y;
3711 #endif
3713 else
3714 return PyErr_Format(PyExc_TypeError,
3715 "expected int/long, %s found",
3716 Py_TYPE(arg)->tp_name);
3717 return PyLong_FromUnsignedLong(htonl((unsigned long)x));
3720 PyDoc_STRVAR(htonl_doc,
3721 "htonl(integer) -> integer\n\
3723 Convert a 32-bit integer from host to network byte order.");
3725 /* socket.inet_aton() and socket.inet_ntoa() functions. */
3727 PyDoc_STRVAR(inet_aton_doc,
3728 "inet_aton(string) -> packed 32-bit IP representation\n\
3730 Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
3731 binary format used in low-level network functions.");
3733 static PyObject*
3734 socket_inet_aton(PyObject *self, PyObject *args)
3736 #ifndef INADDR_NONE
3737 #define INADDR_NONE (-1)
3738 #endif
3739 #ifdef HAVE_INET_ATON
3740 struct in_addr buf;
3741 #endif
3743 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
3744 /* Have to use inet_addr() instead */
3745 unsigned long packed_addr;
3746 #endif
3747 char *ip_addr;
3749 if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr))
3750 return NULL;
3753 #ifdef HAVE_INET_ATON
3755 #ifdef USE_INET_ATON_WEAKLINK
3756 if (inet_aton != NULL) {
3757 #endif
3758 if (inet_aton(ip_addr, &buf))
3759 return PyString_FromStringAndSize((char *)(&buf),
3760 sizeof(buf));
3762 PyErr_SetString(socket_error,
3763 "illegal IP address string passed to inet_aton");
3764 return NULL;
3766 #ifdef USE_INET_ATON_WEAKLINK
3767 } else {
3768 #endif
3770 #endif
3772 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
3774 /* special-case this address as inet_addr might return INADDR_NONE
3775 * for this */
3776 if (strcmp(ip_addr, "255.255.255.255") == 0) {
3777 packed_addr = 0xFFFFFFFF;
3778 } else {
3780 packed_addr = inet_addr(ip_addr);
3782 if (packed_addr == INADDR_NONE) { /* invalid address */
3783 PyErr_SetString(socket_error,
3784 "illegal IP address string passed to inet_aton");
3785 return NULL;
3788 return PyString_FromStringAndSize((char *) &packed_addr,
3789 sizeof(packed_addr));
3791 #ifdef USE_INET_ATON_WEAKLINK
3793 #endif
3795 #endif
3798 PyDoc_STRVAR(inet_ntoa_doc,
3799 "inet_ntoa(packed_ip) -> ip_address_string\n\
3801 Convert an IP address from 32-bit packed binary format to string format");
3803 static PyObject*
3804 socket_inet_ntoa(PyObject *self, PyObject *args)
3806 char *packed_str;
3807 int addr_len;
3808 struct in_addr packed_addr;
3810 if (!PyArg_ParseTuple(args, "s#:inet_ntoa", &packed_str, &addr_len)) {
3811 return NULL;
3814 if (addr_len != sizeof(packed_addr)) {
3815 PyErr_SetString(socket_error,
3816 "packed IP wrong length for inet_ntoa");
3817 return NULL;
3820 memcpy(&packed_addr, packed_str, addr_len);
3822 return PyString_FromString(inet_ntoa(packed_addr));
3825 #ifdef HAVE_INET_PTON
3827 PyDoc_STRVAR(inet_pton_doc,
3828 "inet_pton(af, ip) -> packed IP address string\n\
3830 Convert an IP address from string format to a packed string suitable\n\
3831 for use with low-level network functions.");
3833 static PyObject *
3834 socket_inet_pton(PyObject *self, PyObject *args)
3836 int af;
3837 char* ip;
3838 int retval;
3839 #ifdef ENABLE_IPV6
3840 char packed[MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
3841 #else
3842 char packed[sizeof(struct in_addr)];
3843 #endif
3844 if (!PyArg_ParseTuple(args, "is:inet_pton", &af, &ip)) {
3845 return NULL;
3848 #if !defined(ENABLE_IPV6) && defined(AF_INET6)
3849 if(af == AF_INET6) {
3850 PyErr_SetString(socket_error,
3851 "can't use AF_INET6, IPv6 is disabled");
3852 return NULL;
3854 #endif
3856 retval = inet_pton(af, ip, packed);
3857 if (retval < 0) {
3858 PyErr_SetFromErrno(socket_error);
3859 return NULL;
3860 } else if (retval == 0) {
3861 PyErr_SetString(socket_error,
3862 "illegal IP address string passed to inet_pton");
3863 return NULL;
3864 } else if (af == AF_INET) {
3865 return PyString_FromStringAndSize(packed,
3866 sizeof(struct in_addr));
3867 #ifdef ENABLE_IPV6
3868 } else if (af == AF_INET6) {
3869 return PyString_FromStringAndSize(packed,
3870 sizeof(struct in6_addr));
3871 #endif
3872 } else {
3873 PyErr_SetString(socket_error, "unknown address family");
3874 return NULL;
3878 PyDoc_STRVAR(inet_ntop_doc,
3879 "inet_ntop(af, packed_ip) -> string formatted IP address\n\
3881 Convert a packed IP address of the given family to string format.");
3883 static PyObject *
3884 socket_inet_ntop(PyObject *self, PyObject *args)
3886 int af;
3887 char* packed;
3888 int len;
3889 const char* retval;
3890 #ifdef ENABLE_IPV6
3891 char ip[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) + 1];
3892 #else
3893 char ip[INET_ADDRSTRLEN + 1];
3894 #endif
3896 /* Guarantee NUL-termination for PyString_FromString() below */
3897 memset((void *) &ip[0], '\0', sizeof(ip));
3899 if (!PyArg_ParseTuple(args, "is#:inet_ntop", &af, &packed, &len)) {
3900 return NULL;
3903 if (af == AF_INET) {
3904 if (len != sizeof(struct in_addr)) {
3905 PyErr_SetString(PyExc_ValueError,
3906 "invalid length of packed IP address string");
3907 return NULL;
3909 #ifdef ENABLE_IPV6
3910 } else if (af == AF_INET6) {
3911 if (len != sizeof(struct in6_addr)) {
3912 PyErr_SetString(PyExc_ValueError,
3913 "invalid length of packed IP address string");
3914 return NULL;
3916 #endif
3917 } else {
3918 PyErr_Format(PyExc_ValueError,
3919 "unknown address family %d", af);
3920 return NULL;
3923 retval = inet_ntop(af, packed, ip, sizeof(ip));
3924 if (!retval) {
3925 PyErr_SetFromErrno(socket_error);
3926 return NULL;
3927 } else {
3928 return PyString_FromString(retval);
3931 /* NOTREACHED */
3932 PyErr_SetString(PyExc_RuntimeError, "invalid handling of inet_ntop");
3933 return NULL;
3936 #endif /* HAVE_INET_PTON */
3938 /* Python interface to getaddrinfo(host, port). */
3940 /*ARGSUSED*/
3941 static PyObject *
3942 socket_getaddrinfo(PyObject *self, PyObject *args)
3944 struct addrinfo hints, *res;
3945 struct addrinfo *res0 = NULL;
3946 PyObject *hobj = NULL;
3947 PyObject *pobj = (PyObject *)NULL;
3948 char pbuf[30];
3949 char *hptr, *pptr;
3950 int family, socktype, protocol, flags;
3951 int error;
3952 PyObject *all = (PyObject *)NULL;
3953 PyObject *single = (PyObject *)NULL;
3954 PyObject *idna = NULL;
3956 family = socktype = protocol = flags = 0;
3957 family = AF_UNSPEC;
3958 if (!PyArg_ParseTuple(args, "OO|iiii:getaddrinfo",
3959 &hobj, &pobj, &family, &socktype,
3960 &protocol, &flags)) {
3961 return NULL;
3963 if (hobj == Py_None) {
3964 hptr = NULL;
3965 } else if (PyUnicode_Check(hobj)) {
3966 idna = PyObject_CallMethod(hobj, "encode", "s", "idna");
3967 if (!idna)
3968 return NULL;
3969 hptr = PyString_AsString(idna);
3970 } else if (PyString_Check(hobj)) {
3971 hptr = PyString_AsString(hobj);
3972 } else {
3973 PyErr_SetString(PyExc_TypeError,
3974 "getaddrinfo() argument 1 must be string or None");
3975 return NULL;
3977 if (PyInt_Check(pobj)) {
3978 PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", PyInt_AsLong(pobj));
3979 pptr = pbuf;
3980 } else if (PyString_Check(pobj)) {
3981 pptr = PyString_AsString(pobj);
3982 } else if (pobj == Py_None) {
3983 pptr = (char *)NULL;
3984 } else {
3985 PyErr_SetString(socket_error, "Int or String expected");
3986 goto err;
3988 memset(&hints, 0, sizeof(hints));
3989 hints.ai_family = family;
3990 hints.ai_socktype = socktype;
3991 hints.ai_protocol = protocol;
3992 hints.ai_flags = flags;
3993 Py_BEGIN_ALLOW_THREADS
3994 ACQUIRE_GETADDRINFO_LOCK
3995 error = getaddrinfo(hptr, pptr, &hints, &res0);
3996 Py_END_ALLOW_THREADS
3997 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
3998 if (error) {
3999 set_gaierror(error);
4000 goto err;
4003 if ((all = PyList_New(0)) == NULL)
4004 goto err;
4005 for (res = res0; res; res = res->ai_next) {
4006 PyObject *addr =
4007 makesockaddr(-1, res->ai_addr, res->ai_addrlen, protocol);
4008 if (addr == NULL)
4009 goto err;
4010 single = Py_BuildValue("iiisO", res->ai_family,
4011 res->ai_socktype, res->ai_protocol,
4012 res->ai_canonname ? res->ai_canonname : "",
4013 addr);
4014 Py_DECREF(addr);
4015 if (single == NULL)
4016 goto err;
4018 if (PyList_Append(all, single))
4019 goto err;
4020 Py_XDECREF(single);
4022 Py_XDECREF(idna);
4023 if (res0)
4024 freeaddrinfo(res0);
4025 return all;
4026 err:
4027 Py_XDECREF(single);
4028 Py_XDECREF(all);
4029 Py_XDECREF(idna);
4030 if (res0)
4031 freeaddrinfo(res0);
4032 return (PyObject *)NULL;
4035 PyDoc_STRVAR(getaddrinfo_doc,
4036 "getaddrinfo(host, port [, family, socktype, proto, flags])\n\
4037 -> list of (family, socktype, proto, canonname, sockaddr)\n\
4039 Resolve host and port into addrinfo struct.");
4041 /* Python interface to getnameinfo(sa, flags). */
4043 /*ARGSUSED*/
4044 static PyObject *
4045 socket_getnameinfo(PyObject *self, PyObject *args)
4047 PyObject *sa = (PyObject *)NULL;
4048 int flags;
4049 char *hostp;
4050 int port, flowinfo, scope_id;
4051 char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
4052 struct addrinfo hints, *res = NULL;
4053 int error;
4054 PyObject *ret = (PyObject *)NULL;
4056 flags = flowinfo = scope_id = 0;
4057 if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags))
4058 return NULL;
4059 if (!PyArg_ParseTuple(sa, "si|ii",
4060 &hostp, &port, &flowinfo, &scope_id))
4061 return NULL;
4062 PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port);
4063 memset(&hints, 0, sizeof(hints));
4064 hints.ai_family = AF_UNSPEC;
4065 hints.ai_socktype = SOCK_DGRAM; /* make numeric port happy */
4066 Py_BEGIN_ALLOW_THREADS
4067 ACQUIRE_GETADDRINFO_LOCK
4068 error = getaddrinfo(hostp, pbuf, &hints, &res);
4069 Py_END_ALLOW_THREADS
4070 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
4071 if (error) {
4072 set_gaierror(error);
4073 goto fail;
4075 if (res->ai_next) {
4076 PyErr_SetString(socket_error,
4077 "sockaddr resolved to multiple addresses");
4078 goto fail;
4080 switch (res->ai_family) {
4081 case AF_INET:
4083 char *t1;
4084 int t2;
4085 if (PyArg_ParseTuple(sa, "si", &t1, &t2) == 0) {
4086 PyErr_SetString(socket_error,
4087 "IPv4 sockaddr must be 2 tuple");
4088 goto fail;
4090 break;
4092 #ifdef ENABLE_IPV6
4093 case AF_INET6:
4095 struct sockaddr_in6 *sin6;
4096 sin6 = (struct sockaddr_in6 *)res->ai_addr;
4097 sin6->sin6_flowinfo = flowinfo;
4098 sin6->sin6_scope_id = scope_id;
4099 break;
4101 #endif
4103 error = getnameinfo(res->ai_addr, res->ai_addrlen,
4104 hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags);
4105 if (error) {
4106 set_gaierror(error);
4107 goto fail;
4109 ret = Py_BuildValue("ss", hbuf, pbuf);
4111 fail:
4112 if (res)
4113 freeaddrinfo(res);
4114 return ret;
4117 PyDoc_STRVAR(getnameinfo_doc,
4118 "getnameinfo(sockaddr, flags) --> (host, port)\n\
4120 Get host and port for a sockaddr.");
4123 /* Python API to getting and setting the default timeout value. */
4125 static PyObject *
4126 socket_getdefaulttimeout(PyObject *self)
4128 if (defaulttimeout < 0.0) {
4129 Py_INCREF(Py_None);
4130 return Py_None;
4132 else
4133 return PyFloat_FromDouble(defaulttimeout);
4136 PyDoc_STRVAR(getdefaulttimeout_doc,
4137 "getdefaulttimeout() -> timeout\n\
4139 Returns the default timeout in floating seconds for new socket objects.\n\
4140 A value of None indicates that new socket objects have no timeout.\n\
4141 When the socket module is first imported, the default is None.");
4143 static PyObject *
4144 socket_setdefaulttimeout(PyObject *self, PyObject *arg)
4146 double timeout;
4148 if (arg == Py_None)
4149 timeout = -1.0;
4150 else {
4151 timeout = PyFloat_AsDouble(arg);
4152 if (timeout < 0.0) {
4153 if (!PyErr_Occurred())
4154 PyErr_SetString(PyExc_ValueError,
4155 "Timeout value out of range");
4156 return NULL;
4160 defaulttimeout = timeout;
4162 Py_INCREF(Py_None);
4163 return Py_None;
4166 PyDoc_STRVAR(setdefaulttimeout_doc,
4167 "setdefaulttimeout(timeout)\n\
4169 Set the default timeout in floating seconds for new socket objects.\n\
4170 A value of None indicates that new socket objects have no timeout.\n\
4171 When the socket module is first imported, the default is None.");
4174 /* List of functions exported by this module. */
4176 static PyMethodDef socket_methods[] = {
4177 {"gethostbyname", socket_gethostbyname,
4178 METH_VARARGS, gethostbyname_doc},
4179 {"gethostbyname_ex", socket_gethostbyname_ex,
4180 METH_VARARGS, ghbn_ex_doc},
4181 {"gethostbyaddr", socket_gethostbyaddr,
4182 METH_VARARGS, gethostbyaddr_doc},
4183 {"gethostname", socket_gethostname,
4184 METH_NOARGS, gethostname_doc},
4185 {"getservbyname", socket_getservbyname,
4186 METH_VARARGS, getservbyname_doc},
4187 {"getservbyport", socket_getservbyport,
4188 METH_VARARGS, getservbyport_doc},
4189 {"getprotobyname", socket_getprotobyname,
4190 METH_VARARGS, getprotobyname_doc},
4191 #ifndef NO_DUP
4192 {"fromfd", socket_fromfd,
4193 METH_VARARGS, fromfd_doc},
4194 #endif
4195 #ifdef HAVE_SOCKETPAIR
4196 {"socketpair", socket_socketpair,
4197 METH_VARARGS, socketpair_doc},
4198 #endif
4199 {"ntohs", socket_ntohs,
4200 METH_VARARGS, ntohs_doc},
4201 {"ntohl", socket_ntohl,
4202 METH_O, ntohl_doc},
4203 {"htons", socket_htons,
4204 METH_VARARGS, htons_doc},
4205 {"htonl", socket_htonl,
4206 METH_O, htonl_doc},
4207 {"inet_aton", socket_inet_aton,
4208 METH_VARARGS, inet_aton_doc},
4209 {"inet_ntoa", socket_inet_ntoa,
4210 METH_VARARGS, inet_ntoa_doc},
4211 #ifdef HAVE_INET_PTON
4212 {"inet_pton", socket_inet_pton,
4213 METH_VARARGS, inet_pton_doc},
4214 {"inet_ntop", socket_inet_ntop,
4215 METH_VARARGS, inet_ntop_doc},
4216 #endif
4217 {"getaddrinfo", socket_getaddrinfo,
4218 METH_VARARGS, getaddrinfo_doc},
4219 {"getnameinfo", socket_getnameinfo,
4220 METH_VARARGS, getnameinfo_doc},
4221 {"getdefaulttimeout", (PyCFunction)socket_getdefaulttimeout,
4222 METH_NOARGS, getdefaulttimeout_doc},
4223 {"setdefaulttimeout", socket_setdefaulttimeout,
4224 METH_O, setdefaulttimeout_doc},
4225 {NULL, NULL} /* Sentinel */
4229 #ifdef RISCOS
4230 #define OS_INIT_DEFINED
4232 static int
4233 os_init(void)
4235 _kernel_swi_regs r;
4237 r.r[0] = 0;
4238 _kernel_swi(0x43380, &r, &r);
4239 taskwindow = r.r[0];
4241 return 1;
4244 #endif /* RISCOS */
4247 #ifdef MS_WINDOWS
4248 #define OS_INIT_DEFINED
4250 /* Additional initialization and cleanup for Windows */
4252 static void
4253 os_cleanup(void)
4255 WSACleanup();
4258 static int
4259 os_init(void)
4261 WSADATA WSAData;
4262 int ret;
4263 char buf[100];
4264 ret = WSAStartup(0x0101, &WSAData);
4265 switch (ret) {
4266 case 0: /* No error */
4267 Py_AtExit(os_cleanup);
4268 return 1; /* Success */
4269 case WSASYSNOTREADY:
4270 PyErr_SetString(PyExc_ImportError,
4271 "WSAStartup failed: network not ready");
4272 break;
4273 case WSAVERNOTSUPPORTED:
4274 case WSAEINVAL:
4275 PyErr_SetString(
4276 PyExc_ImportError,
4277 "WSAStartup failed: requested version not supported");
4278 break;
4279 default:
4280 PyOS_snprintf(buf, sizeof(buf),
4281 "WSAStartup failed: error code %d", ret);
4282 PyErr_SetString(PyExc_ImportError, buf);
4283 break;
4285 return 0; /* Failure */
4288 #endif /* MS_WINDOWS */
4291 #ifdef PYOS_OS2
4292 #define OS_INIT_DEFINED
4294 /* Additional initialization for OS/2 */
4296 static int
4297 os_init(void)
4299 #ifndef PYCC_GCC
4300 char reason[64];
4301 int rc = sock_init();
4303 if (rc == 0) {
4304 return 1; /* Success */
4307 PyOS_snprintf(reason, sizeof(reason),
4308 "OS/2 TCP/IP Error# %d", sock_errno());
4309 PyErr_SetString(PyExc_ImportError, reason);
4311 return 0; /* Failure */
4312 #else
4313 /* No need to initialise sockets with GCC/EMX */
4314 return 1; /* Success */
4315 #endif
4318 #endif /* PYOS_OS2 */
4321 #ifndef OS_INIT_DEFINED
4322 static int
4323 os_init(void)
4325 return 1; /* Success */
4327 #endif
4330 /* C API table - always add new things to the end for binary
4331 compatibility. */
4332 static
4333 PySocketModule_APIObject PySocketModuleAPI =
4335 &sock_type,
4336 NULL
4340 /* Initialize the _socket module.
4342 This module is actually called "_socket", and there's a wrapper
4343 "socket.py" which implements some additional functionality. On some
4344 platforms (e.g. Windows and OS/2), socket.py also implements a
4345 wrapper for the socket type that provides missing functionality such
4346 as makefile(), dup() and fromfd(). The import of "_socket" may fail
4347 with an ImportError exception if os-specific initialization fails.
4348 On Windows, this does WINSOCK initialization. When WINSOCK is
4349 initialized succesfully, a call to WSACleanup() is scheduled to be
4350 made at exit time.
4353 PyDoc_STRVAR(socket_doc,
4354 "Implementation module for socket operations.\n\
4356 See the socket module for documentation.");
4358 PyMODINIT_FUNC
4359 init_socket(void)
4361 PyObject *m, *has_ipv6;
4363 if (!os_init())
4364 return;
4366 Py_TYPE(&sock_type) = &PyType_Type;
4367 m = Py_InitModule3(PySocket_MODULE_NAME,
4368 socket_methods,
4369 socket_doc);
4370 if (m == NULL)
4371 return;
4373 socket_error = PyErr_NewException("socket.error",
4374 PyExc_IOError, NULL);
4375 if (socket_error == NULL)
4376 return;
4377 PySocketModuleAPI.error = socket_error;
4378 Py_INCREF(socket_error);
4379 PyModule_AddObject(m, "error", socket_error);
4380 socket_herror = PyErr_NewException("socket.herror",
4381 socket_error, NULL);
4382 if (socket_herror == NULL)
4383 return;
4384 Py_INCREF(socket_herror);
4385 PyModule_AddObject(m, "herror", socket_herror);
4386 socket_gaierror = PyErr_NewException("socket.gaierror", socket_error,
4387 NULL);
4388 if (socket_gaierror == NULL)
4389 return;
4390 Py_INCREF(socket_gaierror);
4391 PyModule_AddObject(m, "gaierror", socket_gaierror);
4392 socket_timeout = PyErr_NewException("socket.timeout",
4393 socket_error, NULL);
4394 if (socket_timeout == NULL)
4395 return;
4396 Py_INCREF(socket_timeout);
4397 PyModule_AddObject(m, "timeout", socket_timeout);
4398 Py_INCREF((PyObject *)&sock_type);
4399 if (PyModule_AddObject(m, "SocketType",
4400 (PyObject *)&sock_type) != 0)
4401 return;
4402 Py_INCREF((PyObject *)&sock_type);
4403 if (PyModule_AddObject(m, "socket",
4404 (PyObject *)&sock_type) != 0)
4405 return;
4407 #ifdef ENABLE_IPV6
4408 has_ipv6 = Py_True;
4409 #else
4410 has_ipv6 = Py_False;
4411 #endif
4412 Py_INCREF(has_ipv6);
4413 PyModule_AddObject(m, "has_ipv6", has_ipv6);
4415 /* Export C API */
4416 if (PyModule_AddObject(m, PySocket_CAPI_NAME,
4417 PyCObject_FromVoidPtr((void *)&PySocketModuleAPI, NULL)
4418 ) != 0)
4419 return;
4421 /* Address families (we only support AF_INET and AF_UNIX) */
4422 #ifdef AF_UNSPEC
4423 PyModule_AddIntConstant(m, "AF_UNSPEC", AF_UNSPEC);
4424 #endif
4425 PyModule_AddIntConstant(m, "AF_INET", AF_INET);
4426 #ifdef AF_INET6
4427 PyModule_AddIntConstant(m, "AF_INET6", AF_INET6);
4428 #endif /* AF_INET6 */
4429 #if defined(AF_UNIX)
4430 PyModule_AddIntConstant(m, "AF_UNIX", AF_UNIX);
4431 #endif /* AF_UNIX */
4432 #ifdef AF_AX25
4433 /* Amateur Radio AX.25 */
4434 PyModule_AddIntConstant(m, "AF_AX25", AF_AX25);
4435 #endif
4436 #ifdef AF_IPX
4437 PyModule_AddIntConstant(m, "AF_IPX", AF_IPX); /* Novell IPX */
4438 #endif
4439 #ifdef AF_APPLETALK
4440 /* Appletalk DDP */
4441 PyModule_AddIntConstant(m, "AF_APPLETALK", AF_APPLETALK);
4442 #endif
4443 #ifdef AF_NETROM
4444 /* Amateur radio NetROM */
4445 PyModule_AddIntConstant(m, "AF_NETROM", AF_NETROM);
4446 #endif
4447 #ifdef AF_BRIDGE
4448 /* Multiprotocol bridge */
4449 PyModule_AddIntConstant(m, "AF_BRIDGE", AF_BRIDGE);
4450 #endif
4451 #ifdef AF_ATMPVC
4452 /* ATM PVCs */
4453 PyModule_AddIntConstant(m, "AF_ATMPVC", AF_ATMPVC);
4454 #endif
4455 #ifdef AF_AAL5
4456 /* Reserved for Werner's ATM */
4457 PyModule_AddIntConstant(m, "AF_AAL5", AF_AAL5);
4458 #endif
4459 #ifdef AF_X25
4460 /* Reserved for X.25 project */
4461 PyModule_AddIntConstant(m, "AF_X25", AF_X25);
4462 #endif
4463 #ifdef AF_INET6
4464 PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); /* IP version 6 */
4465 #endif
4466 #ifdef AF_ROSE
4467 /* Amateur Radio X.25 PLP */
4468 PyModule_AddIntConstant(m, "AF_ROSE", AF_ROSE);
4469 #endif
4470 #ifdef AF_DECnet
4471 /* Reserved for DECnet project */
4472 PyModule_AddIntConstant(m, "AF_DECnet", AF_DECnet);
4473 #endif
4474 #ifdef AF_NETBEUI
4475 /* Reserved for 802.2LLC project */
4476 PyModule_AddIntConstant(m, "AF_NETBEUI", AF_NETBEUI);
4477 #endif
4478 #ifdef AF_SECURITY
4479 /* Security callback pseudo AF */
4480 PyModule_AddIntConstant(m, "AF_SECURITY", AF_SECURITY);
4481 #endif
4482 #ifdef AF_KEY
4483 /* PF_KEY key management API */
4484 PyModule_AddIntConstant(m, "AF_KEY", AF_KEY);
4485 #endif
4486 #ifdef AF_NETLINK
4487 /* */
4488 PyModule_AddIntConstant(m, "AF_NETLINK", AF_NETLINK);
4489 PyModule_AddIntConstant(m, "NETLINK_ROUTE", NETLINK_ROUTE);
4490 #ifdef NETLINK_SKIP
4491 PyModule_AddIntConstant(m, "NETLINK_SKIP", NETLINK_SKIP);
4492 #endif
4493 #ifdef NETLINK_W1
4494 PyModule_AddIntConstant(m, "NETLINK_W1", NETLINK_W1);
4495 #endif
4496 PyModule_AddIntConstant(m, "NETLINK_USERSOCK", NETLINK_USERSOCK);
4497 PyModule_AddIntConstant(m, "NETLINK_FIREWALL", NETLINK_FIREWALL);
4498 #ifdef NETLINK_TCPDIAG
4499 PyModule_AddIntConstant(m, "NETLINK_TCPDIAG", NETLINK_TCPDIAG);
4500 #endif
4501 #ifdef NETLINK_NFLOG
4502 PyModule_AddIntConstant(m, "NETLINK_NFLOG", NETLINK_NFLOG);
4503 #endif
4504 #ifdef NETLINK_XFRM
4505 PyModule_AddIntConstant(m, "NETLINK_XFRM", NETLINK_XFRM);
4506 #endif
4507 #ifdef NETLINK_ARPD
4508 PyModule_AddIntConstant(m, "NETLINK_ARPD", NETLINK_ARPD);
4509 #endif
4510 #ifdef NETLINK_ROUTE6
4511 PyModule_AddIntConstant(m, "NETLINK_ROUTE6", NETLINK_ROUTE6);
4512 #endif
4513 PyModule_AddIntConstant(m, "NETLINK_IP6_FW", NETLINK_IP6_FW);
4514 #ifdef NETLINK_DNRTMSG
4515 PyModule_AddIntConstant(m, "NETLINK_DNRTMSG", NETLINK_DNRTMSG);
4516 #endif
4517 #ifdef NETLINK_TAPBASE
4518 PyModule_AddIntConstant(m, "NETLINK_TAPBASE", NETLINK_TAPBASE);
4519 #endif
4520 #endif /* AF_NETLINK */
4521 #ifdef AF_ROUTE
4522 /* Alias to emulate 4.4BSD */
4523 PyModule_AddIntConstant(m, "AF_ROUTE", AF_ROUTE);
4524 #endif
4525 #ifdef AF_ASH
4526 /* Ash */
4527 PyModule_AddIntConstant(m, "AF_ASH", AF_ASH);
4528 #endif
4529 #ifdef AF_ECONET
4530 /* Acorn Econet */
4531 PyModule_AddIntConstant(m, "AF_ECONET", AF_ECONET);
4532 #endif
4533 #ifdef AF_ATMSVC
4534 /* ATM SVCs */
4535 PyModule_AddIntConstant(m, "AF_ATMSVC", AF_ATMSVC);
4536 #endif
4537 #ifdef AF_SNA
4538 /* Linux SNA Project (nutters!) */
4539 PyModule_AddIntConstant(m, "AF_SNA", AF_SNA);
4540 #endif
4541 #ifdef AF_IRDA
4542 /* IRDA sockets */
4543 PyModule_AddIntConstant(m, "AF_IRDA", AF_IRDA);
4544 #endif
4545 #ifdef AF_PPPOX
4546 /* PPPoX sockets */
4547 PyModule_AddIntConstant(m, "AF_PPPOX", AF_PPPOX);
4548 #endif
4549 #ifdef AF_WANPIPE
4550 /* Wanpipe API Sockets */
4551 PyModule_AddIntConstant(m, "AF_WANPIPE", AF_WANPIPE);
4552 #endif
4553 #ifdef AF_LLC
4554 /* Linux LLC */
4555 PyModule_AddIntConstant(m, "AF_LLC", AF_LLC);
4556 #endif
4558 #ifdef USE_BLUETOOTH
4559 PyModule_AddIntConstant(m, "AF_BLUETOOTH", AF_BLUETOOTH);
4560 PyModule_AddIntConstant(m, "BTPROTO_L2CAP", BTPROTO_L2CAP);
4561 PyModule_AddIntConstant(m, "BTPROTO_HCI", BTPROTO_HCI);
4562 PyModule_AddIntConstant(m, "SOL_HCI", SOL_HCI);
4563 PyModule_AddIntConstant(m, "HCI_FILTER", HCI_FILTER);
4564 #if !defined(__FreeBSD__)
4565 PyModule_AddIntConstant(m, "HCI_TIME_STAMP", HCI_TIME_STAMP);
4566 PyModule_AddIntConstant(m, "HCI_DATA_DIR", HCI_DATA_DIR);
4567 PyModule_AddIntConstant(m, "BTPROTO_SCO", BTPROTO_SCO);
4568 #endif
4569 PyModule_AddIntConstant(m, "BTPROTO_RFCOMM", BTPROTO_RFCOMM);
4570 PyModule_AddStringConstant(m, "BDADDR_ANY", "00:00:00:00:00:00");
4571 PyModule_AddStringConstant(m, "BDADDR_LOCAL", "00:00:00:FF:FF:FF");
4572 #endif
4574 #ifdef HAVE_NETPACKET_PACKET_H
4575 PyModule_AddIntConstant(m, "AF_PACKET", AF_PACKET);
4576 PyModule_AddIntConstant(m, "PF_PACKET", PF_PACKET);
4577 PyModule_AddIntConstant(m, "PACKET_HOST", PACKET_HOST);
4578 PyModule_AddIntConstant(m, "PACKET_BROADCAST", PACKET_BROADCAST);
4579 PyModule_AddIntConstant(m, "PACKET_MULTICAST", PACKET_MULTICAST);
4580 PyModule_AddIntConstant(m, "PACKET_OTHERHOST", PACKET_OTHERHOST);
4581 PyModule_AddIntConstant(m, "PACKET_OUTGOING", PACKET_OUTGOING);
4582 PyModule_AddIntConstant(m, "PACKET_LOOPBACK", PACKET_LOOPBACK);
4583 PyModule_AddIntConstant(m, "PACKET_FASTROUTE", PACKET_FASTROUTE);
4584 #endif
4586 #ifdef HAVE_LINUX_TIPC_H
4587 PyModule_AddIntConstant(m, "AF_TIPC", AF_TIPC);
4589 /* for addresses */
4590 PyModule_AddIntConstant(m, "TIPC_ADDR_NAMESEQ", TIPC_ADDR_NAMESEQ);
4591 PyModule_AddIntConstant(m, "TIPC_ADDR_NAME", TIPC_ADDR_NAME);
4592 PyModule_AddIntConstant(m, "TIPC_ADDR_ID", TIPC_ADDR_ID);
4594 PyModule_AddIntConstant(m, "TIPC_ZONE_SCOPE", TIPC_ZONE_SCOPE);
4595 PyModule_AddIntConstant(m, "TIPC_CLUSTER_SCOPE", TIPC_CLUSTER_SCOPE);
4596 PyModule_AddIntConstant(m, "TIPC_NODE_SCOPE", TIPC_NODE_SCOPE);
4598 /* for setsockopt() */
4599 PyModule_AddIntConstant(m, "SOL_TIPC", SOL_TIPC);
4600 PyModule_AddIntConstant(m, "TIPC_IMPORTANCE", TIPC_IMPORTANCE);
4601 PyModule_AddIntConstant(m, "TIPC_SRC_DROPPABLE", TIPC_SRC_DROPPABLE);
4602 PyModule_AddIntConstant(m, "TIPC_DEST_DROPPABLE",
4603 TIPC_DEST_DROPPABLE);
4604 PyModule_AddIntConstant(m, "TIPC_CONN_TIMEOUT", TIPC_CONN_TIMEOUT);
4606 PyModule_AddIntConstant(m, "TIPC_LOW_IMPORTANCE",
4607 TIPC_LOW_IMPORTANCE);
4608 PyModule_AddIntConstant(m, "TIPC_MEDIUM_IMPORTANCE",
4609 TIPC_MEDIUM_IMPORTANCE);
4610 PyModule_AddIntConstant(m, "TIPC_HIGH_IMPORTANCE",
4611 TIPC_HIGH_IMPORTANCE);
4612 PyModule_AddIntConstant(m, "TIPC_CRITICAL_IMPORTANCE",
4613 TIPC_CRITICAL_IMPORTANCE);
4615 /* for subscriptions */
4616 PyModule_AddIntConstant(m, "TIPC_SUB_PORTS", TIPC_SUB_PORTS);
4617 PyModule_AddIntConstant(m, "TIPC_SUB_SERVICE", TIPC_SUB_SERVICE);
4618 #ifdef TIPC_SUB_CANCEL
4619 /* doesn't seem to be available everywhere */
4620 PyModule_AddIntConstant(m, "TIPC_SUB_CANCEL", TIPC_SUB_CANCEL);
4621 #endif
4622 PyModule_AddIntConstant(m, "TIPC_WAIT_FOREVER", TIPC_WAIT_FOREVER);
4623 PyModule_AddIntConstant(m, "TIPC_PUBLISHED", TIPC_PUBLISHED);
4624 PyModule_AddIntConstant(m, "TIPC_WITHDRAWN", TIPC_WITHDRAWN);
4625 PyModule_AddIntConstant(m, "TIPC_SUBSCR_TIMEOUT", TIPC_SUBSCR_TIMEOUT);
4626 PyModule_AddIntConstant(m, "TIPC_CFG_SRV", TIPC_CFG_SRV);
4627 PyModule_AddIntConstant(m, "TIPC_TOP_SRV", TIPC_TOP_SRV);
4628 #endif
4630 /* Socket types */
4631 PyModule_AddIntConstant(m, "SOCK_STREAM", SOCK_STREAM);
4632 PyModule_AddIntConstant(m, "SOCK_DGRAM", SOCK_DGRAM);
4633 #ifndef __BEOS__
4634 /* We have incomplete socket support. */
4635 PyModule_AddIntConstant(m, "SOCK_RAW", SOCK_RAW);
4636 PyModule_AddIntConstant(m, "SOCK_SEQPACKET", SOCK_SEQPACKET);
4637 #if defined(SOCK_RDM)
4638 PyModule_AddIntConstant(m, "SOCK_RDM", SOCK_RDM);
4639 #endif
4640 #endif
4642 #ifdef SO_DEBUG
4643 PyModule_AddIntConstant(m, "SO_DEBUG", SO_DEBUG);
4644 #endif
4645 #ifdef SO_ACCEPTCONN
4646 PyModule_AddIntConstant(m, "SO_ACCEPTCONN", SO_ACCEPTCONN);
4647 #endif
4648 #ifdef SO_REUSEADDR
4649 PyModule_AddIntConstant(m, "SO_REUSEADDR", SO_REUSEADDR);
4650 #endif
4651 #ifdef SO_EXCLUSIVEADDRUSE
4652 PyModule_AddIntConstant(m, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE);
4653 #endif
4655 #ifdef SO_KEEPALIVE
4656 PyModule_AddIntConstant(m, "SO_KEEPALIVE", SO_KEEPALIVE);
4657 #endif
4658 #ifdef SO_DONTROUTE
4659 PyModule_AddIntConstant(m, "SO_DONTROUTE", SO_DONTROUTE);
4660 #endif
4661 #ifdef SO_BROADCAST
4662 PyModule_AddIntConstant(m, "SO_BROADCAST", SO_BROADCAST);
4663 #endif
4664 #ifdef SO_USELOOPBACK
4665 PyModule_AddIntConstant(m, "SO_USELOOPBACK", SO_USELOOPBACK);
4666 #endif
4667 #ifdef SO_LINGER
4668 PyModule_AddIntConstant(m, "SO_LINGER", SO_LINGER);
4669 #endif
4670 #ifdef SO_OOBINLINE
4671 PyModule_AddIntConstant(m, "SO_OOBINLINE", SO_OOBINLINE);
4672 #endif
4673 #ifdef SO_REUSEPORT
4674 PyModule_AddIntConstant(m, "SO_REUSEPORT", SO_REUSEPORT);
4675 #endif
4676 #ifdef SO_SNDBUF
4677 PyModule_AddIntConstant(m, "SO_SNDBUF", SO_SNDBUF);
4678 #endif
4679 #ifdef SO_RCVBUF
4680 PyModule_AddIntConstant(m, "SO_RCVBUF", SO_RCVBUF);
4681 #endif
4682 #ifdef SO_SNDLOWAT
4683 PyModule_AddIntConstant(m, "SO_SNDLOWAT", SO_SNDLOWAT);
4684 #endif
4685 #ifdef SO_RCVLOWAT
4686 PyModule_AddIntConstant(m, "SO_RCVLOWAT", SO_RCVLOWAT);
4687 #endif
4688 #ifdef SO_SNDTIMEO
4689 PyModule_AddIntConstant(m, "SO_SNDTIMEO", SO_SNDTIMEO);
4690 #endif
4691 #ifdef SO_RCVTIMEO
4692 PyModule_AddIntConstant(m, "SO_RCVTIMEO", SO_RCVTIMEO);
4693 #endif
4694 #ifdef SO_ERROR
4695 PyModule_AddIntConstant(m, "SO_ERROR", SO_ERROR);
4696 #endif
4697 #ifdef SO_TYPE
4698 PyModule_AddIntConstant(m, "SO_TYPE", SO_TYPE);
4699 #endif
4701 /* Maximum number of connections for "listen" */
4702 #ifdef SOMAXCONN
4703 PyModule_AddIntConstant(m, "SOMAXCONN", SOMAXCONN);
4704 #else
4705 PyModule_AddIntConstant(m, "SOMAXCONN", 5); /* Common value */
4706 #endif
4708 /* Flags for send, recv */
4709 #ifdef MSG_OOB
4710 PyModule_AddIntConstant(m, "MSG_OOB", MSG_OOB);
4711 #endif
4712 #ifdef MSG_PEEK
4713 PyModule_AddIntConstant(m, "MSG_PEEK", MSG_PEEK);
4714 #endif
4715 #ifdef MSG_DONTROUTE
4716 PyModule_AddIntConstant(m, "MSG_DONTROUTE", MSG_DONTROUTE);
4717 #endif
4718 #ifdef MSG_DONTWAIT
4719 PyModule_AddIntConstant(m, "MSG_DONTWAIT", MSG_DONTWAIT);
4720 #endif
4721 #ifdef MSG_EOR
4722 PyModule_AddIntConstant(m, "MSG_EOR", MSG_EOR);
4723 #endif
4724 #ifdef MSG_TRUNC
4725 PyModule_AddIntConstant(m, "MSG_TRUNC", MSG_TRUNC);
4726 #endif
4727 #ifdef MSG_CTRUNC
4728 PyModule_AddIntConstant(m, "MSG_CTRUNC", MSG_CTRUNC);
4729 #endif
4730 #ifdef MSG_WAITALL
4731 PyModule_AddIntConstant(m, "MSG_WAITALL", MSG_WAITALL);
4732 #endif
4733 #ifdef MSG_BTAG
4734 PyModule_AddIntConstant(m, "MSG_BTAG", MSG_BTAG);
4735 #endif
4736 #ifdef MSG_ETAG
4737 PyModule_AddIntConstant(m, "MSG_ETAG", MSG_ETAG);
4738 #endif
4740 /* Protocol level and numbers, usable for [gs]etsockopt */
4741 #ifdef SOL_SOCKET
4742 PyModule_AddIntConstant(m, "SOL_SOCKET", SOL_SOCKET);
4743 #endif
4744 #ifdef SOL_IP
4745 PyModule_AddIntConstant(m, "SOL_IP", SOL_IP);
4746 #else
4747 PyModule_AddIntConstant(m, "SOL_IP", 0);
4748 #endif
4749 #ifdef SOL_IPX
4750 PyModule_AddIntConstant(m, "SOL_IPX", SOL_IPX);
4751 #endif
4752 #ifdef SOL_AX25
4753 PyModule_AddIntConstant(m, "SOL_AX25", SOL_AX25);
4754 #endif
4755 #ifdef SOL_ATALK
4756 PyModule_AddIntConstant(m, "SOL_ATALK", SOL_ATALK);
4757 #endif
4758 #ifdef SOL_NETROM
4759 PyModule_AddIntConstant(m, "SOL_NETROM", SOL_NETROM);
4760 #endif
4761 #ifdef SOL_ROSE
4762 PyModule_AddIntConstant(m, "SOL_ROSE", SOL_ROSE);
4763 #endif
4764 #ifdef SOL_TCP
4765 PyModule_AddIntConstant(m, "SOL_TCP", SOL_TCP);
4766 #else
4767 PyModule_AddIntConstant(m, "SOL_TCP", 6);
4768 #endif
4769 #ifdef SOL_UDP
4770 PyModule_AddIntConstant(m, "SOL_UDP", SOL_UDP);
4771 #else
4772 PyModule_AddIntConstant(m, "SOL_UDP", 17);
4773 #endif
4774 #ifdef IPPROTO_IP
4775 PyModule_AddIntConstant(m, "IPPROTO_IP", IPPROTO_IP);
4776 #else
4777 PyModule_AddIntConstant(m, "IPPROTO_IP", 0);
4778 #endif
4779 #ifdef IPPROTO_HOPOPTS
4780 PyModule_AddIntConstant(m, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS);
4781 #endif
4782 #ifdef IPPROTO_ICMP
4783 PyModule_AddIntConstant(m, "IPPROTO_ICMP", IPPROTO_ICMP);
4784 #else
4785 PyModule_AddIntConstant(m, "IPPROTO_ICMP", 1);
4786 #endif
4787 #ifdef IPPROTO_IGMP
4788 PyModule_AddIntConstant(m, "IPPROTO_IGMP", IPPROTO_IGMP);
4789 #endif
4790 #ifdef IPPROTO_GGP
4791 PyModule_AddIntConstant(m, "IPPROTO_GGP", IPPROTO_GGP);
4792 #endif
4793 #ifdef IPPROTO_IPV4
4794 PyModule_AddIntConstant(m, "IPPROTO_IPV4", IPPROTO_IPV4);
4795 #endif
4796 #ifdef IPPROTO_IPV6
4797 PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
4798 #endif
4799 #ifdef IPPROTO_IPIP
4800 PyModule_AddIntConstant(m, "IPPROTO_IPIP", IPPROTO_IPIP);
4801 #endif
4802 #ifdef IPPROTO_TCP
4803 PyModule_AddIntConstant(m, "IPPROTO_TCP", IPPROTO_TCP);
4804 #else
4805 PyModule_AddIntConstant(m, "IPPROTO_TCP", 6);
4806 #endif
4807 #ifdef IPPROTO_EGP
4808 PyModule_AddIntConstant(m, "IPPROTO_EGP", IPPROTO_EGP);
4809 #endif
4810 #ifdef IPPROTO_PUP
4811 PyModule_AddIntConstant(m, "IPPROTO_PUP", IPPROTO_PUP);
4812 #endif
4813 #ifdef IPPROTO_UDP
4814 PyModule_AddIntConstant(m, "IPPROTO_UDP", IPPROTO_UDP);
4815 #else
4816 PyModule_AddIntConstant(m, "IPPROTO_UDP", 17);
4817 #endif
4818 #ifdef IPPROTO_IDP
4819 PyModule_AddIntConstant(m, "IPPROTO_IDP", IPPROTO_IDP);
4820 #endif
4821 #ifdef IPPROTO_HELLO
4822 PyModule_AddIntConstant(m, "IPPROTO_HELLO", IPPROTO_HELLO);
4823 #endif
4824 #ifdef IPPROTO_ND
4825 PyModule_AddIntConstant(m, "IPPROTO_ND", IPPROTO_ND);
4826 #endif
4827 #ifdef IPPROTO_TP
4828 PyModule_AddIntConstant(m, "IPPROTO_TP", IPPROTO_TP);
4829 #endif
4830 #ifdef IPPROTO_IPV6
4831 PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
4832 #endif
4833 #ifdef IPPROTO_ROUTING
4834 PyModule_AddIntConstant(m, "IPPROTO_ROUTING", IPPROTO_ROUTING);
4835 #endif
4836 #ifdef IPPROTO_FRAGMENT
4837 PyModule_AddIntConstant(m, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT);
4838 #endif
4839 #ifdef IPPROTO_RSVP
4840 PyModule_AddIntConstant(m, "IPPROTO_RSVP", IPPROTO_RSVP);
4841 #endif
4842 #ifdef IPPROTO_GRE
4843 PyModule_AddIntConstant(m, "IPPROTO_GRE", IPPROTO_GRE);
4844 #endif
4845 #ifdef IPPROTO_ESP
4846 PyModule_AddIntConstant(m, "IPPROTO_ESP", IPPROTO_ESP);
4847 #endif
4848 #ifdef IPPROTO_AH
4849 PyModule_AddIntConstant(m, "IPPROTO_AH", IPPROTO_AH);
4850 #endif
4851 #ifdef IPPROTO_MOBILE
4852 PyModule_AddIntConstant(m, "IPPROTO_MOBILE", IPPROTO_MOBILE);
4853 #endif
4854 #ifdef IPPROTO_ICMPV6
4855 PyModule_AddIntConstant(m, "IPPROTO_ICMPV6", IPPROTO_ICMPV6);
4856 #endif
4857 #ifdef IPPROTO_NONE
4858 PyModule_AddIntConstant(m, "IPPROTO_NONE", IPPROTO_NONE);
4859 #endif
4860 #ifdef IPPROTO_DSTOPTS
4861 PyModule_AddIntConstant(m, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS);
4862 #endif
4863 #ifdef IPPROTO_XTP
4864 PyModule_AddIntConstant(m, "IPPROTO_XTP", IPPROTO_XTP);
4865 #endif
4866 #ifdef IPPROTO_EON
4867 PyModule_AddIntConstant(m, "IPPROTO_EON", IPPROTO_EON);
4868 #endif
4869 #ifdef IPPROTO_PIM
4870 PyModule_AddIntConstant(m, "IPPROTO_PIM", IPPROTO_PIM);
4871 #endif
4872 #ifdef IPPROTO_IPCOMP
4873 PyModule_AddIntConstant(m, "IPPROTO_IPCOMP", IPPROTO_IPCOMP);
4874 #endif
4875 #ifdef IPPROTO_VRRP
4876 PyModule_AddIntConstant(m, "IPPROTO_VRRP", IPPROTO_VRRP);
4877 #endif
4878 #ifdef IPPROTO_BIP
4879 PyModule_AddIntConstant(m, "IPPROTO_BIP", IPPROTO_BIP);
4880 #endif
4881 /**/
4882 #ifdef IPPROTO_RAW
4883 PyModule_AddIntConstant(m, "IPPROTO_RAW", IPPROTO_RAW);
4884 #else
4885 PyModule_AddIntConstant(m, "IPPROTO_RAW", 255);
4886 #endif
4887 #ifdef IPPROTO_MAX
4888 PyModule_AddIntConstant(m, "IPPROTO_MAX", IPPROTO_MAX);
4889 #endif
4891 /* Some port configuration */
4892 #ifdef IPPORT_RESERVED
4893 PyModule_AddIntConstant(m, "IPPORT_RESERVED", IPPORT_RESERVED);
4894 #else
4895 PyModule_AddIntConstant(m, "IPPORT_RESERVED", 1024);
4896 #endif
4897 #ifdef IPPORT_USERRESERVED
4898 PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", IPPORT_USERRESERVED);
4899 #else
4900 PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", 5000);
4901 #endif
4903 /* Some reserved IP v.4 addresses */
4904 #ifdef INADDR_ANY
4905 PyModule_AddIntConstant(m, "INADDR_ANY", INADDR_ANY);
4906 #else
4907 PyModule_AddIntConstant(m, "INADDR_ANY", 0x00000000);
4908 #endif
4909 #ifdef INADDR_BROADCAST
4910 PyModule_AddIntConstant(m, "INADDR_BROADCAST", INADDR_BROADCAST);
4911 #else
4912 PyModule_AddIntConstant(m, "INADDR_BROADCAST", 0xffffffff);
4913 #endif
4914 #ifdef INADDR_LOOPBACK
4915 PyModule_AddIntConstant(m, "INADDR_LOOPBACK", INADDR_LOOPBACK);
4916 #else
4917 PyModule_AddIntConstant(m, "INADDR_LOOPBACK", 0x7F000001);
4918 #endif
4919 #ifdef INADDR_UNSPEC_GROUP
4920 PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
4921 #else
4922 PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", 0xe0000000);
4923 #endif
4924 #ifdef INADDR_ALLHOSTS_GROUP
4925 PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP",
4926 INADDR_ALLHOSTS_GROUP);
4927 #else
4928 PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
4929 #endif
4930 #ifdef INADDR_MAX_LOCAL_GROUP
4931 PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP",
4932 INADDR_MAX_LOCAL_GROUP);
4933 #else
4934 PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
4935 #endif
4936 #ifdef INADDR_NONE
4937 PyModule_AddIntConstant(m, "INADDR_NONE", INADDR_NONE);
4938 #else
4939 PyModule_AddIntConstant(m, "INADDR_NONE", 0xffffffff);
4940 #endif
4942 /* IPv4 [gs]etsockopt options */
4943 #ifdef IP_OPTIONS
4944 PyModule_AddIntConstant(m, "IP_OPTIONS", IP_OPTIONS);
4945 #endif
4946 #ifdef IP_HDRINCL
4947 PyModule_AddIntConstant(m, "IP_HDRINCL", IP_HDRINCL);
4948 #endif
4949 #ifdef IP_TOS
4950 PyModule_AddIntConstant(m, "IP_TOS", IP_TOS);
4951 #endif
4952 #ifdef IP_TTL
4953 PyModule_AddIntConstant(m, "IP_TTL", IP_TTL);
4954 #endif
4955 #ifdef IP_RECVOPTS
4956 PyModule_AddIntConstant(m, "IP_RECVOPTS", IP_RECVOPTS);
4957 #endif
4958 #ifdef IP_RECVRETOPTS
4959 PyModule_AddIntConstant(m, "IP_RECVRETOPTS", IP_RECVRETOPTS);
4960 #endif
4961 #ifdef IP_RECVDSTADDR
4962 PyModule_AddIntConstant(m, "IP_RECVDSTADDR", IP_RECVDSTADDR);
4963 #endif
4964 #ifdef IP_RETOPTS
4965 PyModule_AddIntConstant(m, "IP_RETOPTS", IP_RETOPTS);
4966 #endif
4967 #ifdef IP_MULTICAST_IF
4968 PyModule_AddIntConstant(m, "IP_MULTICAST_IF", IP_MULTICAST_IF);
4969 #endif
4970 #ifdef IP_MULTICAST_TTL
4971 PyModule_AddIntConstant(m, "IP_MULTICAST_TTL", IP_MULTICAST_TTL);
4972 #endif
4973 #ifdef IP_MULTICAST_LOOP
4974 PyModule_AddIntConstant(m, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
4975 #endif
4976 #ifdef IP_ADD_MEMBERSHIP
4977 PyModule_AddIntConstant(m, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
4978 #endif
4979 #ifdef IP_DROP_MEMBERSHIP
4980 PyModule_AddIntConstant(m, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
4981 #endif
4982 #ifdef IP_DEFAULT_MULTICAST_TTL
4983 PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_TTL",
4984 IP_DEFAULT_MULTICAST_TTL);
4985 #endif
4986 #ifdef IP_DEFAULT_MULTICAST_LOOP
4987 PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_LOOP",
4988 IP_DEFAULT_MULTICAST_LOOP);
4989 #endif
4990 #ifdef IP_MAX_MEMBERSHIPS
4991 PyModule_AddIntConstant(m, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS);
4992 #endif
4994 /* IPv6 [gs]etsockopt options, defined in RFC2553 */
4995 #ifdef IPV6_JOIN_GROUP
4996 PyModule_AddIntConstant(m, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP);
4997 #endif
4998 #ifdef IPV6_LEAVE_GROUP
4999 PyModule_AddIntConstant(m, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP);
5000 #endif
5001 #ifdef IPV6_MULTICAST_HOPS
5002 PyModule_AddIntConstant(m, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS);
5003 #endif
5004 #ifdef IPV6_MULTICAST_IF
5005 PyModule_AddIntConstant(m, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF);
5006 #endif
5007 #ifdef IPV6_MULTICAST_LOOP
5008 PyModule_AddIntConstant(m, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP);
5009 #endif
5010 #ifdef IPV6_UNICAST_HOPS
5011 PyModule_AddIntConstant(m, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS);
5012 #endif
5013 /* Additional IPV6 socket options, defined in RFC 3493 */
5014 #ifdef IPV6_V6ONLY
5015 PyModule_AddIntConstant(m, "IPV6_V6ONLY", IPV6_V6ONLY);
5016 #endif
5017 /* Advanced IPV6 socket options, from RFC 3542 */
5018 #ifdef IPV6_CHECKSUM
5019 PyModule_AddIntConstant(m, "IPV6_CHECKSUM", IPV6_CHECKSUM);
5020 #endif
5021 #ifdef IPV6_DONTFRAG
5022 PyModule_AddIntConstant(m, "IPV6_DONTFRAG", IPV6_DONTFRAG);
5023 #endif
5024 #ifdef IPV6_DSTOPTS
5025 PyModule_AddIntConstant(m, "IPV6_DSTOPTS", IPV6_DSTOPTS);
5026 #endif
5027 #ifdef IPV6_HOPLIMIT
5028 PyModule_AddIntConstant(m, "IPV6_HOPLIMIT", IPV6_HOPLIMIT);
5029 #endif
5030 #ifdef IPV6_HOPOPTS
5031 PyModule_AddIntConstant(m, "IPV6_HOPOPTS", IPV6_HOPOPTS);
5032 #endif
5033 #ifdef IPV6_NEXTHOP
5034 PyModule_AddIntConstant(m, "IPV6_NEXTHOP", IPV6_NEXTHOP);
5035 #endif
5036 #ifdef IPV6_PATHMTU
5037 PyModule_AddIntConstant(m, "IPV6_PATHMTU", IPV6_PATHMTU);
5038 #endif
5039 #ifdef IPV6_PKTINFO
5040 PyModule_AddIntConstant(m, "IPV6_PKTINFO", IPV6_PKTINFO);
5041 #endif
5042 #ifdef IPV6_RECVDSTOPTS
5043 PyModule_AddIntConstant(m, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS);
5044 #endif
5045 #ifdef IPV6_RECVHOPLIMIT
5046 PyModule_AddIntConstant(m, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT);
5047 #endif
5048 #ifdef IPV6_RECVHOPOPTS
5049 PyModule_AddIntConstant(m, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS);
5050 #endif
5051 #ifdef IPV6_RECVPKTINFO
5052 PyModule_AddIntConstant(m, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO);
5053 #endif
5054 #ifdef IPV6_RECVRTHDR
5055 PyModule_AddIntConstant(m, "IPV6_RECVRTHDR", IPV6_RECVRTHDR);
5056 #endif
5057 #ifdef IPV6_RECVTCLASS
5058 PyModule_AddIntConstant(m, "IPV6_RECVTCLASS", IPV6_RECVTCLASS);
5059 #endif
5060 #ifdef IPV6_RTHDR
5061 PyModule_AddIntConstant(m, "IPV6_RTHDR", IPV6_RTHDR);
5062 #endif
5063 #ifdef IPV6_RTHDRDSTOPTS
5064 PyModule_AddIntConstant(m, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS);
5065 #endif
5066 #ifdef IPV6_RTHDR_TYPE_0
5067 PyModule_AddIntConstant(m, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0);
5068 #endif
5069 #ifdef IPV6_RECVPATHMTU
5070 PyModule_AddIntConstant(m, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU);
5071 #endif
5072 #ifdef IPV6_TCLASS
5073 PyModule_AddIntConstant(m, "IPV6_TCLASS", IPV6_TCLASS);
5074 #endif
5075 #ifdef IPV6_USE_MIN_MTU
5076 PyModule_AddIntConstant(m, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU);
5077 #endif
5079 /* TCP options */
5080 #ifdef TCP_NODELAY
5081 PyModule_AddIntConstant(m, "TCP_NODELAY", TCP_NODELAY);
5082 #endif
5083 #ifdef TCP_MAXSEG
5084 PyModule_AddIntConstant(m, "TCP_MAXSEG", TCP_MAXSEG);
5085 #endif
5086 #ifdef TCP_CORK
5087 PyModule_AddIntConstant(m, "TCP_CORK", TCP_CORK);
5088 #endif
5089 #ifdef TCP_KEEPIDLE
5090 PyModule_AddIntConstant(m, "TCP_KEEPIDLE", TCP_KEEPIDLE);
5091 #endif
5092 #ifdef TCP_KEEPINTVL
5093 PyModule_AddIntConstant(m, "TCP_KEEPINTVL", TCP_KEEPINTVL);
5094 #endif
5095 #ifdef TCP_KEEPCNT
5096 PyModule_AddIntConstant(m, "TCP_KEEPCNT", TCP_KEEPCNT);
5097 #endif
5098 #ifdef TCP_SYNCNT
5099 PyModule_AddIntConstant(m, "TCP_SYNCNT", TCP_SYNCNT);
5100 #endif
5101 #ifdef TCP_LINGER2
5102 PyModule_AddIntConstant(m, "TCP_LINGER2", TCP_LINGER2);
5103 #endif
5104 #ifdef TCP_DEFER_ACCEPT
5105 PyModule_AddIntConstant(m, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT);
5106 #endif
5107 #ifdef TCP_WINDOW_CLAMP
5108 PyModule_AddIntConstant(m, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP);
5109 #endif
5110 #ifdef TCP_INFO
5111 PyModule_AddIntConstant(m, "TCP_INFO", TCP_INFO);
5112 #endif
5113 #ifdef TCP_QUICKACK
5114 PyModule_AddIntConstant(m, "TCP_QUICKACK", TCP_QUICKACK);
5115 #endif
5118 /* IPX options */
5119 #ifdef IPX_TYPE
5120 PyModule_AddIntConstant(m, "IPX_TYPE", IPX_TYPE);
5121 #endif
5123 /* get{addr,name}info parameters */
5124 #ifdef EAI_ADDRFAMILY
5125 PyModule_AddIntConstant(m, "EAI_ADDRFAMILY", EAI_ADDRFAMILY);
5126 #endif
5127 #ifdef EAI_AGAIN
5128 PyModule_AddIntConstant(m, "EAI_AGAIN", EAI_AGAIN);
5129 #endif
5130 #ifdef EAI_BADFLAGS
5131 PyModule_AddIntConstant(m, "EAI_BADFLAGS", EAI_BADFLAGS);
5132 #endif
5133 #ifdef EAI_FAIL
5134 PyModule_AddIntConstant(m, "EAI_FAIL", EAI_FAIL);
5135 #endif
5136 #ifdef EAI_FAMILY
5137 PyModule_AddIntConstant(m, "EAI_FAMILY", EAI_FAMILY);
5138 #endif
5139 #ifdef EAI_MEMORY
5140 PyModule_AddIntConstant(m, "EAI_MEMORY", EAI_MEMORY);
5141 #endif
5142 #ifdef EAI_NODATA
5143 PyModule_AddIntConstant(m, "EAI_NODATA", EAI_NODATA);
5144 #endif
5145 #ifdef EAI_NONAME
5146 PyModule_AddIntConstant(m, "EAI_NONAME", EAI_NONAME);
5147 #endif
5148 #ifdef EAI_OVERFLOW
5149 PyModule_AddIntConstant(m, "EAI_OVERFLOW", EAI_OVERFLOW);
5150 #endif
5151 #ifdef EAI_SERVICE
5152 PyModule_AddIntConstant(m, "EAI_SERVICE", EAI_SERVICE);
5153 #endif
5154 #ifdef EAI_SOCKTYPE
5155 PyModule_AddIntConstant(m, "EAI_SOCKTYPE", EAI_SOCKTYPE);
5156 #endif
5157 #ifdef EAI_SYSTEM
5158 PyModule_AddIntConstant(m, "EAI_SYSTEM", EAI_SYSTEM);
5159 #endif
5160 #ifdef EAI_BADHINTS
5161 PyModule_AddIntConstant(m, "EAI_BADHINTS", EAI_BADHINTS);
5162 #endif
5163 #ifdef EAI_PROTOCOL
5164 PyModule_AddIntConstant(m, "EAI_PROTOCOL", EAI_PROTOCOL);
5165 #endif
5166 #ifdef EAI_MAX
5167 PyModule_AddIntConstant(m, "EAI_MAX", EAI_MAX);
5168 #endif
5169 #ifdef AI_PASSIVE
5170 PyModule_AddIntConstant(m, "AI_PASSIVE", AI_PASSIVE);
5171 #endif
5172 #ifdef AI_CANONNAME
5173 PyModule_AddIntConstant(m, "AI_CANONNAME", AI_CANONNAME);
5174 #endif
5175 #ifdef AI_NUMERICHOST
5176 PyModule_AddIntConstant(m, "AI_NUMERICHOST", AI_NUMERICHOST);
5177 #endif
5178 #ifdef AI_NUMERICSERV
5179 PyModule_AddIntConstant(m, "AI_NUMERICSERV", AI_NUMERICSERV);
5180 #endif
5181 #ifdef AI_MASK
5182 PyModule_AddIntConstant(m, "AI_MASK", AI_MASK);
5183 #endif
5184 #ifdef AI_ALL
5185 PyModule_AddIntConstant(m, "AI_ALL", AI_ALL);
5186 #endif
5187 #ifdef AI_V4MAPPED_CFG
5188 PyModule_AddIntConstant(m, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG);
5189 #endif
5190 #ifdef AI_ADDRCONFIG
5191 PyModule_AddIntConstant(m, "AI_ADDRCONFIG", AI_ADDRCONFIG);
5192 #endif
5193 #ifdef AI_V4MAPPED
5194 PyModule_AddIntConstant(m, "AI_V4MAPPED", AI_V4MAPPED);
5195 #endif
5196 #ifdef AI_DEFAULT
5197 PyModule_AddIntConstant(m, "AI_DEFAULT", AI_DEFAULT);
5198 #endif
5199 #ifdef NI_MAXHOST
5200 PyModule_AddIntConstant(m, "NI_MAXHOST", NI_MAXHOST);
5201 #endif
5202 #ifdef NI_MAXSERV
5203 PyModule_AddIntConstant(m, "NI_MAXSERV", NI_MAXSERV);
5204 #endif
5205 #ifdef NI_NOFQDN
5206 PyModule_AddIntConstant(m, "NI_NOFQDN", NI_NOFQDN);
5207 #endif
5208 #ifdef NI_NUMERICHOST
5209 PyModule_AddIntConstant(m, "NI_NUMERICHOST", NI_NUMERICHOST);
5210 #endif
5211 #ifdef NI_NAMEREQD
5212 PyModule_AddIntConstant(m, "NI_NAMEREQD", NI_NAMEREQD);
5213 #endif
5214 #ifdef NI_NUMERICSERV
5215 PyModule_AddIntConstant(m, "NI_NUMERICSERV", NI_NUMERICSERV);
5216 #endif
5217 #ifdef NI_DGRAM
5218 PyModule_AddIntConstant(m, "NI_DGRAM", NI_DGRAM);
5219 #endif
5221 /* shutdown() parameters */
5222 #ifdef SHUT_RD
5223 PyModule_AddIntConstant(m, "SHUT_RD", SHUT_RD);
5224 #elif defined(SD_RECEIVE)
5225 PyModule_AddIntConstant(m, "SHUT_RD", SD_RECEIVE);
5226 #else
5227 PyModule_AddIntConstant(m, "SHUT_RD", 0);
5228 #endif
5229 #ifdef SHUT_WR
5230 PyModule_AddIntConstant(m, "SHUT_WR", SHUT_WR);
5231 #elif defined(SD_SEND)
5232 PyModule_AddIntConstant(m, "SHUT_WR", SD_SEND);
5233 #else
5234 PyModule_AddIntConstant(m, "SHUT_WR", 1);
5235 #endif
5236 #ifdef SHUT_RDWR
5237 PyModule_AddIntConstant(m, "SHUT_RDWR", SHUT_RDWR);
5238 #elif defined(SD_BOTH)
5239 PyModule_AddIntConstant(m, "SHUT_RDWR", SD_BOTH);
5240 #else
5241 PyModule_AddIntConstant(m, "SHUT_RDWR", 2);
5242 #endif
5244 #ifdef SIO_RCVALL
5246 PyObject *tmp;
5247 tmp = PyLong_FromUnsignedLong(SIO_RCVALL);
5248 if (tmp == NULL)
5249 return;
5250 PyModule_AddObject(m, "SIO_RCVALL", tmp);
5252 PyModule_AddIntConstant(m, "RCVALL_OFF", RCVALL_OFF);
5253 PyModule_AddIntConstant(m, "RCVALL_ON", RCVALL_ON);
5254 PyModule_AddIntConstant(m, "RCVALL_SOCKETLEVELONLY", RCVALL_SOCKETLEVELONLY);
5255 #ifdef RCVALL_IPLEVEL
5256 PyModule_AddIntConstant(m, "RCVALL_IPLEVEL", RCVALL_IPLEVEL);
5257 #endif
5258 #ifdef RCVALL_MAX
5259 PyModule_AddIntConstant(m, "RCVALL_MAX", RCVALL_MAX);
5260 #endif
5261 #endif /* _MSTCPIP_ */
5263 /* Initialize gethostbyname lock */
5264 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
5265 netdb_lock = PyThread_allocate_lock();
5266 #endif
5270 #ifndef HAVE_INET_PTON
5271 #if !defined(NTDDI_VERSION) || (NTDDI_VERSION < NTDDI_LONGHORN)
5273 /* Simplistic emulation code for inet_pton that only works for IPv4 */
5274 /* These are not exposed because they do not set errno properly */
5277 inet_pton(int af, const char *src, void *dst)
5279 if (af == AF_INET) {
5280 long packed_addr;
5281 packed_addr = inet_addr(src);
5282 if (packed_addr == INADDR_NONE)
5283 return 0;
5284 memcpy(dst, &packed_addr, 4);
5285 return 1;
5287 /* Should set errno to EAFNOSUPPORT */
5288 return -1;
5291 const char *
5292 inet_ntop(int af, const void *src, char *dst, socklen_t size)
5294 if (af == AF_INET) {
5295 struct in_addr packed_addr;
5296 if (size < 16)
5297 /* Should set errno to ENOSPC. */
5298 return NULL;
5299 memcpy(&packed_addr, src, sizeof(packed_addr));
5300 return strncpy(dst, inet_ntoa(packed_addr), size);
5302 /* Should set errno to EAFNOSUPPORT */
5303 return NULL;
5306 #endif
5307 #endif