Patch #1635058 by Mark Roberts: ensure that htonl and friends never accept or
[python.git] / Modules / socketmodule.c
blob82461d4602e171d6b52058be45ead1eef7381538
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 and AF_NETLINK are supported under Linux.
11 - No read/write operations (use sendall/recv or makefile instead).
12 - Additional restrictions apply on some non-Unix platforms (compensated
13 for by socket.py).
15 Module interface:
17 - socket.error: exception raised for socket specific errors
18 - socket.gaierror: exception raised for getaddrinfo/getnameinfo errors,
19 a subclass of socket.error
20 - socket.herror: exception raised for gethostby* errors,
21 a subclass of socket.error
22 - socket.fromfd(fd, family, type[, proto]) --> new socket object (created
23 from an existing file descriptor)
24 - socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')
25 - socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])
26 - socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com')
27 - socket.getprotobyname(protocolname) --> protocol number
28 - socket.getservbyname(servicename[, protocolname]) --> port number
29 - socket.getservbyport(portnumber[, protocolname]) --> service name
30 - socket.socket([family[, type [, proto]]]) --> new socket object
31 - socket.socketpair([family[, type [, proto]]]) --> (socket, socket)
32 - socket.ntohs(16 bit value) --> new int object
33 - socket.ntohl(32 bit value) --> new int object
34 - socket.htons(16 bit value) --> new int object
35 - socket.htonl(32 bit value) --> new int object
36 - socket.getaddrinfo(host, port [, family, socktype, proto, flags])
37 --> List of (family, socktype, proto, canonname, sockaddr)
38 - socket.getnameinfo(sockaddr, flags) --> (host, port)
39 - socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
40 - socket.has_ipv6: boolean value indicating if IPv6 is supported
41 - socket.inet_aton(IP address) -> 32-bit packed IP representation
42 - socket.inet_ntoa(packed IP) -> IP address string
43 - socket.getdefaulttimeout() -> None | float
44 - socket.setdefaulttimeout(None | float)
45 - an Internet socket address is a pair (hostname, port)
46 where hostname can be anything recognized by gethostbyname()
47 (including the dd.dd.dd.dd notation) and port is in host byte order
48 - where a hostname is returned, the dd.dd.dd.dd notation is used
49 - a UNIX domain socket address is a string specifying the pathname
50 - an AF_PACKET socket address is a tuple containing a string
51 specifying the ethernet interface and an integer specifying
52 the Ethernet protocol number to be received. For example:
53 ("eth0",0x1234). Optional 3rd,4th,5th elements in the tuple
54 specify packet-type and ha-type/addr.
56 Local naming conventions:
58 - names starting with sock_ are socket object methods
59 - names starting with socket_ are module-level functions
60 - names starting with PySocket are exported through socketmodule.h
64 #ifdef __APPLE__
66 * inet_aton is not available on OSX 10.3, yet we want to use a binary
67 * that was build on 10.4 or later to work on that release, weak linking
68 * comes to the rescue.
70 # pragma weak inet_aton
71 #endif
73 #include "Python.h"
74 #include "structmember.h"
76 #undef MAX
77 #define MAX(x, y) ((x) < (y) ? (y) : (x))
79 /* Socket object documentation */
80 PyDoc_STRVAR(sock_doc,
81 "socket([family[, type[, proto]]]) -> socket object\n\
82 \n\
83 Open a socket of the given type. The family argument specifies the\n\
84 address family; it defaults to AF_INET. The type argument specifies\n\
85 whether this is a stream (SOCK_STREAM, this is the default)\n\
86 or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0,\n\
87 specifying the default protocol. Keyword arguments are accepted.\n\
88 \n\
89 A socket object represents one endpoint of a network connection.\n\
90 \n\
91 Methods of socket objects (keyword arguments not allowed):\n\
92 \n\
93 accept() -- accept a connection, returning new socket and client address\n\
94 bind(addr) -- bind the socket to a local address\n\
95 close() -- close the socket\n\
96 connect(addr) -- connect the socket to a remote address\n\
97 connect_ex(addr) -- connect, return an error code instead of an exception\n\
98 dup() -- return a new socket object identical to the current one [*]\n\
99 fileno() -- return underlying file descriptor\n\
100 getpeername() -- return remote address [*]\n\
101 getsockname() -- return local address\n\
102 getsockopt(level, optname[, buflen]) -- get socket options\n\
103 gettimeout() -- return timeout or None\n\
104 listen(n) -- start listening for incoming connections\n\
105 makefile([mode, [bufsize]]) -- return a file object for the socket [*]\n\
106 recv(buflen[, flags]) -- receive data\n\
107 recv_into(buffer[, nbytes[, flags]]) -- receive data (into a buffer)\n\
108 recvfrom(buflen[, flags]) -- receive data and sender\'s address\n\
109 recvfrom_into(buffer[, nbytes, [, flags])\n\
110 -- receive data and sender\'s address (into a buffer)\n\
111 sendall(data[, flags]) -- send all data\n\
112 send(data[, flags]) -- send data, may not send all of it\n\
113 sendto(data[, flags], addr) -- send data to a given address\n\
114 setblocking(0 | 1) -- set or clear the blocking I/O flag\n\
115 setsockopt(level, optname, value) -- set socket options\n\
116 settimeout(None | float) -- set or clear the timeout\n\
117 shutdown(how) -- shut down traffic in one or both directions\n\
119 [*] not available on all platforms!");
121 /* XXX This is a terrible mess of platform-dependent preprocessor hacks.
122 I hope some day someone can clean this up please... */
124 /* Hacks for gethostbyname_r(). On some non-Linux platforms, the configure
125 script doesn't get this right, so we hardcode some platform checks below.
126 On the other hand, not all Linux versions agree, so there the settings
127 computed by the configure script are needed! */
129 #ifndef linux
130 # undef HAVE_GETHOSTBYNAME_R_3_ARG
131 # undef HAVE_GETHOSTBYNAME_R_5_ARG
132 # undef HAVE_GETHOSTBYNAME_R_6_ARG
133 #endif
135 #ifndef WITH_THREAD
136 # undef HAVE_GETHOSTBYNAME_R
137 #endif
139 #ifdef HAVE_GETHOSTBYNAME_R
140 # if defined(_AIX) || defined(__osf__)
141 # define HAVE_GETHOSTBYNAME_R_3_ARG
142 # elif defined(__sun) || defined(__sgi)
143 # define HAVE_GETHOSTBYNAME_R_5_ARG
144 # elif defined(linux)
145 /* Rely on the configure script */
146 # else
147 # undef HAVE_GETHOSTBYNAME_R
148 # endif
149 #endif
151 #if !defined(HAVE_GETHOSTBYNAME_R) && defined(WITH_THREAD) && \
152 !defined(MS_WINDOWS)
153 # define USE_GETHOSTBYNAME_LOCK
154 #endif
156 /* To use __FreeBSD_version */
157 #ifdef HAVE_SYS_PARAM_H
158 #include <sys/param.h>
159 #endif
160 /* On systems on which getaddrinfo() is believed to not be thread-safe,
161 (this includes the getaddrinfo emulation) protect access with a lock. */
162 #if defined(WITH_THREAD) && (defined(__APPLE__) || \
163 (defined(__FreeBSD__) && __FreeBSD_version+0 < 503000) || \
164 defined(__OpenBSD__) || defined(__NetBSD__) || \
165 defined(__VMS) || !defined(HAVE_GETADDRINFO))
166 #define USE_GETADDRINFO_LOCK
167 #endif
169 #ifdef USE_GETADDRINFO_LOCK
170 #define ACQUIRE_GETADDRINFO_LOCK PyThread_acquire_lock(netdb_lock, 1);
171 #define RELEASE_GETADDRINFO_LOCK PyThread_release_lock(netdb_lock);
172 #else
173 #define ACQUIRE_GETADDRINFO_LOCK
174 #define RELEASE_GETADDRINFO_LOCK
175 #endif
177 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
178 # include "pythread.h"
179 #endif
181 #if defined(PYCC_VACPP)
182 # include <types.h>
183 # include <io.h>
184 # include <sys/ioctl.h>
185 # include <utils.h>
186 # include <ctype.h>
187 #endif
189 #if defined(__VMS)
190 # include <ioctl.h>
191 #endif
193 #if defined(PYOS_OS2)
194 # define INCL_DOS
195 # define INCL_DOSERRORS
196 # define INCL_NOPMAPI
197 # include <os2.h>
198 #endif
200 #if defined(__sgi) && _COMPILER_VERSION>700 && !_SGIAPI
201 /* make sure that the reentrant (gethostbyaddr_r etc)
202 functions are declared correctly if compiling with
203 MIPSPro 7.x in ANSI C mode (default) */
205 /* XXX Using _SGIAPI is the wrong thing,
206 but I don't know what the right thing is. */
207 #undef _SGIAPI /* to avoid warning */
208 #define _SGIAPI 1
210 #undef _XOPEN_SOURCE
211 #include <sys/socket.h>
212 #include <sys/types.h>
213 #include <netinet/in.h>
214 #ifdef _SS_ALIGNSIZE
215 #define HAVE_GETADDRINFO 1
216 #define HAVE_GETNAMEINFO 1
217 #endif
219 #define HAVE_INET_PTON
220 #include <netdb.h>
221 #endif
223 /* Irix 6.5 fails to define this variable at all. This is needed
224 for both GCC and SGI's compiler. I'd say that the SGI headers
225 are just busted. Same thing for Solaris. */
226 #if (defined(__sgi) || defined(sun)) && !defined(INET_ADDRSTRLEN)
227 #define INET_ADDRSTRLEN 16
228 #endif
230 /* Generic includes */
231 #ifdef HAVE_SYS_TYPES_H
232 #include <sys/types.h>
233 #endif
235 /* Generic socket object definitions and includes */
236 #define PySocket_BUILDING_SOCKET
237 #include "socketmodule.h"
239 /* Addressing includes */
241 #ifndef MS_WINDOWS
243 /* Non-MS WINDOWS includes */
244 # include <netdb.h>
246 /* Headers needed for inet_ntoa() and inet_addr() */
247 # ifdef __BEOS__
248 # include <net/netdb.h>
249 # elif defined(PYOS_OS2) && defined(PYCC_VACPP)
250 # include <netdb.h>
251 typedef size_t socklen_t;
252 # else
253 # include <arpa/inet.h>
254 # endif
256 # ifndef RISCOS
257 # include <fcntl.h>
258 # else
259 # include <sys/ioctl.h>
260 # include <socklib.h>
261 # define NO_DUP
262 int h_errno; /* not used */
263 # define INET_ADDRSTRLEN 16
264 # endif
266 #else
268 /* MS_WINDOWS includes */
269 # ifdef HAVE_FCNTL_H
270 # include <fcntl.h>
271 # endif
273 #endif
275 #include <stddef.h>
277 #ifndef offsetof
278 # define offsetof(type, member) ((size_t)(&((type *)0)->member))
279 #endif
281 #ifndef O_NONBLOCK
282 # define O_NONBLOCK O_NDELAY
283 #endif
285 /* include Python's addrinfo.h unless it causes trouble */
286 #if defined(__sgi) && _COMPILER_VERSION>700 && defined(_SS_ALIGNSIZE)
287 /* Do not include addinfo.h on some newer IRIX versions.
288 * _SS_ALIGNSIZE is defined in sys/socket.h by 6.5.21,
289 * for example, but not by 6.5.10.
291 #elif defined(_MSC_VER) && _MSC_VER>1201
292 /* Do not include addrinfo.h for MSVC7 or greater. 'addrinfo' and
293 * EAI_* constants are defined in (the already included) ws2tcpip.h.
295 #else
296 # include "addrinfo.h"
297 #endif
299 #ifndef HAVE_INET_PTON
300 int inet_pton(int af, const char *src, void *dst);
301 const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
302 #endif
304 #ifdef __APPLE__
305 /* On OS X, getaddrinfo returns no error indication of lookup
306 failure, so we must use the emulation instead of the libinfo
307 implementation. Unfortunately, performing an autoconf test
308 for this bug would require DNS access for the machine performing
309 the configuration, which is not acceptable. Therefore, we
310 determine the bug just by checking for __APPLE__. If this bug
311 gets ever fixed, perhaps checking for sys/version.h would be
312 appropriate, which is 10/0 on the system with the bug. */
313 #ifndef HAVE_GETNAMEINFO
314 /* This bug seems to be fixed in Jaguar. Ths easiest way I could
315 Find to check for Jaguar is that it has getnameinfo(), which
316 older releases don't have */
317 #undef HAVE_GETADDRINFO
318 #endif
320 #ifdef HAVE_INET_ATON
321 #define USE_INET_ATON_WEAKLINK
322 #endif
324 #endif
326 /* I know this is a bad practice, but it is the easiest... */
327 #if !defined(HAVE_GETADDRINFO)
328 /* avoid clashes with the C library definition of the symbol. */
329 #define getaddrinfo fake_getaddrinfo
330 #define gai_strerror fake_gai_strerror
331 #define freeaddrinfo fake_freeaddrinfo
332 #include "getaddrinfo.c"
333 #endif
334 #if !defined(HAVE_GETNAMEINFO)
335 #define getnameinfo fake_getnameinfo
336 #include "getnameinfo.c"
337 #endif
339 #if defined(MS_WINDOWS) || defined(__BEOS__)
340 /* BeOS suffers from the same socket dichotomy as Win32... - [cjh] */
341 /* seem to be a few differences in the API */
342 #define SOCKETCLOSE closesocket
343 #define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */
344 #endif
346 #ifdef MS_WIN32
347 #define EAFNOSUPPORT WSAEAFNOSUPPORT
348 #define snprintf _snprintf
349 #endif
351 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
352 #define SOCKETCLOSE soclose
353 #define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
354 #endif
356 #ifndef SOCKETCLOSE
357 #define SOCKETCLOSE close
358 #endif
360 #if defined(HAVE_BLUETOOTH_H) || defined(HAVE_BLUETOOTH_BLUETOOTH_H)
361 #define USE_BLUETOOTH 1
362 #if defined(__FreeBSD__)
363 #define BTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP
364 #define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM
365 #define sockaddr_l2 sockaddr_l2cap
366 #define sockaddr_rc sockaddr_rfcomm
367 #define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb)
368 #define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)
369 #elif defined(__NetBSD__)
370 #define sockaddr_l2 sockaddr_bt
371 #define sockaddr_rc sockaddr_bt
372 #define sockaddr_sco sockaddr_bt
373 #define _BT_L2_MEMB(sa, memb) ((sa)->bt_##memb)
374 #define _BT_RC_MEMB(sa, memb) ((sa)->bt_##memb)
375 #define _BT_SCO_MEMB(sa, memb) ((sa)->bt_##memb)
376 #else
377 #define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb)
378 #define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb)
379 #define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)
380 #endif
381 #endif
383 #ifdef __VMS
384 /* TCP/IP Services for VMS uses a maximum send/recv buffer length */
385 #define SEGMENT_SIZE (32 * 1024 -1)
386 #endif
388 #define SAS2SA(x) ((struct sockaddr *)(x))
391 * Constants for getnameinfo()
393 #if !defined(NI_MAXHOST)
394 #define NI_MAXHOST 1025
395 #endif
396 #if !defined(NI_MAXSERV)
397 #define NI_MAXSERV 32
398 #endif
400 /* XXX There's a problem here: *static* functions are not supposed to have
401 a Py prefix (or use CapitalizedWords). Later... */
403 /* Global variable holding the exception type for errors detected
404 by this module (but not argument type or memory errors, etc.). */
405 static PyObject *socket_error;
406 static PyObject *socket_herror;
407 static PyObject *socket_gaierror;
408 static PyObject *socket_timeout;
410 #ifdef RISCOS
411 /* Global variable which is !=0 if Python is running in a RISC OS taskwindow */
412 static int taskwindow;
413 #endif
415 /* A forward reference to the socket type object.
416 The sock_type variable contains pointers to various functions,
417 some of which call new_sockobject(), which uses sock_type, so
418 there has to be a circular reference. */
419 static PyTypeObject sock_type;
421 #if defined(HAVE_POLL_H)
422 #include <poll.h>
423 #elif defined(HAVE_SYS_POLL_H)
424 #include <sys/poll.h>
425 #endif
427 #ifdef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
428 /* Platform can select file descriptors beyond FD_SETSIZE */
429 #define IS_SELECTABLE(s) 1
430 #elif defined(HAVE_POLL)
431 /* Instead of select(), we'll use poll() since poll() works on any fd. */
432 #define IS_SELECTABLE(s) 1
433 /* Can we call select() with this socket without a buffer overrun? */
434 #else
435 /* POSIX says selecting file descriptors beyond FD_SETSIZE
436 has undefined behaviour. If there's no timeout left, we don't have to
437 call select, so it's a safe, little white lie. */
438 #define IS_SELECTABLE(s) ((s)->sock_fd < FD_SETSIZE || s->sock_timeout <= 0.0)
439 #endif
441 static PyObject*
442 select_error(void)
444 PyErr_SetString(socket_error, "unable to select on socket");
445 return NULL;
448 /* Convenience function to raise an error according to errno
449 and return a NULL pointer from a function. */
451 static PyObject *
452 set_error(void)
454 #ifdef MS_WINDOWS
455 int err_no = WSAGetLastError();
456 static struct {
457 int no;
458 const char *msg;
459 } *msgp, msgs[] = {
460 {WSAEINTR, "Interrupted system call"},
461 {WSAEBADF, "Bad file descriptor"},
462 {WSAEACCES, "Permission denied"},
463 {WSAEFAULT, "Bad address"},
464 {WSAEINVAL, "Invalid argument"},
465 {WSAEMFILE, "Too many open files"},
466 {WSAEWOULDBLOCK,
467 "The socket operation could not complete "
468 "without blocking"},
469 {WSAEINPROGRESS, "Operation now in progress"},
470 {WSAEALREADY, "Operation already in progress"},
471 {WSAENOTSOCK, "Socket operation on non-socket"},
472 {WSAEDESTADDRREQ, "Destination address required"},
473 {WSAEMSGSIZE, "Message too long"},
474 {WSAEPROTOTYPE, "Protocol wrong type for socket"},
475 {WSAENOPROTOOPT, "Protocol not available"},
476 {WSAEPROTONOSUPPORT, "Protocol not supported"},
477 {WSAESOCKTNOSUPPORT, "Socket type not supported"},
478 {WSAEOPNOTSUPP, "Operation not supported"},
479 {WSAEPFNOSUPPORT, "Protocol family not supported"},
480 {WSAEAFNOSUPPORT, "Address family not supported"},
481 {WSAEADDRINUSE, "Address already in use"},
482 {WSAEADDRNOTAVAIL, "Can't assign requested address"},
483 {WSAENETDOWN, "Network is down"},
484 {WSAENETUNREACH, "Network is unreachable"},
485 {WSAENETRESET, "Network dropped connection on reset"},
486 {WSAECONNABORTED, "Software caused connection abort"},
487 {WSAECONNRESET, "Connection reset by peer"},
488 {WSAENOBUFS, "No buffer space available"},
489 {WSAEISCONN, "Socket is already connected"},
490 {WSAENOTCONN, "Socket is not connected"},
491 {WSAESHUTDOWN, "Can't send after socket shutdown"},
492 {WSAETOOMANYREFS, "Too many references: can't splice"},
493 {WSAETIMEDOUT, "Operation timed out"},
494 {WSAECONNREFUSED, "Connection refused"},
495 {WSAELOOP, "Too many levels of symbolic links"},
496 {WSAENAMETOOLONG, "File name too long"},
497 {WSAEHOSTDOWN, "Host is down"},
498 {WSAEHOSTUNREACH, "No route to host"},
499 {WSAENOTEMPTY, "Directory not empty"},
500 {WSAEPROCLIM, "Too many processes"},
501 {WSAEUSERS, "Too many users"},
502 {WSAEDQUOT, "Disc quota exceeded"},
503 {WSAESTALE, "Stale NFS file handle"},
504 {WSAEREMOTE, "Too many levels of remote in path"},
505 {WSASYSNOTREADY, "Network subsystem is unvailable"},
506 {WSAVERNOTSUPPORTED, "WinSock version is not supported"},
507 {WSANOTINITIALISED,
508 "Successful WSAStartup() not yet performed"},
509 {WSAEDISCON, "Graceful shutdown in progress"},
510 /* Resolver errors */
511 {WSAHOST_NOT_FOUND, "No such host is known"},
512 {WSATRY_AGAIN, "Host not found, or server failed"},
513 {WSANO_RECOVERY, "Unexpected server error encountered"},
514 {WSANO_DATA, "Valid name without requested data"},
515 {WSANO_ADDRESS, "No address, look for MX record"},
516 {0, NULL}
518 if (err_no) {
519 PyObject *v;
520 const char *msg = "winsock error";
522 for (msgp = msgs; msgp->msg; msgp++) {
523 if (err_no == msgp->no) {
524 msg = msgp->msg;
525 break;
529 v = Py_BuildValue("(is)", err_no, msg);
530 if (v != NULL) {
531 PyErr_SetObject(socket_error, v);
532 Py_DECREF(v);
534 return NULL;
536 else
537 #endif
539 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
540 if (sock_errno() != NO_ERROR) {
541 APIRET rc;
542 ULONG msglen;
543 char outbuf[100];
544 int myerrorcode = sock_errno();
546 /* Retrieve socket-related error message from MPTN.MSG file */
547 rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf),
548 myerrorcode - SOCBASEERR + 26,
549 "mptn.msg",
550 &msglen);
551 if (rc == NO_ERROR) {
552 PyObject *v;
554 /* OS/2 doesn't guarantee a terminator */
555 outbuf[msglen] = '\0';
556 if (strlen(outbuf) > 0) {
557 /* If non-empty msg, trim CRLF */
558 char *lastc = &outbuf[ strlen(outbuf)-1 ];
559 while (lastc > outbuf &&
560 isspace(Py_CHARMASK(*lastc))) {
561 /* Trim trailing whitespace (CRLF) */
562 *lastc-- = '\0';
565 v = Py_BuildValue("(is)", myerrorcode, outbuf);
566 if (v != NULL) {
567 PyErr_SetObject(socket_error, v);
568 Py_DECREF(v);
570 return NULL;
573 #endif
575 #if defined(RISCOS)
576 if (_inet_error.errnum != NULL) {
577 PyObject *v;
578 v = Py_BuildValue("(is)", errno, _inet_err());
579 if (v != NULL) {
580 PyErr_SetObject(socket_error, v);
581 Py_DECREF(v);
583 return NULL;
585 #endif
587 return PyErr_SetFromErrno(socket_error);
591 static PyObject *
592 set_herror(int h_error)
594 PyObject *v;
596 #ifdef HAVE_HSTRERROR
597 v = Py_BuildValue("(is)", h_error, (char *)hstrerror(h_error));
598 #else
599 v = Py_BuildValue("(is)", h_error, "host not found");
600 #endif
601 if (v != NULL) {
602 PyErr_SetObject(socket_herror, v);
603 Py_DECREF(v);
606 return NULL;
610 static PyObject *
611 set_gaierror(int error)
613 PyObject *v;
615 #ifdef EAI_SYSTEM
616 /* EAI_SYSTEM is not available on Windows XP. */
617 if (error == EAI_SYSTEM)
618 return set_error();
619 #endif
621 #ifdef HAVE_GAI_STRERROR
622 v = Py_BuildValue("(is)", error, gai_strerror(error));
623 #else
624 v = Py_BuildValue("(is)", error, "getaddrinfo failed");
625 #endif
626 if (v != NULL) {
627 PyErr_SetObject(socket_gaierror, v);
628 Py_DECREF(v);
631 return NULL;
634 #ifdef __VMS
635 /* Function to send in segments */
636 static int
637 sendsegmented(int sock_fd, char *buf, int len, int flags)
639 int n = 0;
640 int remaining = len;
642 while (remaining > 0) {
643 unsigned int segment;
645 segment = (remaining >= SEGMENT_SIZE ? SEGMENT_SIZE : remaining);
646 n = send(sock_fd, buf, segment, flags);
647 if (n < 0) {
648 return n;
650 remaining -= segment;
651 buf += segment;
652 } /* end while */
654 return len;
656 #endif
658 /* Function to perform the setting of socket blocking mode
659 internally. block = (1 | 0). */
660 static int
661 internal_setblocking(PySocketSockObject *s, int block)
663 #ifndef RISCOS
664 #ifndef MS_WINDOWS
665 int delay_flag;
666 #endif
667 #endif
669 Py_BEGIN_ALLOW_THREADS
670 #ifdef __BEOS__
671 block = !block;
672 setsockopt(s->sock_fd, SOL_SOCKET, SO_NONBLOCK,
673 (void *)(&block), sizeof(int));
674 #else
675 #ifndef RISCOS
676 #ifndef MS_WINDOWS
677 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
678 block = !block;
679 ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block));
680 #elif defined(__VMS)
681 block = !block;
682 ioctl(s->sock_fd, FIONBIO, (unsigned int *)&block);
683 #else /* !PYOS_OS2 && !__VMS */
684 delay_flag = fcntl(s->sock_fd, F_GETFL, 0);
685 if (block)
686 delay_flag &= (~O_NONBLOCK);
687 else
688 delay_flag |= O_NONBLOCK;
689 fcntl(s->sock_fd, F_SETFL, delay_flag);
690 #endif /* !PYOS_OS2 */
691 #else /* MS_WINDOWS */
692 block = !block;
693 ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
694 #endif /* MS_WINDOWS */
695 #else /* RISCOS */
696 block = !block;
697 socketioctl(s->sock_fd, FIONBIO, (u_long*)&block);
698 #endif /* RISCOS */
699 #endif /* __BEOS__ */
700 Py_END_ALLOW_THREADS
702 /* Since these don't return anything */
703 return 1;
706 /* Do a select()/poll() on the socket, if necessary (sock_timeout > 0).
707 The argument writing indicates the direction.
708 This does not raise an exception; we'll let our caller do that
709 after they've reacquired the interpreter lock.
710 Returns 1 on timeout, -1 on error, 0 otherwise. */
711 static int
712 internal_select(PySocketSockObject *s, int writing)
714 int n;
716 /* Nothing to do unless we're in timeout mode (not non-blocking) */
717 if (s->sock_timeout <= 0.0)
718 return 0;
720 /* Guard against closed socket */
721 if (s->sock_fd < 0)
722 return 0;
724 /* Prefer poll, if available, since you can poll() any fd
725 * which can't be done with select(). */
726 #ifdef HAVE_POLL
728 struct pollfd pollfd;
729 int timeout;
731 pollfd.fd = s->sock_fd;
732 pollfd.events = writing ? POLLOUT : POLLIN;
734 /* s->sock_timeout is in seconds, timeout in ms */
735 timeout = (int)(s->sock_timeout * 1000 + 0.5);
736 n = poll(&pollfd, 1, timeout);
738 #else
740 /* Construct the arguments to select */
741 fd_set fds;
742 struct timeval tv;
743 tv.tv_sec = (int)s->sock_timeout;
744 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
745 FD_ZERO(&fds);
746 FD_SET(s->sock_fd, &fds);
748 /* See if the socket is ready */
749 if (writing)
750 n = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
751 else
752 n = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
754 #endif
756 if (n < 0)
757 return -1;
758 if (n == 0)
759 return 1;
760 return 0;
763 /* Initialize a new socket object. */
765 static double defaulttimeout = -1.0; /* Default timeout for new sockets */
767 PyMODINIT_FUNC
768 init_sockobject(PySocketSockObject *s,
769 SOCKET_T fd, int family, int type, int proto)
771 #ifdef RISCOS
772 int block = 1;
773 #endif
774 s->sock_fd = fd;
775 s->sock_family = family;
776 s->sock_type = type;
777 s->sock_proto = proto;
778 s->sock_timeout = defaulttimeout;
780 s->errorhandler = &set_error;
782 if (defaulttimeout >= 0.0)
783 internal_setblocking(s, 0);
785 #ifdef RISCOS
786 if (taskwindow)
787 socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
788 #endif
792 /* Create a new socket object.
793 This just creates the object and initializes it.
794 If the creation fails, return NULL and set an exception (implicit
795 in NEWOBJ()). */
797 static PySocketSockObject *
798 new_sockobject(SOCKET_T fd, int family, int type, int proto)
800 PySocketSockObject *s;
801 s = (PySocketSockObject *)
802 PyType_GenericNew(&sock_type, NULL, NULL);
803 if (s != NULL)
804 init_sockobject(s, fd, family, type, proto);
805 return s;
809 /* Lock to allow python interpreter to continue, but only allow one
810 thread to be in gethostbyname or getaddrinfo */
811 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
812 PyThread_type_lock netdb_lock;
813 #endif
816 /* Convert a string specifying a host name or one of a few symbolic
817 names to a numeric IP address. This usually calls gethostbyname()
818 to do the work; the names "" and "<broadcast>" are special.
819 Return the length (IPv4 should be 4 bytes), or negative if
820 an error occurred; then an exception is raised. */
822 static int
823 setipaddr(char *name, struct sockaddr *addr_ret, size_t addr_ret_size, int af)
825 struct addrinfo hints, *res;
826 int error;
827 int d1, d2, d3, d4;
828 char ch;
830 memset((void *) addr_ret, '\0', sizeof(*addr_ret));
831 if (name[0] == '\0') {
832 int siz;
833 memset(&hints, 0, sizeof(hints));
834 hints.ai_family = af;
835 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
836 hints.ai_flags = AI_PASSIVE;
837 Py_BEGIN_ALLOW_THREADS
838 ACQUIRE_GETADDRINFO_LOCK
839 error = getaddrinfo(NULL, "0", &hints, &res);
840 Py_END_ALLOW_THREADS
841 /* We assume that those thread-unsafe getaddrinfo() versions
842 *are* safe regarding their return value, ie. that a
843 subsequent call to getaddrinfo() does not destroy the
844 outcome of the first call. */
845 RELEASE_GETADDRINFO_LOCK
846 if (error) {
847 set_gaierror(error);
848 return -1;
850 switch (res->ai_family) {
851 case AF_INET:
852 siz = 4;
853 break;
854 #ifdef ENABLE_IPV6
855 case AF_INET6:
856 siz = 16;
857 break;
858 #endif
859 default:
860 freeaddrinfo(res);
861 PyErr_SetString(socket_error,
862 "unsupported address family");
863 return -1;
865 if (res->ai_next) {
866 freeaddrinfo(res);
867 PyErr_SetString(socket_error,
868 "wildcard resolved to multiple address");
869 return -1;
871 if (res->ai_addrlen < addr_ret_size)
872 addr_ret_size = res->ai_addrlen;
873 memcpy(addr_ret, res->ai_addr, addr_ret_size);
874 freeaddrinfo(res);
875 return siz;
877 if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
878 struct sockaddr_in *sin;
879 if (af != AF_INET && af != AF_UNSPEC) {
880 PyErr_SetString(socket_error,
881 "address family mismatched");
882 return -1;
884 sin = (struct sockaddr_in *)addr_ret;
885 memset((void *) sin, '\0', sizeof(*sin));
886 sin->sin_family = AF_INET;
887 #ifdef HAVE_SOCKADDR_SA_LEN
888 sin->sin_len = sizeof(*sin);
889 #endif
890 sin->sin_addr.s_addr = INADDR_BROADCAST;
891 return sizeof(sin->sin_addr);
893 if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 &&
894 0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 &&
895 0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) {
896 struct sockaddr_in *sin;
897 sin = (struct sockaddr_in *)addr_ret;
898 sin->sin_addr.s_addr = htonl(
899 ((long) d1 << 24) | ((long) d2 << 16) |
900 ((long) d3 << 8) | ((long) d4 << 0));
901 sin->sin_family = AF_INET;
902 #ifdef HAVE_SOCKADDR_SA_LEN
903 sin->sin_len = sizeof(*sin);
904 #endif
905 return 4;
907 memset(&hints, 0, sizeof(hints));
908 hints.ai_family = af;
909 Py_BEGIN_ALLOW_THREADS
910 ACQUIRE_GETADDRINFO_LOCK
911 error = getaddrinfo(name, NULL, &hints, &res);
912 #if defined(__digital__) && defined(__unix__)
913 if (error == EAI_NONAME && af == AF_UNSPEC) {
914 /* On Tru64 V5.1, numeric-to-addr conversion fails
915 if no address family is given. Assume IPv4 for now.*/
916 hints.ai_family = AF_INET;
917 error = getaddrinfo(name, NULL, &hints, &res);
919 #endif
920 Py_END_ALLOW_THREADS
921 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
922 if (error) {
923 set_gaierror(error);
924 return -1;
926 if (res->ai_addrlen < addr_ret_size)
927 addr_ret_size = res->ai_addrlen;
928 memcpy((char *) addr_ret, res->ai_addr, addr_ret_size);
929 freeaddrinfo(res);
930 switch (addr_ret->sa_family) {
931 case AF_INET:
932 return 4;
933 #ifdef ENABLE_IPV6
934 case AF_INET6:
935 return 16;
936 #endif
937 default:
938 PyErr_SetString(socket_error, "unknown address family");
939 return -1;
944 /* Create a string object representing an IP address.
945 This is always a string of the form 'dd.dd.dd.dd' (with variable
946 size numbers). */
948 static PyObject *
949 makeipaddr(struct sockaddr *addr, int addrlen)
951 char buf[NI_MAXHOST];
952 int error;
954 error = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0,
955 NI_NUMERICHOST);
956 if (error) {
957 set_gaierror(error);
958 return NULL;
960 return PyString_FromString(buf);
964 #ifdef USE_BLUETOOTH
965 /* Convert a string representation of a Bluetooth address into a numeric
966 address. Returns the length (6), or raises an exception and returns -1 if
967 an error occurred. */
969 static int
970 setbdaddr(char *name, bdaddr_t *bdaddr)
972 unsigned int b0, b1, b2, b3, b4, b5;
973 char ch;
974 int n;
976 n = sscanf(name, "%X:%X:%X:%X:%X:%X%c",
977 &b5, &b4, &b3, &b2, &b1, &b0, &ch);
978 if (n == 6 && (b0 | b1 | b2 | b3 | b4 | b5) < 256) {
979 bdaddr->b[0] = b0;
980 bdaddr->b[1] = b1;
981 bdaddr->b[2] = b2;
982 bdaddr->b[3] = b3;
983 bdaddr->b[4] = b4;
984 bdaddr->b[5] = b5;
985 return 6;
986 } else {
987 PyErr_SetString(socket_error, "bad bluetooth address");
988 return -1;
992 /* Create a string representation of the Bluetooth address. This is always a
993 string of the form 'XX:XX:XX:XX:XX:XX' where XX is a two digit hexadecimal
994 value (zero padded if necessary). */
996 static PyObject *
997 makebdaddr(bdaddr_t *bdaddr)
999 char buf[(6 * 2) + 5 + 1];
1001 sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
1002 bdaddr->b[5], bdaddr->b[4], bdaddr->b[3],
1003 bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]);
1004 return PyString_FromString(buf);
1006 #endif
1009 /* Create an object representing the given socket address,
1010 suitable for passing it back to bind(), connect() etc.
1011 The family field of the sockaddr structure is inspected
1012 to determine what kind of address it really is. */
1014 /*ARGSUSED*/
1015 static PyObject *
1016 makesockaddr(int sockfd, struct sockaddr *addr, int addrlen, int proto)
1018 if (addrlen == 0) {
1019 /* No address -- may be recvfrom() from known socket */
1020 Py_INCREF(Py_None);
1021 return Py_None;
1024 #ifdef __BEOS__
1025 /* XXX: BeOS version of accept() doesn't set family correctly */
1026 addr->sa_family = AF_INET;
1027 #endif
1029 switch (addr->sa_family) {
1031 case AF_INET:
1033 struct sockaddr_in *a;
1034 PyObject *addrobj = makeipaddr(addr, sizeof(*a));
1035 PyObject *ret = NULL;
1036 if (addrobj) {
1037 a = (struct sockaddr_in *)addr;
1038 ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
1039 Py_DECREF(addrobj);
1041 return ret;
1044 #if defined(AF_UNIX)
1045 case AF_UNIX:
1047 struct sockaddr_un *a = (struct sockaddr_un *) addr;
1048 #ifdef linux
1049 if (a->sun_path[0] == 0) { /* Linux abstract namespace */
1050 addrlen -= (sizeof(*a) - sizeof(a->sun_path));
1051 return PyString_FromStringAndSize(a->sun_path,
1052 addrlen);
1054 else
1055 #endif /* linux */
1057 /* regular NULL-terminated string */
1058 return PyString_FromString(a->sun_path);
1061 #endif /* AF_UNIX */
1063 #if defined(AF_NETLINK)
1064 case AF_NETLINK:
1066 struct sockaddr_nl *a = (struct sockaddr_nl *) addr;
1067 return Py_BuildValue("II", a->nl_pid, a->nl_groups);
1069 #endif /* AF_NETLINK */
1071 #ifdef ENABLE_IPV6
1072 case AF_INET6:
1074 struct sockaddr_in6 *a;
1075 PyObject *addrobj = makeipaddr(addr, sizeof(*a));
1076 PyObject *ret = NULL;
1077 if (addrobj) {
1078 a = (struct sockaddr_in6 *)addr;
1079 ret = Py_BuildValue("Oiii",
1080 addrobj,
1081 ntohs(a->sin6_port),
1082 a->sin6_flowinfo,
1083 a->sin6_scope_id);
1084 Py_DECREF(addrobj);
1086 return ret;
1088 #endif
1090 #ifdef USE_BLUETOOTH
1091 case AF_BLUETOOTH:
1092 switch (proto) {
1094 case BTPROTO_L2CAP:
1096 struct sockaddr_l2 *a = (struct sockaddr_l2 *) addr;
1097 PyObject *addrobj = makebdaddr(&_BT_L2_MEMB(a, bdaddr));
1098 PyObject *ret = NULL;
1099 if (addrobj) {
1100 ret = Py_BuildValue("Oi",
1101 addrobj,
1102 _BT_L2_MEMB(a, psm));
1103 Py_DECREF(addrobj);
1105 return ret;
1108 case BTPROTO_RFCOMM:
1110 struct sockaddr_rc *a = (struct sockaddr_rc *) addr;
1111 PyObject *addrobj = makebdaddr(&_BT_RC_MEMB(a, bdaddr));
1112 PyObject *ret = NULL;
1113 if (addrobj) {
1114 ret = Py_BuildValue("Oi",
1115 addrobj,
1116 _BT_RC_MEMB(a, channel));
1117 Py_DECREF(addrobj);
1119 return ret;
1122 #if !defined(__FreeBSD__)
1123 case BTPROTO_SCO:
1125 struct sockaddr_sco *a = (struct sockaddr_sco *) addr;
1126 return makebdaddr(&_BT_SCO_MEMB(a, bdaddr));
1128 #endif
1131 #endif
1133 #ifdef HAVE_NETPACKET_PACKET_H
1134 case AF_PACKET:
1136 struct sockaddr_ll *a = (struct sockaddr_ll *)addr;
1137 char *ifname = "";
1138 struct ifreq ifr;
1139 /* need to look up interface name give index */
1140 if (a->sll_ifindex) {
1141 ifr.ifr_ifindex = a->sll_ifindex;
1142 if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0)
1143 ifname = ifr.ifr_name;
1145 return Py_BuildValue("shbhs#",
1146 ifname,
1147 ntohs(a->sll_protocol),
1148 a->sll_pkttype,
1149 a->sll_hatype,
1150 a->sll_addr,
1151 a->sll_halen);
1153 #endif
1155 /* More cases here... */
1157 default:
1158 /* If we don't know the address family, don't raise an
1159 exception -- return it as a tuple. */
1160 return Py_BuildValue("is#",
1161 addr->sa_family,
1162 addr->sa_data,
1163 sizeof(addr->sa_data));
1169 /* Parse a socket address argument according to the socket object's
1170 address family. Return 1 if the address was in the proper format,
1171 0 of not. The address is returned through addr_ret, its length
1172 through len_ret. */
1174 static int
1175 getsockaddrarg(PySocketSockObject *s, PyObject *args,
1176 struct sockaddr *addr_ret, int *len_ret)
1178 switch (s->sock_family) {
1180 #if defined(AF_UNIX)
1181 case AF_UNIX:
1183 struct sockaddr_un* addr;
1184 char *path;
1185 int len;
1186 if (!PyArg_Parse(args, "t#", &path, &len))
1187 return 0;
1189 addr = (struct sockaddr_un*)addr_ret;
1190 #ifdef linux
1191 if (len > 0 && path[0] == 0) {
1192 /* Linux abstract namespace extension */
1193 if (len > sizeof addr->sun_path) {
1194 PyErr_SetString(socket_error,
1195 "AF_UNIX path too long");
1196 return 0;
1199 else
1200 #endif /* linux */
1202 /* regular NULL-terminated string */
1203 if (len >= sizeof addr->sun_path) {
1204 PyErr_SetString(socket_error,
1205 "AF_UNIX path too long");
1206 return 0;
1208 addr->sun_path[len] = 0;
1210 addr->sun_family = s->sock_family;
1211 memcpy(addr->sun_path, path, len);
1212 #if defined(PYOS_OS2)
1213 *len_ret = sizeof(*addr);
1214 #else
1215 *len_ret = len + sizeof(*addr) - sizeof(addr->sun_path);
1216 #endif
1217 return 1;
1219 #endif /* AF_UNIX */
1221 #if defined(AF_NETLINK)
1222 case AF_NETLINK:
1224 struct sockaddr_nl* addr;
1225 int pid, groups;
1226 addr = (struct sockaddr_nl *)addr_ret;
1227 if (!PyTuple_Check(args)) {
1228 PyErr_Format(
1229 PyExc_TypeError,
1230 "getsockaddrarg: "
1231 "AF_NETLINK address must be tuple, not %.500s",
1232 args->ob_type->tp_name);
1233 return 0;
1235 if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &pid, &groups))
1236 return 0;
1237 addr->nl_family = AF_NETLINK;
1238 addr->nl_pid = pid;
1239 addr->nl_groups = groups;
1240 *len_ret = sizeof(*addr);
1241 return 1;
1243 #endif
1245 case AF_INET:
1247 struct sockaddr_in* addr;
1248 char *host;
1249 int port, result;
1250 if (!PyTuple_Check(args)) {
1251 PyErr_Format(
1252 PyExc_TypeError,
1253 "getsockaddrarg: "
1254 "AF_INET address must be tuple, not %.500s",
1255 args->ob_type->tp_name);
1256 return 0;
1258 if (!PyArg_ParseTuple(args, "eti:getsockaddrarg",
1259 "idna", &host, &port))
1260 return 0;
1261 addr=(struct sockaddr_in*)addr_ret;
1262 result = setipaddr(host, (struct sockaddr *)addr,
1263 sizeof(*addr), AF_INET);
1264 PyMem_Free(host);
1265 if (result < 0)
1266 return 0;
1267 addr->sin_family = AF_INET;
1268 addr->sin_port = htons((short)port);
1269 *len_ret = sizeof *addr;
1270 return 1;
1273 #ifdef ENABLE_IPV6
1274 case AF_INET6:
1276 struct sockaddr_in6* addr;
1277 char *host;
1278 int port, flowinfo, scope_id, result;
1279 flowinfo = scope_id = 0;
1280 if (!PyTuple_Check(args)) {
1281 PyErr_Format(
1282 PyExc_TypeError,
1283 "getsockaddrarg: "
1284 "AF_INET6 address must be tuple, not %.500s",
1285 args->ob_type->tp_name);
1286 return 0;
1288 if (!PyArg_ParseTuple(args, "eti|ii",
1289 "idna", &host, &port, &flowinfo,
1290 &scope_id)) {
1291 return 0;
1293 addr = (struct sockaddr_in6*)addr_ret;
1294 result = setipaddr(host, (struct sockaddr *)addr,
1295 sizeof(*addr), AF_INET6);
1296 PyMem_Free(host);
1297 if (result < 0)
1298 return 0;
1299 addr->sin6_family = s->sock_family;
1300 addr->sin6_port = htons((short)port);
1301 addr->sin6_flowinfo = flowinfo;
1302 addr->sin6_scope_id = scope_id;
1303 *len_ret = sizeof *addr;
1304 return 1;
1306 #endif
1308 #ifdef USE_BLUETOOTH
1309 case AF_BLUETOOTH:
1311 switch (s->sock_proto) {
1312 case BTPROTO_L2CAP:
1314 struct sockaddr_l2 *addr;
1315 char *straddr;
1317 addr = (struct sockaddr_l2 *)addr_ret;
1318 _BT_L2_MEMB(addr, family) = AF_BLUETOOTH;
1319 if (!PyArg_ParseTuple(args, "si", &straddr,
1320 &_BT_L2_MEMB(addr, psm))) {
1321 PyErr_SetString(socket_error, "getsockaddrarg: "
1322 "wrong format");
1323 return 0;
1325 if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0)
1326 return 0;
1328 *len_ret = sizeof *addr;
1329 return 1;
1331 case BTPROTO_RFCOMM:
1333 struct sockaddr_rc *addr;
1334 char *straddr;
1336 addr = (struct sockaddr_rc *)addr_ret;
1337 _BT_RC_MEMB(addr, family) = AF_BLUETOOTH;
1338 if (!PyArg_ParseTuple(args, "si", &straddr,
1339 &_BT_RC_MEMB(addr, channel))) {
1340 PyErr_SetString(socket_error, "getsockaddrarg: "
1341 "wrong format");
1342 return 0;
1344 if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0)
1345 return 0;
1347 *len_ret = sizeof *addr;
1348 return 1;
1350 #if !defined(__FreeBSD__)
1351 case BTPROTO_SCO:
1353 struct sockaddr_sco *addr;
1354 char *straddr;
1356 addr = (struct sockaddr_sco *)addr_ret;
1357 _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH;
1358 straddr = PyString_AsString(args);
1359 if (straddr == NULL) {
1360 PyErr_SetString(socket_error, "getsockaddrarg: "
1361 "wrong format");
1362 return 0;
1364 if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0)
1365 return 0;
1367 *len_ret = sizeof *addr;
1368 return 1;
1370 #endif
1371 default:
1372 PyErr_SetString(socket_error, "getsockaddrarg: unknown Bluetooth protocol");
1373 return 0;
1376 #endif
1378 #ifdef HAVE_NETPACKET_PACKET_H
1379 case AF_PACKET:
1381 struct sockaddr_ll* addr;
1382 struct ifreq ifr;
1383 char *interfaceName;
1384 int protoNumber;
1385 int hatype = 0;
1386 int pkttype = 0;
1387 char *haddr = NULL;
1388 unsigned int halen = 0;
1390 if (!PyTuple_Check(args)) {
1391 PyErr_Format(
1392 PyExc_TypeError,
1393 "getsockaddrarg: "
1394 "AF_PACKET address must be tuple, not %.500s",
1395 args->ob_type->tp_name);
1396 return 0;
1398 if (!PyArg_ParseTuple(args, "si|iis#", &interfaceName,
1399 &protoNumber, &pkttype, &hatype,
1400 &haddr, &halen))
1401 return 0;
1402 strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name));
1403 ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
1404 if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
1405 s->errorhandler();
1406 return 0;
1408 if (halen > 8) {
1409 PyErr_SetString(PyExc_ValueError,
1410 "Hardware address must be 8 bytes or less");
1411 return 0;
1413 addr = (struct sockaddr_ll*)addr_ret;
1414 addr->sll_family = AF_PACKET;
1415 addr->sll_protocol = htons((short)protoNumber);
1416 addr->sll_ifindex = ifr.ifr_ifindex;
1417 addr->sll_pkttype = pkttype;
1418 addr->sll_hatype = hatype;
1419 if (halen != 0) {
1420 memcpy(&addr->sll_addr, haddr, halen);
1422 addr->sll_halen = halen;
1423 *len_ret = sizeof *addr;
1424 return 1;
1426 #endif
1428 /* More cases here... */
1430 default:
1431 PyErr_SetString(socket_error, "getsockaddrarg: bad family");
1432 return 0;
1438 /* Get the address length according to the socket object's address family.
1439 Return 1 if the family is known, 0 otherwise. The length is returned
1440 through len_ret. */
1442 static int
1443 getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
1445 switch (s->sock_family) {
1447 #if defined(AF_UNIX)
1448 case AF_UNIX:
1450 *len_ret = sizeof (struct sockaddr_un);
1451 return 1;
1453 #endif /* AF_UNIX */
1454 #if defined(AF_NETLINK)
1455 case AF_NETLINK:
1457 *len_ret = sizeof (struct sockaddr_nl);
1458 return 1;
1460 #endif
1462 case AF_INET:
1464 *len_ret = sizeof (struct sockaddr_in);
1465 return 1;
1468 #ifdef ENABLE_IPV6
1469 case AF_INET6:
1471 *len_ret = sizeof (struct sockaddr_in6);
1472 return 1;
1474 #endif
1476 #ifdef USE_BLUETOOTH
1477 case AF_BLUETOOTH:
1479 switch(s->sock_proto)
1482 case BTPROTO_L2CAP:
1483 *len_ret = sizeof (struct sockaddr_l2);
1484 return 1;
1485 case BTPROTO_RFCOMM:
1486 *len_ret = sizeof (struct sockaddr_rc);
1487 return 1;
1488 #if !defined(__FreeBSD__)
1489 case BTPROTO_SCO:
1490 *len_ret = sizeof (struct sockaddr_sco);
1491 return 1;
1492 #endif
1493 default:
1494 PyErr_SetString(socket_error, "getsockaddrlen: "
1495 "unknown BT protocol");
1496 return 0;
1500 #endif
1502 #ifdef HAVE_NETPACKET_PACKET_H
1503 case AF_PACKET:
1505 *len_ret = sizeof (struct sockaddr_ll);
1506 return 1;
1508 #endif
1510 /* More cases here... */
1512 default:
1513 PyErr_SetString(socket_error, "getsockaddrlen: bad family");
1514 return 0;
1520 /* s.accept() method */
1522 static PyObject *
1523 sock_accept(PySocketSockObject *s)
1525 sock_addr_t addrbuf;
1526 SOCKET_T newfd;
1527 socklen_t addrlen;
1528 PyObject *sock = NULL;
1529 PyObject *addr = NULL;
1530 PyObject *res = NULL;
1531 int timeout;
1533 if (!getsockaddrlen(s, &addrlen))
1534 return NULL;
1535 memset(&addrbuf, 0, addrlen);
1537 #ifdef MS_WINDOWS
1538 newfd = INVALID_SOCKET;
1539 #else
1540 newfd = -1;
1541 #endif
1543 if (!IS_SELECTABLE(s))
1544 return select_error();
1546 Py_BEGIN_ALLOW_THREADS
1547 timeout = internal_select(s, 0);
1548 if (!timeout)
1549 newfd = accept(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
1550 Py_END_ALLOW_THREADS
1552 if (timeout == 1) {
1553 PyErr_SetString(socket_timeout, "timed out");
1554 return NULL;
1557 #ifdef MS_WINDOWS
1558 if (newfd == INVALID_SOCKET)
1559 #else
1560 if (newfd < 0)
1561 #endif
1562 return s->errorhandler();
1564 /* Create the new object with unspecified family,
1565 to avoid calls to bind() etc. on it. */
1566 sock = (PyObject *) new_sockobject(newfd,
1567 s->sock_family,
1568 s->sock_type,
1569 s->sock_proto);
1571 if (sock == NULL) {
1572 SOCKETCLOSE(newfd);
1573 goto finally;
1575 addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
1576 addrlen, s->sock_proto);
1577 if (addr == NULL)
1578 goto finally;
1580 res = PyTuple_Pack(2, sock, addr);
1582 finally:
1583 Py_XDECREF(sock);
1584 Py_XDECREF(addr);
1585 return res;
1588 PyDoc_STRVAR(accept_doc,
1589 "accept() -> (socket object, address info)\n\
1591 Wait for an incoming connection. Return a new socket representing the\n\
1592 connection, and the address of the client. For IP sockets, the address\n\
1593 info is a pair (hostaddr, port).");
1595 /* s.setblocking(flag) method. Argument:
1596 False -- non-blocking mode; same as settimeout(0)
1597 True -- blocking mode; same as settimeout(None)
1600 static PyObject *
1601 sock_setblocking(PySocketSockObject *s, PyObject *arg)
1603 int block;
1605 block = PyInt_AsLong(arg);
1606 if (block == -1 && PyErr_Occurred())
1607 return NULL;
1609 s->sock_timeout = block ? -1.0 : 0.0;
1610 internal_setblocking(s, block);
1612 Py_INCREF(Py_None);
1613 return Py_None;
1616 PyDoc_STRVAR(setblocking_doc,
1617 "setblocking(flag)\n\
1619 Set the socket to blocking (flag is true) or non-blocking (false).\n\
1620 setblocking(True) is equivalent to settimeout(None);\n\
1621 setblocking(False) is equivalent to settimeout(0.0).");
1623 /* s.settimeout(timeout) method. Argument:
1624 None -- no timeout, blocking mode; same as setblocking(True)
1625 0.0 -- non-blocking mode; same as setblocking(False)
1626 > 0 -- timeout mode; operations time out after timeout seconds
1627 < 0 -- illegal; raises an exception
1629 static PyObject *
1630 sock_settimeout(PySocketSockObject *s, PyObject *arg)
1632 double timeout;
1634 if (arg == Py_None)
1635 timeout = -1.0;
1636 else {
1637 timeout = PyFloat_AsDouble(arg);
1638 if (timeout < 0.0) {
1639 if (!PyErr_Occurred())
1640 PyErr_SetString(PyExc_ValueError,
1641 "Timeout value out of range");
1642 return NULL;
1646 s->sock_timeout = timeout;
1647 internal_setblocking(s, timeout < 0.0);
1649 Py_INCREF(Py_None);
1650 return Py_None;
1653 PyDoc_STRVAR(settimeout_doc,
1654 "settimeout(timeout)\n\
1656 Set a timeout on socket operations. 'timeout' can be a float,\n\
1657 giving in seconds, or None. Setting a timeout of None disables\n\
1658 the timeout feature and is equivalent to setblocking(1).\n\
1659 Setting a timeout of zero is the same as setblocking(0).");
1661 /* s.gettimeout() method.
1662 Returns the timeout associated with a socket. */
1663 static PyObject *
1664 sock_gettimeout(PySocketSockObject *s)
1666 if (s->sock_timeout < 0.0) {
1667 Py_INCREF(Py_None);
1668 return Py_None;
1670 else
1671 return PyFloat_FromDouble(s->sock_timeout);
1674 PyDoc_STRVAR(gettimeout_doc,
1675 "gettimeout() -> timeout\n\
1677 Returns the timeout in floating seconds associated with socket \n\
1678 operations. A timeout of None indicates that timeouts on socket \n\
1679 operations are disabled.");
1681 #ifdef RISCOS
1682 /* s.sleeptaskw(1 | 0) method */
1684 static PyObject *
1685 sock_sleeptaskw(PySocketSockObject *s,PyObject *arg)
1687 int block;
1688 block = PyInt_AsLong(arg);
1689 if (block == -1 && PyErr_Occurred())
1690 return NULL;
1691 Py_BEGIN_ALLOW_THREADS
1692 socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
1693 Py_END_ALLOW_THREADS
1695 Py_INCREF(Py_None);
1696 return Py_None;
1698 PyDoc_STRVAR(sleeptaskw_doc,
1699 "sleeptaskw(flag)\n\
1701 Allow sleeps in taskwindows.");
1702 #endif
1705 /* s.setsockopt() method.
1706 With an integer third argument, sets an integer option.
1707 With a string third argument, sets an option from a buffer;
1708 use optional built-in module 'struct' to encode the string. */
1710 static PyObject *
1711 sock_setsockopt(PySocketSockObject *s, PyObject *args)
1713 int level;
1714 int optname;
1715 int res;
1716 char *buf;
1717 int buflen;
1718 int flag;
1720 if (PyArg_ParseTuple(args, "iii:setsockopt",
1721 &level, &optname, &flag)) {
1722 buf = (char *) &flag;
1723 buflen = sizeof flag;
1725 else {
1726 PyErr_Clear();
1727 if (!PyArg_ParseTuple(args, "iis#:setsockopt",
1728 &level, &optname, &buf, &buflen))
1729 return NULL;
1731 res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen);
1732 if (res < 0)
1733 return s->errorhandler();
1734 Py_INCREF(Py_None);
1735 return Py_None;
1738 PyDoc_STRVAR(setsockopt_doc,
1739 "setsockopt(level, option, value)\n\
1741 Set a socket option. See the Unix manual for level and option.\n\
1742 The value argument can either be an integer or a string.");
1745 /* s.getsockopt() method.
1746 With two arguments, retrieves an integer option.
1747 With a third integer argument, retrieves a string buffer of that size;
1748 use optional built-in module 'struct' to decode the string. */
1750 static PyObject *
1751 sock_getsockopt(PySocketSockObject *s, PyObject *args)
1753 int level;
1754 int optname;
1755 int res;
1756 PyObject *buf;
1757 socklen_t buflen = 0;
1759 #ifdef __BEOS__
1760 /* We have incomplete socket support. */
1761 PyErr_SetString(socket_error, "getsockopt not supported");
1762 return NULL;
1763 #else
1765 if (!PyArg_ParseTuple(args, "ii|i:getsockopt",
1766 &level, &optname, &buflen))
1767 return NULL;
1769 if (buflen == 0) {
1770 int flag = 0;
1771 socklen_t flagsize = sizeof flag;
1772 res = getsockopt(s->sock_fd, level, optname,
1773 (void *)&flag, &flagsize);
1774 if (res < 0)
1775 return s->errorhandler();
1776 return PyInt_FromLong(flag);
1778 #ifdef __VMS
1779 /* socklen_t is unsigned so no negative test is needed,
1780 test buflen == 0 is previously done */
1781 if (buflen > 1024) {
1782 #else
1783 if (buflen <= 0 || buflen > 1024) {
1784 #endif
1785 PyErr_SetString(socket_error,
1786 "getsockopt buflen out of range");
1787 return NULL;
1789 buf = PyString_FromStringAndSize((char *)NULL, buflen);
1790 if (buf == NULL)
1791 return NULL;
1792 res = getsockopt(s->sock_fd, level, optname,
1793 (void *)PyString_AS_STRING(buf), &buflen);
1794 if (res < 0) {
1795 Py_DECREF(buf);
1796 return s->errorhandler();
1798 _PyString_Resize(&buf, buflen);
1799 return buf;
1800 #endif /* __BEOS__ */
1803 PyDoc_STRVAR(getsockopt_doc,
1804 "getsockopt(level, option[, buffersize]) -> value\n\
1806 Get a socket option. See the Unix manual for level and option.\n\
1807 If a nonzero buffersize argument is given, the return value is a\n\
1808 string of that length; otherwise it is an integer.");
1811 /* s.bind(sockaddr) method */
1813 static PyObject *
1814 sock_bind(PySocketSockObject *s, PyObject *addro)
1816 sock_addr_t addrbuf;
1817 int addrlen;
1818 int res;
1820 if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
1821 return NULL;
1822 Py_BEGIN_ALLOW_THREADS
1823 res = bind(s->sock_fd, SAS2SA(&addrbuf), addrlen);
1824 Py_END_ALLOW_THREADS
1825 if (res < 0)
1826 return s->errorhandler();
1827 Py_INCREF(Py_None);
1828 return Py_None;
1831 PyDoc_STRVAR(bind_doc,
1832 "bind(address)\n\
1834 Bind the socket to a local address. For IP sockets, the address is a\n\
1835 pair (host, port); the host must refer to the local host. For raw packet\n\
1836 sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");
1839 /* s.close() method.
1840 Set the file descriptor to -1 so operations tried subsequently
1841 will surely fail. */
1843 static PyObject *
1844 sock_close(PySocketSockObject *s)
1846 SOCKET_T fd;
1848 if ((fd = s->sock_fd) != -1) {
1849 s->sock_fd = -1;
1850 Py_BEGIN_ALLOW_THREADS
1851 (void) SOCKETCLOSE(fd);
1852 Py_END_ALLOW_THREADS
1854 Py_INCREF(Py_None);
1855 return Py_None;
1858 PyDoc_STRVAR(close_doc,
1859 "close()\n\
1861 Close the socket. It cannot be used after this call.");
1863 static int
1864 internal_connect(PySocketSockObject *s, struct sockaddr *addr, int addrlen,
1865 int *timeoutp)
1867 int res, timeout;
1869 timeout = 0;
1870 res = connect(s->sock_fd, addr, addrlen);
1872 #ifdef MS_WINDOWS
1874 if (s->sock_timeout > 0.0) {
1875 if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK &&
1876 IS_SELECTABLE(s)) {
1877 /* This is a mess. Best solution: trust select */
1878 fd_set fds;
1879 fd_set fds_exc;
1880 struct timeval tv;
1881 tv.tv_sec = (int)s->sock_timeout;
1882 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1883 FD_ZERO(&fds);
1884 FD_SET(s->sock_fd, &fds);
1885 FD_ZERO(&fds_exc);
1886 FD_SET(s->sock_fd, &fds_exc);
1887 res = select(s->sock_fd+1, NULL, &fds, &fds_exc, &tv);
1888 if (res == 0) {
1889 res = WSAEWOULDBLOCK;
1890 timeout = 1;
1891 } else if (res > 0) {
1892 if (FD_ISSET(s->sock_fd, &fds))
1893 /* The socket is in the writeable set - this
1894 means connected */
1895 res = 0;
1896 else {
1897 /* As per MS docs, we need to call getsockopt()
1898 to get the underlying error */
1899 int res_size = sizeof res;
1900 /* It must be in the exception set */
1901 assert(FD_ISSET(s->sock_fd, &fds_exc));
1902 if (0 == getsockopt(s->sock_fd, SOL_SOCKET, SO_ERROR,
1903 (char *)&res, &res_size))
1904 /* getsockopt also clears WSAGetLastError,
1905 so reset it back. */
1906 WSASetLastError(res);
1907 else
1908 res = WSAGetLastError();
1911 /* else if (res < 0) an error occurred */
1915 if (res < 0)
1916 res = WSAGetLastError();
1918 #else
1920 if (s->sock_timeout > 0.0) {
1921 if (res < 0 && errno == EINPROGRESS && IS_SELECTABLE(s)) {
1922 timeout = internal_select(s, 1);
1923 if (timeout == 0) {
1924 res = connect(s->sock_fd, addr, addrlen);
1925 if (res < 0 && errno == EISCONN)
1926 res = 0;
1928 else if (timeout == -1)
1929 res = errno; /* had error */
1930 else
1931 res = EWOULDBLOCK; /* timed out */
1935 if (res < 0)
1936 res = errno;
1938 #endif
1939 *timeoutp = timeout;
1941 return res;
1944 /* s.connect(sockaddr) method */
1946 static PyObject *
1947 sock_connect(PySocketSockObject *s, PyObject *addro)
1949 sock_addr_t addrbuf;
1950 int addrlen;
1951 int res;
1952 int timeout;
1954 if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
1955 return NULL;
1957 Py_BEGIN_ALLOW_THREADS
1958 res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
1959 Py_END_ALLOW_THREADS
1961 if (timeout == 1) {
1962 PyErr_SetString(socket_timeout, "timed out");
1963 return NULL;
1965 if (res != 0)
1966 return s->errorhandler();
1967 Py_INCREF(Py_None);
1968 return Py_None;
1971 PyDoc_STRVAR(connect_doc,
1972 "connect(address)\n\
1974 Connect the socket to a remote address. For IP sockets, the address\n\
1975 is a pair (host, port).");
1978 /* s.connect_ex(sockaddr) method */
1980 static PyObject *
1981 sock_connect_ex(PySocketSockObject *s, PyObject *addro)
1983 sock_addr_t addrbuf;
1984 int addrlen;
1985 int res;
1986 int timeout;
1988 if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
1989 return NULL;
1991 Py_BEGIN_ALLOW_THREADS
1992 res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
1993 Py_END_ALLOW_THREADS
1995 /* Signals are not errors (though they may raise exceptions). Adapted
1996 from PyErr_SetFromErrnoWithFilenameObject(). */
1997 #ifdef EINTR
1998 if (res == EINTR && PyErr_CheckSignals())
1999 return NULL;
2000 #endif
2002 return PyInt_FromLong((long) res);
2005 PyDoc_STRVAR(connect_ex_doc,
2006 "connect_ex(address) -> errno\n\
2008 This is like connect(address), but returns an error code (the errno value)\n\
2009 instead of raising an exception when an error occurs.");
2012 /* s.fileno() method */
2014 static PyObject *
2015 sock_fileno(PySocketSockObject *s)
2017 #if SIZEOF_SOCKET_T <= SIZEOF_LONG
2018 return PyInt_FromLong((long) s->sock_fd);
2019 #else
2020 return PyLong_FromLongLong((PY_LONG_LONG)s->sock_fd);
2021 #endif
2024 PyDoc_STRVAR(fileno_doc,
2025 "fileno() -> integer\n\
2027 Return the integer file descriptor of the socket.");
2030 #ifndef NO_DUP
2031 /* s.dup() method */
2033 static PyObject *
2034 sock_dup(PySocketSockObject *s)
2036 SOCKET_T newfd;
2037 PyObject *sock;
2039 newfd = dup(s->sock_fd);
2040 if (newfd < 0)
2041 return s->errorhandler();
2042 sock = (PyObject *) new_sockobject(newfd,
2043 s->sock_family,
2044 s->sock_type,
2045 s->sock_proto);
2046 if (sock == NULL)
2047 SOCKETCLOSE(newfd);
2048 return sock;
2051 PyDoc_STRVAR(dup_doc,
2052 "dup() -> socket object\n\
2054 Return a new socket object connected to the same system resource.");
2056 #endif
2059 /* s.getsockname() method */
2061 static PyObject *
2062 sock_getsockname(PySocketSockObject *s)
2064 sock_addr_t addrbuf;
2065 int res;
2066 socklen_t addrlen;
2068 if (!getsockaddrlen(s, &addrlen))
2069 return NULL;
2070 memset(&addrbuf, 0, addrlen);
2071 Py_BEGIN_ALLOW_THREADS
2072 res = getsockname(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
2073 Py_END_ALLOW_THREADS
2074 if (res < 0)
2075 return s->errorhandler();
2076 return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
2077 s->sock_proto);
2080 PyDoc_STRVAR(getsockname_doc,
2081 "getsockname() -> address info\n\
2083 Return the address of the local endpoint. For IP sockets, the address\n\
2084 info is a pair (hostaddr, port).");
2087 #ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
2088 /* s.getpeername() method */
2090 static PyObject *
2091 sock_getpeername(PySocketSockObject *s)
2093 sock_addr_t addrbuf;
2094 int res;
2095 socklen_t addrlen;
2097 if (!getsockaddrlen(s, &addrlen))
2098 return NULL;
2099 memset(&addrbuf, 0, addrlen);
2100 Py_BEGIN_ALLOW_THREADS
2101 res = getpeername(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
2102 Py_END_ALLOW_THREADS
2103 if (res < 0)
2104 return s->errorhandler();
2105 return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
2106 s->sock_proto);
2109 PyDoc_STRVAR(getpeername_doc,
2110 "getpeername() -> address info\n\
2112 Return the address of the remote endpoint. For IP sockets, the address\n\
2113 info is a pair (hostaddr, port).");
2115 #endif /* HAVE_GETPEERNAME */
2118 /* s.listen(n) method */
2120 static PyObject *
2121 sock_listen(PySocketSockObject *s, PyObject *arg)
2123 int backlog;
2124 int res;
2126 backlog = PyInt_AsLong(arg);
2127 if (backlog == -1 && PyErr_Occurred())
2128 return NULL;
2129 Py_BEGIN_ALLOW_THREADS
2130 if (backlog < 1)
2131 backlog = 1;
2132 res = listen(s->sock_fd, backlog);
2133 Py_END_ALLOW_THREADS
2134 if (res < 0)
2135 return s->errorhandler();
2136 Py_INCREF(Py_None);
2137 return Py_None;
2140 PyDoc_STRVAR(listen_doc,
2141 "listen(backlog)\n\
2143 Enable a server to accept connections. The backlog argument must be at\n\
2144 least 1; it specifies the number of unaccepted connection that the system\n\
2145 will allow before refusing new connections.");
2148 #ifndef NO_DUP
2149 /* s.makefile(mode) method.
2150 Create a new open file object referring to a dupped version of
2151 the socket's file descriptor. (The dup() call is necessary so
2152 that the open file and socket objects may be closed independent
2153 of each other.)
2154 The mode argument specifies 'r' or 'w' passed to fdopen(). */
2156 static PyObject *
2157 sock_makefile(PySocketSockObject *s, PyObject *args)
2159 extern int fclose(FILE *);
2160 char *mode = "r";
2161 int bufsize = -1;
2162 #ifdef MS_WIN32
2163 Py_intptr_t fd;
2164 #else
2165 int fd;
2166 #endif
2167 FILE *fp;
2168 PyObject *f;
2169 #ifdef __VMS
2170 char *mode_r = "r";
2171 char *mode_w = "w";
2172 #endif
2174 if (!PyArg_ParseTuple(args, "|si:makefile", &mode, &bufsize))
2175 return NULL;
2176 #ifdef __VMS
2177 if (strcmp(mode,"rb") == 0) {
2178 mode = mode_r;
2180 else {
2181 if (strcmp(mode,"wb") == 0) {
2182 mode = mode_w;
2185 #endif
2186 #ifdef MS_WIN32
2187 if (((fd = _open_osfhandle(s->sock_fd, _O_BINARY)) < 0) ||
2188 ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL))
2189 #else
2190 if ((fd = dup(s->sock_fd)) < 0 || (fp = fdopen(fd, mode)) == NULL)
2191 #endif
2193 if (fd >= 0)
2194 SOCKETCLOSE(fd);
2195 return s->errorhandler();
2197 f = PyFile_FromFile(fp, "<socket>", mode, fclose);
2198 if (f != NULL)
2199 PyFile_SetBufSize(f, bufsize);
2200 return f;
2203 PyDoc_STRVAR(makefile_doc,
2204 "makefile([mode[, buffersize]]) -> file object\n\
2206 Return a regular file object corresponding to the socket.\n\
2207 The mode and buffersize arguments are as for the built-in open() function.");
2209 #endif /* NO_DUP */
2212 * This is the guts of the recv() and recv_into() methods, which reads into a
2213 * char buffer. If you have any inc/dec ref to do to the objects that contain
2214 * the buffer, do it in the caller. This function returns the number of bytes
2215 * succesfully read. If there was an error, it returns -1. Note that it is
2216 * also possible that we return a number of bytes smaller than the request
2217 * bytes.
2219 static ssize_t
2220 sock_recv_guts(PySocketSockObject *s, char* cbuf, int len, int flags)
2222 ssize_t outlen = -1;
2223 int timeout;
2224 #ifdef __VMS
2225 int remaining;
2226 char *read_buf;
2227 #endif
2229 if (!IS_SELECTABLE(s)) {
2230 select_error();
2231 return -1;
2234 #ifndef __VMS
2235 Py_BEGIN_ALLOW_THREADS
2236 timeout = internal_select(s, 0);
2237 if (!timeout)
2238 outlen = recv(s->sock_fd, cbuf, len, flags);
2239 Py_END_ALLOW_THREADS
2241 if (timeout == 1) {
2242 PyErr_SetString(socket_timeout, "timed out");
2243 return -1;
2245 if (outlen < 0) {
2246 /* Note: the call to errorhandler() ALWAYS indirectly returned
2247 NULL, so ignore its return value */
2248 s->errorhandler();
2249 return -1;
2251 #else
2252 read_buf = cbuf;
2253 remaining = len;
2254 while (remaining != 0) {
2255 unsigned int segment;
2256 int nread = -1;
2258 segment = remaining /SEGMENT_SIZE;
2259 if (segment != 0) {
2260 segment = SEGMENT_SIZE;
2262 else {
2263 segment = remaining;
2266 Py_BEGIN_ALLOW_THREADS
2267 timeout = internal_select(s, 0);
2268 if (!timeout)
2269 nread = recv(s->sock_fd, read_buf, segment, flags);
2270 Py_END_ALLOW_THREADS
2272 if (timeout == 1) {
2273 PyErr_SetString(socket_timeout, "timed out");
2274 return -1;
2276 if (nread < 0) {
2277 s->errorhandler();
2278 return -1;
2280 if (nread != remaining) {
2281 read_buf += nread;
2282 break;
2285 remaining -= segment;
2286 read_buf += segment;
2288 outlen = read_buf - cbuf;
2289 #endif /* !__VMS */
2291 return outlen;
2295 /* s.recv(nbytes [,flags]) method */
2297 static PyObject *
2298 sock_recv(PySocketSockObject *s, PyObject *args)
2300 int recvlen, flags = 0;
2301 ssize_t outlen;
2302 PyObject *buf;
2304 if (!PyArg_ParseTuple(args, "i|i:recv", &recvlen, &flags))
2305 return NULL;
2307 if (recvlen < 0) {
2308 PyErr_SetString(PyExc_ValueError,
2309 "negative buffersize in recv");
2310 return NULL;
2313 /* Allocate a new string. */
2314 buf = PyString_FromStringAndSize((char *) 0, recvlen);
2315 if (buf == NULL)
2316 return NULL;
2318 /* Call the guts */
2319 outlen = sock_recv_guts(s, PyString_AS_STRING(buf), recvlen, flags);
2320 if (outlen < 0) {
2321 /* An error occurred, release the string and return an
2322 error. */
2323 Py_DECREF(buf);
2324 return NULL;
2326 if (outlen != recvlen) {
2327 /* We did not read as many bytes as we anticipated, resize the
2328 string if possible and be succesful. */
2329 if (_PyString_Resize(&buf, outlen) < 0)
2330 /* Oopsy, not so succesful after all. */
2331 return NULL;
2334 return buf;
2337 PyDoc_STRVAR(recv_doc,
2338 "recv(buffersize[, flags]) -> data\n\
2340 Receive up to buffersize bytes from the socket. For the optional flags\n\
2341 argument, see the Unix manual. When no data is available, block until\n\
2342 at least one byte is available or until the remote end is closed. When\n\
2343 the remote end is closed and all data is read, return the empty string.");
2346 /* s.recv_into(buffer, [nbytes [,flags]]) method */
2348 static PyObject*
2349 sock_recv_into(PySocketSockObject *s, PyObject *args, PyObject *kwds)
2351 static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
2353 int recvlen = 0, flags = 0;
2354 ssize_t readlen;
2355 char *buf;
2356 int buflen;
2358 /* Get the buffer's memory */
2359 if (!PyArg_ParseTupleAndKeywords(args, kwds, "w#|ii:recv", kwlist,
2360 &buf, &buflen, &recvlen, &flags))
2361 return NULL;
2362 assert(buf != 0 && buflen > 0);
2364 if (recvlen < 0) {
2365 PyErr_SetString(PyExc_ValueError,
2366 "negative buffersize in recv");
2367 return NULL;
2369 if (recvlen == 0) {
2370 /* If nbytes was not specified, use the buffer's length */
2371 recvlen = buflen;
2374 /* Check if the buffer is large enough */
2375 if (buflen < recvlen) {
2376 PyErr_SetString(PyExc_ValueError,
2377 "buffer too small for requested bytes");
2378 return NULL;
2381 /* Call the guts */
2382 readlen = sock_recv_guts(s, buf, recvlen, flags);
2383 if (readlen < 0) {
2384 /* Return an error. */
2385 return NULL;
2388 /* Return the number of bytes read. Note that we do not do anything
2389 special here in the case that readlen < recvlen. */
2390 return PyInt_FromSsize_t(readlen);
2393 PyDoc_STRVAR(recv_into_doc,
2394 "recv_into(buffer, [nbytes[, flags]]) -> nbytes_read\n\
2396 A version of recv() that stores its data into a buffer rather than creating \n\
2397 a new string. Receive up to buffersize bytes from the socket. If buffersize \n\
2398 is not specified (or 0), receive up to the size available in the given buffer.\n\
2400 See recv() for documentation about the flags.");
2404 * This is the guts of the recv() and recv_into() methods, which reads into a
2405 * char buffer. If you have any inc/def ref to do to the objects that contain
2406 * the buffer, do it in the caller. This function returns the number of bytes
2407 * succesfully read. If there was an error, it returns -1. Note that it is
2408 * also possible that we return a number of bytes smaller than the request
2409 * bytes.
2411 * 'addr' is a return value for the address object. Note that you must decref
2412 * it yourself.
2414 static ssize_t
2415 sock_recvfrom_guts(PySocketSockObject *s, char* cbuf, int len, int flags,
2416 PyObject** addr)
2418 sock_addr_t addrbuf;
2419 int timeout;
2420 ssize_t n = -1;
2421 socklen_t addrlen;
2423 *addr = NULL;
2425 if (!getsockaddrlen(s, &addrlen))
2426 return -1;
2428 if (!IS_SELECTABLE(s)) {
2429 select_error();
2430 return -1;
2433 Py_BEGIN_ALLOW_THREADS
2434 memset(&addrbuf, 0, addrlen);
2435 timeout = internal_select(s, 0);
2436 if (!timeout) {
2437 #ifndef MS_WINDOWS
2438 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
2439 n = recvfrom(s->sock_fd, cbuf, len, flags,
2440 SAS2SA(&addrbuf), &addrlen);
2441 #else
2442 n = recvfrom(s->sock_fd, cbuf, len, flags,
2443 (void *) &addrbuf, &addrlen);
2444 #endif
2445 #else
2446 n = recvfrom(s->sock_fd, cbuf, len, flags,
2447 SAS2SA(&addrbuf), &addrlen);
2448 #endif
2450 Py_END_ALLOW_THREADS
2452 if (timeout == 1) {
2453 PyErr_SetString(socket_timeout, "timed out");
2454 return -1;
2456 if (n < 0) {
2457 s->errorhandler();
2458 return -1;
2461 if (!(*addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
2462 addrlen, s->sock_proto)))
2463 return -1;
2465 return n;
2468 /* s.recvfrom(nbytes [,flags]) method */
2470 static PyObject *
2471 sock_recvfrom(PySocketSockObject *s, PyObject *args)
2473 PyObject *buf = NULL;
2474 PyObject *addr = NULL;
2475 PyObject *ret = NULL;
2476 int recvlen, flags = 0;
2477 ssize_t outlen;
2479 if (!PyArg_ParseTuple(args, "i|i:recvfrom", &recvlen, &flags))
2480 return NULL;
2482 buf = PyString_FromStringAndSize((char *) 0, recvlen);
2483 if (buf == NULL)
2484 return NULL;
2486 outlen = sock_recvfrom_guts(s, PyString_AS_STRING(buf),
2487 recvlen, flags, &addr);
2488 if (outlen < 0) {
2489 goto finally;
2492 if (outlen != recvlen) {
2493 /* We did not read as many bytes as we anticipated, resize the
2494 string if possible and be succesful. */
2495 if (_PyString_Resize(&buf, outlen) < 0)
2496 /* Oopsy, not so succesful after all. */
2497 goto finally;
2500 ret = PyTuple_Pack(2, buf, addr);
2502 finally:
2503 Py_XDECREF(buf);
2504 Py_XDECREF(addr);
2505 return ret;
2508 PyDoc_STRVAR(recvfrom_doc,
2509 "recvfrom(buffersize[, flags]) -> (data, address info)\n\
2511 Like recv(buffersize, flags) but also return the sender's address info.");
2514 /* s.recvfrom_into(buffer[, nbytes [,flags]]) method */
2516 static PyObject *
2517 sock_recvfrom_into(PySocketSockObject *s, PyObject *args, PyObject* kwds)
2519 static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
2521 int recvlen = 0, flags = 0;
2522 ssize_t readlen;
2523 char *buf;
2524 int buflen;
2526 PyObject *addr = NULL;
2528 if (!PyArg_ParseTupleAndKeywords(args, kwds, "w#|ii:recvfrom", kwlist,
2529 &buf, &buflen, &recvlen, &flags))
2530 return NULL;
2531 assert(buf != 0 && buflen > 0);
2533 if (recvlen < 0) {
2534 PyErr_SetString(PyExc_ValueError,
2535 "negative buffersize in recv");
2536 return NULL;
2538 if (recvlen == 0) {
2539 /* If nbytes was not specified, use the buffer's length */
2540 recvlen = buflen;
2543 readlen = sock_recvfrom_guts(s, buf, recvlen, flags, &addr);
2544 if (readlen < 0) {
2545 /* Return an error */
2546 Py_XDECREF(addr);
2547 return NULL;
2550 /* Return the number of bytes read and the address. Note that we do
2551 not do anything special here in the case that readlen < recvlen. */
2552 return Py_BuildValue("lN", readlen, addr);
2555 PyDoc_STRVAR(recvfrom_into_doc,
2556 "recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)\n\
2558 Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.");
2561 /* s.send(data [,flags]) method */
2563 static PyObject *
2564 sock_send(PySocketSockObject *s, PyObject *args)
2566 char *buf;
2567 int len, n = -1, flags = 0, timeout;
2569 if (!PyArg_ParseTuple(args, "s#|i:send", &buf, &len, &flags))
2570 return NULL;
2572 if (!IS_SELECTABLE(s))
2573 return select_error();
2575 Py_BEGIN_ALLOW_THREADS
2576 timeout = internal_select(s, 1);
2577 if (!timeout)
2578 #ifdef __VMS
2579 n = sendsegmented(s->sock_fd, buf, len, flags);
2580 #else
2581 n = send(s->sock_fd, buf, len, flags);
2582 #endif
2583 Py_END_ALLOW_THREADS
2585 if (timeout == 1) {
2586 PyErr_SetString(socket_timeout, "timed out");
2587 return NULL;
2589 if (n < 0)
2590 return s->errorhandler();
2591 return PyInt_FromLong((long)n);
2594 PyDoc_STRVAR(send_doc,
2595 "send(data[, flags]) -> count\n\
2597 Send a data string to the socket. For the optional flags\n\
2598 argument, see the Unix manual. Return the number of bytes\n\
2599 sent; this may be less than len(data) if the network is busy.");
2602 /* s.sendall(data [,flags]) method */
2604 static PyObject *
2605 sock_sendall(PySocketSockObject *s, PyObject *args)
2607 char *buf;
2608 int len, n = -1, flags = 0, timeout;
2610 if (!PyArg_ParseTuple(args, "s#|i:sendall", &buf, &len, &flags))
2611 return NULL;
2613 if (!IS_SELECTABLE(s))
2614 return select_error();
2616 Py_BEGIN_ALLOW_THREADS
2617 do {
2618 timeout = internal_select(s, 1);
2619 n = -1;
2620 if (timeout)
2621 break;
2622 #ifdef __VMS
2623 n = sendsegmented(s->sock_fd, buf, len, flags);
2624 #else
2625 n = send(s->sock_fd, buf, len, flags);
2626 #endif
2627 if (n < 0)
2628 break;
2629 buf += n;
2630 len -= n;
2631 } while (len > 0);
2632 Py_END_ALLOW_THREADS
2634 if (timeout == 1) {
2635 PyErr_SetString(socket_timeout, "timed out");
2636 return NULL;
2638 if (n < 0)
2639 return s->errorhandler();
2641 Py_INCREF(Py_None);
2642 return Py_None;
2645 PyDoc_STRVAR(sendall_doc,
2646 "sendall(data[, flags])\n\
2648 Send a data string to the socket. For the optional flags\n\
2649 argument, see the Unix manual. This calls send() repeatedly\n\
2650 until all data is sent. If an error occurs, it's impossible\n\
2651 to tell how much data has been sent.");
2654 /* s.sendto(data, [flags,] sockaddr) method */
2656 static PyObject *
2657 sock_sendto(PySocketSockObject *s, PyObject *args)
2659 PyObject *addro;
2660 char *buf;
2661 sock_addr_t addrbuf;
2662 int addrlen, len, n = -1, flags, timeout;
2664 flags = 0;
2665 if (!PyArg_ParseTuple(args, "s#O:sendto", &buf, &len, &addro)) {
2666 PyErr_Clear();
2667 if (!PyArg_ParseTuple(args, "s#iO:sendto",
2668 &buf, &len, &flags, &addro))
2669 return NULL;
2672 if (!IS_SELECTABLE(s))
2673 return select_error();
2675 if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
2676 return NULL;
2678 Py_BEGIN_ALLOW_THREADS
2679 timeout = internal_select(s, 1);
2680 if (!timeout)
2681 n = sendto(s->sock_fd, buf, len, flags, SAS2SA(&addrbuf), addrlen);
2682 Py_END_ALLOW_THREADS
2684 if (timeout == 1) {
2685 PyErr_SetString(socket_timeout, "timed out");
2686 return NULL;
2688 if (n < 0)
2689 return s->errorhandler();
2690 return PyInt_FromLong((long)n);
2693 PyDoc_STRVAR(sendto_doc,
2694 "sendto(data[, flags], address) -> count\n\
2696 Like send(data, flags) but allows specifying the destination address.\n\
2697 For IP sockets, the address is a pair (hostaddr, port).");
2700 /* s.shutdown(how) method */
2702 static PyObject *
2703 sock_shutdown(PySocketSockObject *s, PyObject *arg)
2705 int how;
2706 int res;
2708 how = PyInt_AsLong(arg);
2709 if (how == -1 && PyErr_Occurred())
2710 return NULL;
2711 Py_BEGIN_ALLOW_THREADS
2712 res = shutdown(s->sock_fd, how);
2713 Py_END_ALLOW_THREADS
2714 if (res < 0)
2715 return s->errorhandler();
2716 Py_INCREF(Py_None);
2717 return Py_None;
2720 PyDoc_STRVAR(shutdown_doc,
2721 "shutdown(flag)\n\
2723 Shut down the reading side of the socket (flag == SHUT_RD), the writing side\n\
2724 of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).");
2727 /* List of methods for socket objects */
2729 static PyMethodDef sock_methods[] = {
2730 {"accept", (PyCFunction)sock_accept, METH_NOARGS,
2731 accept_doc},
2732 {"bind", (PyCFunction)sock_bind, METH_O,
2733 bind_doc},
2734 {"close", (PyCFunction)sock_close, METH_NOARGS,
2735 close_doc},
2736 {"connect", (PyCFunction)sock_connect, METH_O,
2737 connect_doc},
2738 {"connect_ex", (PyCFunction)sock_connect_ex, METH_O,
2739 connect_ex_doc},
2740 #ifndef NO_DUP
2741 {"dup", (PyCFunction)sock_dup, METH_NOARGS,
2742 dup_doc},
2743 #endif
2744 {"fileno", (PyCFunction)sock_fileno, METH_NOARGS,
2745 fileno_doc},
2746 #ifdef HAVE_GETPEERNAME
2747 {"getpeername", (PyCFunction)sock_getpeername,
2748 METH_NOARGS, getpeername_doc},
2749 #endif
2750 {"getsockname", (PyCFunction)sock_getsockname,
2751 METH_NOARGS, getsockname_doc},
2752 {"getsockopt", (PyCFunction)sock_getsockopt, METH_VARARGS,
2753 getsockopt_doc},
2754 {"listen", (PyCFunction)sock_listen, METH_O,
2755 listen_doc},
2756 #ifndef NO_DUP
2757 {"makefile", (PyCFunction)sock_makefile, METH_VARARGS,
2758 makefile_doc},
2759 #endif
2760 {"recv", (PyCFunction)sock_recv, METH_VARARGS,
2761 recv_doc},
2762 {"recv_into", (PyCFunction)sock_recv_into, METH_VARARGS | METH_KEYWORDS,
2763 recv_into_doc},
2764 {"recvfrom", (PyCFunction)sock_recvfrom, METH_VARARGS,
2765 recvfrom_doc},
2766 {"recvfrom_into", (PyCFunction)sock_recvfrom_into, METH_VARARGS | METH_KEYWORDS,
2767 recvfrom_into_doc},
2768 {"send", (PyCFunction)sock_send, METH_VARARGS,
2769 send_doc},
2770 {"sendall", (PyCFunction)sock_sendall, METH_VARARGS,
2771 sendall_doc},
2772 {"sendto", (PyCFunction)sock_sendto, METH_VARARGS,
2773 sendto_doc},
2774 {"setblocking", (PyCFunction)sock_setblocking, METH_O,
2775 setblocking_doc},
2776 {"settimeout", (PyCFunction)sock_settimeout, METH_O,
2777 settimeout_doc},
2778 {"gettimeout", (PyCFunction)sock_gettimeout, METH_NOARGS,
2779 gettimeout_doc},
2780 {"setsockopt", (PyCFunction)sock_setsockopt, METH_VARARGS,
2781 setsockopt_doc},
2782 {"shutdown", (PyCFunction)sock_shutdown, METH_O,
2783 shutdown_doc},
2784 #ifdef RISCOS
2785 {"sleeptaskw", (PyCFunction)sock_sleeptaskw, METH_O,
2786 sleeptaskw_doc},
2787 #endif
2788 {NULL, NULL} /* sentinel */
2791 /* SockObject members */
2792 static PyMemberDef sock_memberlist[] = {
2793 {"family", T_INT, offsetof(PySocketSockObject, sock_family), READONLY, "the socket family"},
2794 {"type", T_INT, offsetof(PySocketSockObject, sock_type), READONLY, "the socket type"},
2795 {"proto", T_INT, offsetof(PySocketSockObject, sock_proto), READONLY, "the socket protocol"},
2796 {"timeout", T_DOUBLE, offsetof(PySocketSockObject, sock_timeout), READONLY, "the socket timeout"},
2797 {0},
2800 /* Deallocate a socket object in response to the last Py_DECREF().
2801 First close the file description. */
2803 static void
2804 sock_dealloc(PySocketSockObject *s)
2806 if (s->sock_fd != -1)
2807 (void) SOCKETCLOSE(s->sock_fd);
2808 s->ob_type->tp_free((PyObject *)s);
2812 static PyObject *
2813 sock_repr(PySocketSockObject *s)
2815 char buf[512];
2816 #if SIZEOF_SOCKET_T > SIZEOF_LONG
2817 if (s->sock_fd > LONG_MAX) {
2818 /* this can occur on Win64, and actually there is a special
2819 ugly printf formatter for decimal pointer length integer
2820 printing, only bother if necessary*/
2821 PyErr_SetString(PyExc_OverflowError,
2822 "no printf formatter to display "
2823 "the socket descriptor in decimal");
2824 return NULL;
2826 #endif
2827 PyOS_snprintf(
2828 buf, sizeof(buf),
2829 "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
2830 (long)s->sock_fd, s->sock_family,
2831 s->sock_type,
2832 s->sock_proto);
2833 return PyString_FromString(buf);
2837 /* Create a new, uninitialized socket object. */
2839 static PyObject *
2840 sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2842 PyObject *new;
2844 new = type->tp_alloc(type, 0);
2845 if (new != NULL) {
2846 ((PySocketSockObject *)new)->sock_fd = -1;
2847 ((PySocketSockObject *)new)->sock_timeout = -1.0;
2848 ((PySocketSockObject *)new)->errorhandler = &set_error;
2850 return new;
2854 /* Initialize a new socket object. */
2856 /*ARGSUSED*/
2857 static int
2858 sock_initobj(PyObject *self, PyObject *args, PyObject *kwds)
2860 PySocketSockObject *s = (PySocketSockObject *)self;
2861 SOCKET_T fd;
2862 int family = AF_INET, type = SOCK_STREAM, proto = 0;
2863 static char *keywords[] = {"family", "type", "proto", 0};
2865 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2866 "|iii:socket", keywords,
2867 &family, &type, &proto))
2868 return -1;
2870 Py_BEGIN_ALLOW_THREADS
2871 fd = socket(family, type, proto);
2872 Py_END_ALLOW_THREADS
2874 #ifdef MS_WINDOWS
2875 if (fd == INVALID_SOCKET)
2876 #else
2877 if (fd < 0)
2878 #endif
2880 set_error();
2881 return -1;
2883 init_sockobject(s, fd, family, type, proto);
2885 return 0;
2890 /* Type object for socket objects. */
2892 static PyTypeObject sock_type = {
2893 PyObject_HEAD_INIT(0) /* Must fill in type value later */
2894 0, /* ob_size */
2895 "_socket.socket", /* tp_name */
2896 sizeof(PySocketSockObject), /* tp_basicsize */
2897 0, /* tp_itemsize */
2898 (destructor)sock_dealloc, /* tp_dealloc */
2899 0, /* tp_print */
2900 0, /* tp_getattr */
2901 0, /* tp_setattr */
2902 0, /* tp_compare */
2903 (reprfunc)sock_repr, /* tp_repr */
2904 0, /* tp_as_number */
2905 0, /* tp_as_sequence */
2906 0, /* tp_as_mapping */
2907 0, /* tp_hash */
2908 0, /* tp_call */
2909 0, /* tp_str */
2910 PyObject_GenericGetAttr, /* tp_getattro */
2911 0, /* tp_setattro */
2912 0, /* tp_as_buffer */
2913 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2914 sock_doc, /* tp_doc */
2915 0, /* tp_traverse */
2916 0, /* tp_clear */
2917 0, /* tp_richcompare */
2918 0, /* tp_weaklistoffset */
2919 0, /* tp_iter */
2920 0, /* tp_iternext */
2921 sock_methods, /* tp_methods */
2922 sock_memberlist, /* tp_members */
2923 0, /* tp_getset */
2924 0, /* tp_base */
2925 0, /* tp_dict */
2926 0, /* tp_descr_get */
2927 0, /* tp_descr_set */
2928 0, /* tp_dictoffset */
2929 sock_initobj, /* tp_init */
2930 PyType_GenericAlloc, /* tp_alloc */
2931 sock_new, /* tp_new */
2932 PyObject_Del, /* tp_free */
2936 /* Python interface to gethostname(). */
2938 /*ARGSUSED*/
2939 static PyObject *
2940 socket_gethostname(PyObject *self, PyObject *unused)
2942 char buf[1024];
2943 int res;
2944 Py_BEGIN_ALLOW_THREADS
2945 res = gethostname(buf, (int) sizeof buf - 1);
2946 Py_END_ALLOW_THREADS
2947 if (res < 0)
2948 return set_error();
2949 buf[sizeof buf - 1] = '\0';
2950 return PyString_FromString(buf);
2953 PyDoc_STRVAR(gethostname_doc,
2954 "gethostname() -> string\n\
2956 Return the current host name.");
2959 /* Python interface to gethostbyname(name). */
2961 /*ARGSUSED*/
2962 static PyObject *
2963 socket_gethostbyname(PyObject *self, PyObject *args)
2965 char *name;
2966 sock_addr_t addrbuf;
2968 if (!PyArg_ParseTuple(args, "s:gethostbyname", &name))
2969 return NULL;
2970 if (setipaddr(name, SAS2SA(&addrbuf), sizeof(addrbuf), AF_INET) < 0)
2971 return NULL;
2972 return makeipaddr(SAS2SA(&addrbuf), sizeof(struct sockaddr_in));
2975 PyDoc_STRVAR(gethostbyname_doc,
2976 "gethostbyname(host) -> address\n\
2978 Return the IP address (a string of the form '255.255.255.255') for a host.");
2981 /* Convenience function common to gethostbyname_ex and gethostbyaddr */
2983 static PyObject *
2984 gethost_common(struct hostent *h, struct sockaddr *addr, int alen, int af)
2986 char **pch;
2987 PyObject *rtn_tuple = (PyObject *)NULL;
2988 PyObject *name_list = (PyObject *)NULL;
2989 PyObject *addr_list = (PyObject *)NULL;
2990 PyObject *tmp;
2992 if (h == NULL) {
2993 /* Let's get real error message to return */
2994 #ifndef RISCOS
2995 set_herror(h_errno);
2996 #else
2997 PyErr_SetString(socket_error, "host not found");
2998 #endif
2999 return NULL;
3002 if (h->h_addrtype != af) {
3003 #ifdef HAVE_STRERROR
3004 /* Let's get real error message to return */
3005 PyErr_SetString(socket_error,
3006 (char *)strerror(EAFNOSUPPORT));
3007 #else
3008 PyErr_SetString(
3009 socket_error,
3010 "Address family not supported by protocol family");
3011 #endif
3012 return NULL;
3015 switch (af) {
3017 case AF_INET:
3018 if (alen < sizeof(struct sockaddr_in))
3019 return NULL;
3020 break;
3022 #ifdef ENABLE_IPV6
3023 case AF_INET6:
3024 if (alen < sizeof(struct sockaddr_in6))
3025 return NULL;
3026 break;
3027 #endif
3031 if ((name_list = PyList_New(0)) == NULL)
3032 goto err;
3034 if ((addr_list = PyList_New(0)) == NULL)
3035 goto err;
3037 /* SF #1511317: h_aliases can be NULL */
3038 if (h->h_aliases) {
3039 for (pch = h->h_aliases; *pch != NULL; pch++) {
3040 int status;
3041 tmp = PyString_FromString(*pch);
3042 if (tmp == NULL)
3043 goto err;
3045 status = PyList_Append(name_list, tmp);
3046 Py_DECREF(tmp);
3048 if (status)
3049 goto err;
3053 for (pch = h->h_addr_list; *pch != NULL; pch++) {
3054 int status;
3056 switch (af) {
3058 case AF_INET:
3060 struct sockaddr_in sin;
3061 memset(&sin, 0, sizeof(sin));
3062 sin.sin_family = af;
3063 #ifdef HAVE_SOCKADDR_SA_LEN
3064 sin.sin_len = sizeof(sin);
3065 #endif
3066 memcpy(&sin.sin_addr, *pch, sizeof(sin.sin_addr));
3067 tmp = makeipaddr((struct sockaddr *)&sin, sizeof(sin));
3069 if (pch == h->h_addr_list && alen >= sizeof(sin))
3070 memcpy((char *) addr, &sin, sizeof(sin));
3071 break;
3074 #ifdef ENABLE_IPV6
3075 case AF_INET6:
3077 struct sockaddr_in6 sin6;
3078 memset(&sin6, 0, sizeof(sin6));
3079 sin6.sin6_family = af;
3080 #ifdef HAVE_SOCKADDR_SA_LEN
3081 sin6.sin6_len = sizeof(sin6);
3082 #endif
3083 memcpy(&sin6.sin6_addr, *pch, sizeof(sin6.sin6_addr));
3084 tmp = makeipaddr((struct sockaddr *)&sin6,
3085 sizeof(sin6));
3087 if (pch == h->h_addr_list && alen >= sizeof(sin6))
3088 memcpy((char *) addr, &sin6, sizeof(sin6));
3089 break;
3091 #endif
3093 default: /* can't happen */
3094 PyErr_SetString(socket_error,
3095 "unsupported address family");
3096 return NULL;
3099 if (tmp == NULL)
3100 goto err;
3102 status = PyList_Append(addr_list, tmp);
3103 Py_DECREF(tmp);
3105 if (status)
3106 goto err;
3109 rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list);
3111 err:
3112 Py_XDECREF(name_list);
3113 Py_XDECREF(addr_list);
3114 return rtn_tuple;
3118 /* Python interface to gethostbyname_ex(name). */
3120 /*ARGSUSED*/
3121 static PyObject *
3122 socket_gethostbyname_ex(PyObject *self, PyObject *args)
3124 char *name;
3125 struct hostent *h;
3126 #ifdef ENABLE_IPV6
3127 struct sockaddr_storage addr;
3128 #else
3129 struct sockaddr_in addr;
3130 #endif
3131 struct sockaddr *sa;
3132 PyObject *ret;
3133 #ifdef HAVE_GETHOSTBYNAME_R
3134 struct hostent hp_allocated;
3135 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
3136 struct hostent_data data;
3137 #else
3138 char buf[16384];
3139 int buf_len = (sizeof buf) - 1;
3140 int errnop;
3141 #endif
3142 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3143 int result;
3144 #endif
3145 #endif /* HAVE_GETHOSTBYNAME_R */
3147 if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name))
3148 return NULL;
3149 if (setipaddr(name, (struct sockaddr *)&addr, sizeof(addr), AF_INET) < 0)
3150 return NULL;
3151 Py_BEGIN_ALLOW_THREADS
3152 #ifdef HAVE_GETHOSTBYNAME_R
3153 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3154 result = gethostbyname_r(name, &hp_allocated, buf, buf_len,
3155 &h, &errnop);
3156 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
3157 h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
3158 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
3159 memset((void *) &data, '\0', sizeof(data));
3160 result = gethostbyname_r(name, &hp_allocated, &data);
3161 h = (result != 0) ? NULL : &hp_allocated;
3162 #endif
3163 #else /* not HAVE_GETHOSTBYNAME_R */
3164 #ifdef USE_GETHOSTBYNAME_LOCK
3165 PyThread_acquire_lock(netdb_lock, 1);
3166 #endif
3167 h = gethostbyname(name);
3168 #endif /* HAVE_GETHOSTBYNAME_R */
3169 Py_END_ALLOW_THREADS
3170 /* Some C libraries would require addr.__ss_family instead of
3171 addr.ss_family.
3172 Therefore, we cast the sockaddr_storage into sockaddr to
3173 access sa_family. */
3174 sa = (struct sockaddr*)&addr;
3175 ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr),
3176 sa->sa_family);
3177 #ifdef USE_GETHOSTBYNAME_LOCK
3178 PyThread_release_lock(netdb_lock);
3179 #endif
3180 return ret;
3183 PyDoc_STRVAR(ghbn_ex_doc,
3184 "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
3186 Return the true host name, a list of aliases, and a list of IP addresses,\n\
3187 for a host. The host argument is a string giving a host name or IP number.");
3190 /* Python interface to gethostbyaddr(IP). */
3192 /*ARGSUSED*/
3193 static PyObject *
3194 socket_gethostbyaddr(PyObject *self, PyObject *args)
3196 #ifdef ENABLE_IPV6
3197 struct sockaddr_storage addr;
3198 #else
3199 struct sockaddr_in addr;
3200 #endif
3201 struct sockaddr *sa = (struct sockaddr *)&addr;
3202 char *ip_num;
3203 struct hostent *h;
3204 PyObject *ret;
3205 #ifdef HAVE_GETHOSTBYNAME_R
3206 struct hostent hp_allocated;
3207 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
3208 struct hostent_data data;
3209 #else
3210 char buf[16384];
3211 int buf_len = (sizeof buf) - 1;
3212 int errnop;
3213 #endif
3214 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3215 int result;
3216 #endif
3217 #endif /* HAVE_GETHOSTBYNAME_R */
3218 char *ap;
3219 int al;
3220 int af;
3222 if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num))
3223 return NULL;
3224 af = AF_UNSPEC;
3225 if (setipaddr(ip_num, sa, sizeof(addr), af) < 0)
3226 return NULL;
3227 af = sa->sa_family;
3228 ap = NULL;
3229 al = 0;
3230 switch (af) {
3231 case AF_INET:
3232 ap = (char *)&((struct sockaddr_in *)sa)->sin_addr;
3233 al = sizeof(((struct sockaddr_in *)sa)->sin_addr);
3234 break;
3235 #ifdef ENABLE_IPV6
3236 case AF_INET6:
3237 ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr;
3238 al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr);
3239 break;
3240 #endif
3241 default:
3242 PyErr_SetString(socket_error, "unsupported address family");
3243 return NULL;
3245 Py_BEGIN_ALLOW_THREADS
3246 #ifdef HAVE_GETHOSTBYNAME_R
3247 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3248 result = gethostbyaddr_r(ap, al, af,
3249 &hp_allocated, buf, buf_len,
3250 &h, &errnop);
3251 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
3252 h = gethostbyaddr_r(ap, al, af,
3253 &hp_allocated, buf, buf_len, &errnop);
3254 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
3255 memset((void *) &data, '\0', sizeof(data));
3256 result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data);
3257 h = (result != 0) ? NULL : &hp_allocated;
3258 #endif
3259 #else /* not HAVE_GETHOSTBYNAME_R */
3260 #ifdef USE_GETHOSTBYNAME_LOCK
3261 PyThread_acquire_lock(netdb_lock, 1);
3262 #endif
3263 h = gethostbyaddr(ap, al, af);
3264 #endif /* HAVE_GETHOSTBYNAME_R */
3265 Py_END_ALLOW_THREADS
3266 ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), af);
3267 #ifdef USE_GETHOSTBYNAME_LOCK
3268 PyThread_release_lock(netdb_lock);
3269 #endif
3270 return ret;
3273 PyDoc_STRVAR(gethostbyaddr_doc,
3274 "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
3276 Return the true host name, a list of aliases, and a list of IP addresses,\n\
3277 for a host. The host argument is a string giving a host name or IP number.");
3280 /* Python interface to getservbyname(name).
3281 This only returns the port number, since the other info is already
3282 known or not useful (like the list of aliases). */
3284 /*ARGSUSED*/
3285 static PyObject *
3286 socket_getservbyname(PyObject *self, PyObject *args)
3288 char *name, *proto=NULL;
3289 struct servent *sp;
3290 if (!PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto))
3291 return NULL;
3292 Py_BEGIN_ALLOW_THREADS
3293 sp = getservbyname(name, proto);
3294 Py_END_ALLOW_THREADS
3295 if (sp == NULL) {
3296 PyErr_SetString(socket_error, "service/proto not found");
3297 return NULL;
3299 return PyInt_FromLong((long) ntohs(sp->s_port));
3302 PyDoc_STRVAR(getservbyname_doc,
3303 "getservbyname(servicename[, protocolname]) -> integer\n\
3305 Return a port number from a service name and protocol name.\n\
3306 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3307 otherwise any protocol will match.");
3310 /* Python interface to getservbyport(port).
3311 This only returns the service name, since the other info is already
3312 known or not useful (like the list of aliases). */
3314 /*ARGSUSED*/
3315 static PyObject *
3316 socket_getservbyport(PyObject *self, PyObject *args)
3318 unsigned short port;
3319 char *proto=NULL;
3320 struct servent *sp;
3321 if (!PyArg_ParseTuple(args, "H|s:getservbyport", &port, &proto))
3322 return NULL;
3323 Py_BEGIN_ALLOW_THREADS
3324 sp = getservbyport(htons(port), proto);
3325 Py_END_ALLOW_THREADS
3326 if (sp == NULL) {
3327 PyErr_SetString(socket_error, "port/proto not found");
3328 return NULL;
3330 return PyString_FromString(sp->s_name);
3333 PyDoc_STRVAR(getservbyport_doc,
3334 "getservbyport(port[, protocolname]) -> string\n\
3336 Return the service name from a port number and protocol name.\n\
3337 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3338 otherwise any protocol will match.");
3340 /* Python interface to getprotobyname(name).
3341 This only returns the protocol number, since the other info is
3342 already known or not useful (like the list of aliases). */
3344 /*ARGSUSED*/
3345 static PyObject *
3346 socket_getprotobyname(PyObject *self, PyObject *args)
3348 char *name;
3349 struct protoent *sp;
3350 #ifdef __BEOS__
3351 /* Not available in BeOS yet. - [cjh] */
3352 PyErr_SetString(socket_error, "getprotobyname not supported");
3353 return NULL;
3354 #else
3355 if (!PyArg_ParseTuple(args, "s:getprotobyname", &name))
3356 return NULL;
3357 Py_BEGIN_ALLOW_THREADS
3358 sp = getprotobyname(name);
3359 Py_END_ALLOW_THREADS
3360 if (sp == NULL) {
3361 PyErr_SetString(socket_error, "protocol not found");
3362 return NULL;
3364 return PyInt_FromLong((long) sp->p_proto);
3365 #endif
3368 PyDoc_STRVAR(getprotobyname_doc,
3369 "getprotobyname(name) -> integer\n\
3371 Return the protocol number for the named protocol. (Rarely used.)");
3374 #ifdef HAVE_SOCKETPAIR
3375 /* Create a pair of sockets using the socketpair() function.
3376 Arguments as for socket() except the default family is AF_UNIX if
3377 defined on the platform; otherwise, the default is AF_INET. */
3379 /*ARGSUSED*/
3380 static PyObject *
3381 socket_socketpair(PyObject *self, PyObject *args)
3383 PySocketSockObject *s0 = NULL, *s1 = NULL;
3384 SOCKET_T sv[2];
3385 int family, type = SOCK_STREAM, proto = 0;
3386 PyObject *res = NULL;
3388 #if defined(AF_UNIX)
3389 family = AF_UNIX;
3390 #else
3391 family = AF_INET;
3392 #endif
3393 if (!PyArg_ParseTuple(args, "|iii:socketpair",
3394 &family, &type, &proto))
3395 return NULL;
3396 /* Create a pair of socket fds */
3397 if (socketpair(family, type, proto, sv) < 0)
3398 return set_error();
3399 s0 = new_sockobject(sv[0], family, type, proto);
3400 if (s0 == NULL)
3401 goto finally;
3402 s1 = new_sockobject(sv[1], family, type, proto);
3403 if (s1 == NULL)
3404 goto finally;
3405 res = PyTuple_Pack(2, s0, s1);
3407 finally:
3408 if (res == NULL) {
3409 if (s0 == NULL)
3410 SOCKETCLOSE(sv[0]);
3411 if (s1 == NULL)
3412 SOCKETCLOSE(sv[1]);
3414 Py_XDECREF(s0);
3415 Py_XDECREF(s1);
3416 return res;
3419 PyDoc_STRVAR(socketpair_doc,
3420 "socketpair([family[, type[, proto]]]) -> (socket object, socket object)\n\
3422 Create a pair of socket objects from the sockets returned by the platform\n\
3423 socketpair() function.\n\
3424 The arguments are the same as for socket() except the default family is\n\
3425 AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");
3427 #endif /* HAVE_SOCKETPAIR */
3430 #ifndef NO_DUP
3431 /* Create a socket object from a numeric file description.
3432 Useful e.g. if stdin is a socket.
3433 Additional arguments as for socket(). */
3435 /*ARGSUSED*/
3436 static PyObject *
3437 socket_fromfd(PyObject *self, PyObject *args)
3439 PySocketSockObject *s;
3440 SOCKET_T fd;
3441 int family, type, proto = 0;
3442 if (!PyArg_ParseTuple(args, "iii|i:fromfd",
3443 &fd, &family, &type, &proto))
3444 return NULL;
3445 /* Dup the fd so it and the socket can be closed independently */
3446 fd = dup(fd);
3447 if (fd < 0)
3448 return set_error();
3449 s = new_sockobject(fd, family, type, proto);
3450 return (PyObject *) s;
3453 PyDoc_STRVAR(fromfd_doc,
3454 "fromfd(fd, family, type[, proto]) -> socket object\n\
3456 Create a socket object from a duplicate of the given\n\
3457 file descriptor.\n\
3458 The remaining arguments are the same as for socket().");
3460 #endif /* NO_DUP */
3463 static PyObject *
3464 socket_ntohs(PyObject *self, PyObject *args)
3466 int x1, x2;
3468 if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) {
3469 return NULL;
3471 if (x1 < 0) {
3472 PyErr_SetString(PyExc_OverflowError,
3473 "can't convert negative number to unsigned long");
3474 return NULL;
3476 x2 = (unsigned int)ntohs((unsigned short)x1);
3477 return PyInt_FromLong(x2);
3480 PyDoc_STRVAR(ntohs_doc,
3481 "ntohs(integer) -> integer\n\
3483 Convert a 16-bit integer from network to host byte order.");
3486 static PyObject *
3487 socket_ntohl(PyObject *self, PyObject *arg)
3489 unsigned long x;
3491 if (PyInt_Check(arg)) {
3492 x = PyInt_AS_LONG(arg);
3493 if (x == (unsigned long) -1 && PyErr_Occurred())
3494 return NULL;
3495 if ((long)x < 0) {
3496 PyErr_SetString(PyExc_OverflowError,
3497 "can't convert negative number to unsigned long");
3498 return NULL;
3501 else if (PyLong_Check(arg)) {
3502 x = PyLong_AsUnsignedLong(arg);
3503 if (x == (unsigned long) -1 && PyErr_Occurred())
3504 return NULL;
3505 #if SIZEOF_LONG > 4
3507 unsigned long y;
3508 /* only want the trailing 32 bits */
3509 y = x & 0xFFFFFFFFUL;
3510 if (y ^ x)
3511 return PyErr_Format(PyExc_OverflowError,
3512 "long int larger than 32 bits");
3513 x = y;
3515 #endif
3517 else
3518 return PyErr_Format(PyExc_TypeError,
3519 "expected int/long, %s found",
3520 arg->ob_type->tp_name);
3521 if (x == (unsigned long) -1 && PyErr_Occurred())
3522 return NULL;
3523 return PyLong_FromUnsignedLong(ntohl(x));
3526 PyDoc_STRVAR(ntohl_doc,
3527 "ntohl(integer) -> integer\n\
3529 Convert a 32-bit integer from network to host byte order.");
3532 static PyObject *
3533 socket_htons(PyObject *self, PyObject *args)
3535 int x1, x2;
3537 if (!PyArg_ParseTuple(args, "i:htons", &x1)) {
3538 return NULL;
3540 if (x1 < 0) {
3541 PyErr_SetString(PyExc_OverflowError,
3542 "can't convert negative number to unsigned long");
3543 return NULL;
3545 x2 = (unsigned int)htons((unsigned short)x1);
3546 return PyInt_FromLong(x2);
3549 PyDoc_STRVAR(htons_doc,
3550 "htons(integer) -> integer\n\
3552 Convert a 16-bit integer from host to network byte order.");
3555 static PyObject *
3556 socket_htonl(PyObject *self, PyObject *arg)
3558 unsigned long x;
3560 if (PyInt_Check(arg)) {
3561 x = PyInt_AS_LONG(arg);
3562 if (x == (unsigned long) -1 && PyErr_Occurred())
3563 return NULL;
3564 if ((long)x < 0) {
3565 PyErr_SetString(PyExc_OverflowError,
3566 "can't convert negative number to unsigned long");
3567 return NULL;
3570 else if (PyLong_Check(arg)) {
3571 x = PyLong_AsUnsignedLong(arg);
3572 if (x == (unsigned long) -1 && PyErr_Occurred())
3573 return NULL;
3574 #if SIZEOF_LONG > 4
3576 unsigned long y;
3577 /* only want the trailing 32 bits */
3578 y = x & 0xFFFFFFFFUL;
3579 if (y ^ x)
3580 return PyErr_Format(PyExc_OverflowError,
3581 "long int larger than 32 bits");
3582 x = y;
3584 #endif
3586 else
3587 return PyErr_Format(PyExc_TypeError,
3588 "expected int/long, %s found",
3589 arg->ob_type->tp_name);
3590 return PyLong_FromUnsignedLong(htonl((unsigned long)x));
3593 PyDoc_STRVAR(htonl_doc,
3594 "htonl(integer) -> integer\n\
3596 Convert a 32-bit integer from host to network byte order.");
3598 /* socket.inet_aton() and socket.inet_ntoa() functions. */
3600 PyDoc_STRVAR(inet_aton_doc,
3601 "inet_aton(string) -> packed 32-bit IP representation\n\
3603 Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
3604 binary format used in low-level network functions.");
3606 static PyObject*
3607 socket_inet_aton(PyObject *self, PyObject *args)
3609 #ifndef INADDR_NONE
3610 #define INADDR_NONE (-1)
3611 #endif
3612 #ifdef HAVE_INET_ATON
3613 struct in_addr buf;
3614 #endif
3616 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
3617 /* Have to use inet_addr() instead */
3618 unsigned long packed_addr;
3619 #endif
3620 char *ip_addr;
3622 if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr))
3623 return NULL;
3626 #ifdef HAVE_INET_ATON
3628 #ifdef USE_INET_ATON_WEAKLINK
3629 if (inet_aton != NULL) {
3630 #endif
3631 if (inet_aton(ip_addr, &buf))
3632 return PyString_FromStringAndSize((char *)(&buf),
3633 sizeof(buf));
3635 PyErr_SetString(socket_error,
3636 "illegal IP address string passed to inet_aton");
3637 return NULL;
3639 #ifdef USE_INET_ATON_WEAKLINK
3640 } else {
3641 #endif
3643 #endif
3645 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
3647 /* special-case this address as inet_addr might return INADDR_NONE
3648 * for this */
3649 if (strcmp(ip_addr, "255.255.255.255") == 0) {
3650 packed_addr = 0xFFFFFFFF;
3651 } else {
3653 packed_addr = inet_addr(ip_addr);
3655 if (packed_addr == INADDR_NONE) { /* invalid address */
3656 PyErr_SetString(socket_error,
3657 "illegal IP address string passed to inet_aton");
3658 return NULL;
3661 return PyString_FromStringAndSize((char *) &packed_addr,
3662 sizeof(packed_addr));
3664 #ifdef USE_INET_ATON_WEAKLINK
3666 #endif
3668 #endif
3671 PyDoc_STRVAR(inet_ntoa_doc,
3672 "inet_ntoa(packed_ip) -> ip_address_string\n\
3674 Convert an IP address from 32-bit packed binary format to string format");
3676 static PyObject*
3677 socket_inet_ntoa(PyObject *self, PyObject *args)
3679 char *packed_str;
3680 int addr_len;
3681 struct in_addr packed_addr;
3683 if (!PyArg_ParseTuple(args, "s#:inet_ntoa", &packed_str, &addr_len)) {
3684 return NULL;
3687 if (addr_len != sizeof(packed_addr)) {
3688 PyErr_SetString(socket_error,
3689 "packed IP wrong length for inet_ntoa");
3690 return NULL;
3693 memcpy(&packed_addr, packed_str, addr_len);
3695 return PyString_FromString(inet_ntoa(packed_addr));
3698 #ifdef HAVE_INET_PTON
3700 PyDoc_STRVAR(inet_pton_doc,
3701 "inet_pton(af, ip) -> packed IP address string\n\
3703 Convert an IP address from string format to a packed string suitable\n\
3704 for use with low-level network functions.");
3706 static PyObject *
3707 socket_inet_pton(PyObject *self, PyObject *args)
3709 int af;
3710 char* ip;
3711 int retval;
3712 #ifdef ENABLE_IPV6
3713 char packed[MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
3714 #else
3715 char packed[sizeof(struct in_addr)];
3716 #endif
3717 if (!PyArg_ParseTuple(args, "is:inet_pton", &af, &ip)) {
3718 return NULL;
3721 #if !defined(ENABLE_IPV6) && defined(AF_INET6)
3722 if(af == AF_INET6) {
3723 PyErr_SetString(socket_error,
3724 "can't use AF_INET6, IPv6 is disabled");
3725 return NULL;
3727 #endif
3729 retval = inet_pton(af, ip, packed);
3730 if (retval < 0) {
3731 PyErr_SetFromErrno(socket_error);
3732 return NULL;
3733 } else if (retval == 0) {
3734 PyErr_SetString(socket_error,
3735 "illegal IP address string passed to inet_pton");
3736 return NULL;
3737 } else if (af == AF_INET) {
3738 return PyString_FromStringAndSize(packed,
3739 sizeof(struct in_addr));
3740 #ifdef ENABLE_IPV6
3741 } else if (af == AF_INET6) {
3742 return PyString_FromStringAndSize(packed,
3743 sizeof(struct in6_addr));
3744 #endif
3745 } else {
3746 PyErr_SetString(socket_error, "unknown address family");
3747 return NULL;
3751 PyDoc_STRVAR(inet_ntop_doc,
3752 "inet_ntop(af, packed_ip) -> string formatted IP address\n\
3754 Convert a packed IP address of the given family to string format.");
3756 static PyObject *
3757 socket_inet_ntop(PyObject *self, PyObject *args)
3759 int af;
3760 char* packed;
3761 int len;
3762 const char* retval;
3763 #ifdef ENABLE_IPV6
3764 char ip[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) + 1];
3765 #else
3766 char ip[INET_ADDRSTRLEN + 1];
3767 #endif
3769 /* Guarantee NUL-termination for PyString_FromString() below */
3770 memset((void *) &ip[0], '\0', sizeof(ip));
3772 if (!PyArg_ParseTuple(args, "is#:inet_ntop", &af, &packed, &len)) {
3773 return NULL;
3776 if (af == AF_INET) {
3777 if (len != sizeof(struct in_addr)) {
3778 PyErr_SetString(PyExc_ValueError,
3779 "invalid length of packed IP address string");
3780 return NULL;
3782 #ifdef ENABLE_IPV6
3783 } else if (af == AF_INET6) {
3784 if (len != sizeof(struct in6_addr)) {
3785 PyErr_SetString(PyExc_ValueError,
3786 "invalid length of packed IP address string");
3787 return NULL;
3789 #endif
3790 } else {
3791 PyErr_Format(PyExc_ValueError,
3792 "unknown address family %d", af);
3793 return NULL;
3796 retval = inet_ntop(af, packed, ip, sizeof(ip));
3797 if (!retval) {
3798 PyErr_SetFromErrno(socket_error);
3799 return NULL;
3800 } else {
3801 return PyString_FromString(retval);
3804 /* NOTREACHED */
3805 PyErr_SetString(PyExc_RuntimeError, "invalid handling of inet_ntop");
3806 return NULL;
3809 #endif /* HAVE_INET_PTON */
3811 /* Python interface to getaddrinfo(host, port). */
3813 /*ARGSUSED*/
3814 static PyObject *
3815 socket_getaddrinfo(PyObject *self, PyObject *args)
3817 struct addrinfo hints, *res;
3818 struct addrinfo *res0 = NULL;
3819 PyObject *hobj = NULL;
3820 PyObject *pobj = (PyObject *)NULL;
3821 char pbuf[30];
3822 char *hptr, *pptr;
3823 int family, socktype, protocol, flags;
3824 int error;
3825 PyObject *all = (PyObject *)NULL;
3826 PyObject *single = (PyObject *)NULL;
3827 PyObject *idna = NULL;
3829 family = socktype = protocol = flags = 0;
3830 family = AF_UNSPEC;
3831 if (!PyArg_ParseTuple(args, "OO|iiii:getaddrinfo",
3832 &hobj, &pobj, &family, &socktype,
3833 &protocol, &flags)) {
3834 return NULL;
3836 if (hobj == Py_None) {
3837 hptr = NULL;
3838 } else if (PyUnicode_Check(hobj)) {
3839 idna = PyObject_CallMethod(hobj, "encode", "s", "idna");
3840 if (!idna)
3841 return NULL;
3842 hptr = PyString_AsString(idna);
3843 } else if (PyString_Check(hobj)) {
3844 hptr = PyString_AsString(hobj);
3845 } else {
3846 PyErr_SetString(PyExc_TypeError,
3847 "getaddrinfo() argument 1 must be string or None");
3848 return NULL;
3850 if (PyInt_Check(pobj)) {
3851 PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", PyInt_AsLong(pobj));
3852 pptr = pbuf;
3853 } else if (PyString_Check(pobj)) {
3854 pptr = PyString_AsString(pobj);
3855 } else if (pobj == Py_None) {
3856 pptr = (char *)NULL;
3857 } else {
3858 PyErr_SetString(socket_error, "Int or String expected");
3859 goto err;
3861 memset(&hints, 0, sizeof(hints));
3862 hints.ai_family = family;
3863 hints.ai_socktype = socktype;
3864 hints.ai_protocol = protocol;
3865 hints.ai_flags = flags;
3866 Py_BEGIN_ALLOW_THREADS
3867 ACQUIRE_GETADDRINFO_LOCK
3868 error = getaddrinfo(hptr, pptr, &hints, &res0);
3869 Py_END_ALLOW_THREADS
3870 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
3871 if (error) {
3872 set_gaierror(error);
3873 goto err;
3876 if ((all = PyList_New(0)) == NULL)
3877 goto err;
3878 for (res = res0; res; res = res->ai_next) {
3879 PyObject *addr =
3880 makesockaddr(-1, res->ai_addr, res->ai_addrlen, protocol);
3881 if (addr == NULL)
3882 goto err;
3883 single = Py_BuildValue("iiisO", res->ai_family,
3884 res->ai_socktype, res->ai_protocol,
3885 res->ai_canonname ? res->ai_canonname : "",
3886 addr);
3887 Py_DECREF(addr);
3888 if (single == NULL)
3889 goto err;
3891 if (PyList_Append(all, single))
3892 goto err;
3893 Py_XDECREF(single);
3895 Py_XDECREF(idna);
3896 if (res0)
3897 freeaddrinfo(res0);
3898 return all;
3899 err:
3900 Py_XDECREF(single);
3901 Py_XDECREF(all);
3902 Py_XDECREF(idna);
3903 if (res0)
3904 freeaddrinfo(res0);
3905 return (PyObject *)NULL;
3908 PyDoc_STRVAR(getaddrinfo_doc,
3909 "getaddrinfo(host, port [, family, socktype, proto, flags])\n\
3910 -> list of (family, socktype, proto, canonname, sockaddr)\n\
3912 Resolve host and port into addrinfo struct.");
3914 /* Python interface to getnameinfo(sa, flags). */
3916 /*ARGSUSED*/
3917 static PyObject *
3918 socket_getnameinfo(PyObject *self, PyObject *args)
3920 PyObject *sa = (PyObject *)NULL;
3921 int flags;
3922 char *hostp;
3923 int port, flowinfo, scope_id;
3924 char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
3925 struct addrinfo hints, *res = NULL;
3926 int error;
3927 PyObject *ret = (PyObject *)NULL;
3929 flags = flowinfo = scope_id = 0;
3930 if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags))
3931 return NULL;
3932 if (!PyArg_ParseTuple(sa, "si|ii",
3933 &hostp, &port, &flowinfo, &scope_id))
3934 return NULL;
3935 PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port);
3936 memset(&hints, 0, sizeof(hints));
3937 hints.ai_family = AF_UNSPEC;
3938 hints.ai_socktype = SOCK_DGRAM; /* make numeric port happy */
3939 Py_BEGIN_ALLOW_THREADS
3940 ACQUIRE_GETADDRINFO_LOCK
3941 error = getaddrinfo(hostp, pbuf, &hints, &res);
3942 Py_END_ALLOW_THREADS
3943 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
3944 if (error) {
3945 set_gaierror(error);
3946 goto fail;
3948 if (res->ai_next) {
3949 PyErr_SetString(socket_error,
3950 "sockaddr resolved to multiple addresses");
3951 goto fail;
3953 switch (res->ai_family) {
3954 case AF_INET:
3956 char *t1;
3957 int t2;
3958 if (PyArg_ParseTuple(sa, "si", &t1, &t2) == 0) {
3959 PyErr_SetString(socket_error,
3960 "IPv4 sockaddr must be 2 tuple");
3961 goto fail;
3963 break;
3965 #ifdef ENABLE_IPV6
3966 case AF_INET6:
3968 struct sockaddr_in6 *sin6;
3969 sin6 = (struct sockaddr_in6 *)res->ai_addr;
3970 sin6->sin6_flowinfo = flowinfo;
3971 sin6->sin6_scope_id = scope_id;
3972 break;
3974 #endif
3976 error = getnameinfo(res->ai_addr, res->ai_addrlen,
3977 hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags);
3978 if (error) {
3979 set_gaierror(error);
3980 goto fail;
3982 ret = Py_BuildValue("ss", hbuf, pbuf);
3984 fail:
3985 if (res)
3986 freeaddrinfo(res);
3987 return ret;
3990 PyDoc_STRVAR(getnameinfo_doc,
3991 "getnameinfo(sockaddr, flags) --> (host, port)\n\
3993 Get host and port for a sockaddr.");
3996 /* Python API to getting and setting the default timeout value. */
3998 static PyObject *
3999 socket_getdefaulttimeout(PyObject *self)
4001 if (defaulttimeout < 0.0) {
4002 Py_INCREF(Py_None);
4003 return Py_None;
4005 else
4006 return PyFloat_FromDouble(defaulttimeout);
4009 PyDoc_STRVAR(getdefaulttimeout_doc,
4010 "getdefaulttimeout() -> timeout\n\
4012 Returns the default timeout in floating seconds for new socket objects.\n\
4013 A value of None indicates that new socket objects have no timeout.\n\
4014 When the socket module is first imported, the default is None.");
4016 static PyObject *
4017 socket_setdefaulttimeout(PyObject *self, PyObject *arg)
4019 double timeout;
4021 if (arg == Py_None)
4022 timeout = -1.0;
4023 else {
4024 timeout = PyFloat_AsDouble(arg);
4025 if (timeout < 0.0) {
4026 if (!PyErr_Occurred())
4027 PyErr_SetString(PyExc_ValueError,
4028 "Timeout value out of range");
4029 return NULL;
4033 defaulttimeout = timeout;
4035 Py_INCREF(Py_None);
4036 return Py_None;
4039 PyDoc_STRVAR(setdefaulttimeout_doc,
4040 "setdefaulttimeout(timeout)\n\
4042 Set the default timeout in floating seconds for new socket objects.\n\
4043 A value of None indicates that new socket objects have no timeout.\n\
4044 When the socket module is first imported, the default is None.");
4047 /* List of functions exported by this module. */
4049 static PyMethodDef socket_methods[] = {
4050 {"gethostbyname", socket_gethostbyname,
4051 METH_VARARGS, gethostbyname_doc},
4052 {"gethostbyname_ex", socket_gethostbyname_ex,
4053 METH_VARARGS, ghbn_ex_doc},
4054 {"gethostbyaddr", socket_gethostbyaddr,
4055 METH_VARARGS, gethostbyaddr_doc},
4056 {"gethostname", socket_gethostname,
4057 METH_NOARGS, gethostname_doc},
4058 {"getservbyname", socket_getservbyname,
4059 METH_VARARGS, getservbyname_doc},
4060 {"getservbyport", socket_getservbyport,
4061 METH_VARARGS, getservbyport_doc},
4062 {"getprotobyname", socket_getprotobyname,
4063 METH_VARARGS, getprotobyname_doc},
4064 #ifndef NO_DUP
4065 {"fromfd", socket_fromfd,
4066 METH_VARARGS, fromfd_doc},
4067 #endif
4068 #ifdef HAVE_SOCKETPAIR
4069 {"socketpair", socket_socketpair,
4070 METH_VARARGS, socketpair_doc},
4071 #endif
4072 {"ntohs", socket_ntohs,
4073 METH_VARARGS, ntohs_doc},
4074 {"ntohl", socket_ntohl,
4075 METH_O, ntohl_doc},
4076 {"htons", socket_htons,
4077 METH_VARARGS, htons_doc},
4078 {"htonl", socket_htonl,
4079 METH_O, htonl_doc},
4080 {"inet_aton", socket_inet_aton,
4081 METH_VARARGS, inet_aton_doc},
4082 {"inet_ntoa", socket_inet_ntoa,
4083 METH_VARARGS, inet_ntoa_doc},
4084 #ifdef HAVE_INET_PTON
4085 {"inet_pton", socket_inet_pton,
4086 METH_VARARGS, inet_pton_doc},
4087 {"inet_ntop", socket_inet_ntop,
4088 METH_VARARGS, inet_ntop_doc},
4089 #endif
4090 {"getaddrinfo", socket_getaddrinfo,
4091 METH_VARARGS, getaddrinfo_doc},
4092 {"getnameinfo", socket_getnameinfo,
4093 METH_VARARGS, getnameinfo_doc},
4094 {"getdefaulttimeout", (PyCFunction)socket_getdefaulttimeout,
4095 METH_NOARGS, getdefaulttimeout_doc},
4096 {"setdefaulttimeout", socket_setdefaulttimeout,
4097 METH_O, setdefaulttimeout_doc},
4098 {NULL, NULL} /* Sentinel */
4102 #ifdef RISCOS
4103 #define OS_INIT_DEFINED
4105 static int
4106 os_init(void)
4108 _kernel_swi_regs r;
4110 r.r[0] = 0;
4111 _kernel_swi(0x43380, &r, &r);
4112 taskwindow = r.r[0];
4114 return 1;
4117 #endif /* RISCOS */
4120 #ifdef MS_WINDOWS
4121 #define OS_INIT_DEFINED
4123 /* Additional initialization and cleanup for Windows */
4125 static void
4126 os_cleanup(void)
4128 WSACleanup();
4131 static int
4132 os_init(void)
4134 WSADATA WSAData;
4135 int ret;
4136 char buf[100];
4137 ret = WSAStartup(0x0101, &WSAData);
4138 switch (ret) {
4139 case 0: /* No error */
4140 Py_AtExit(os_cleanup);
4141 return 1; /* Success */
4142 case WSASYSNOTREADY:
4143 PyErr_SetString(PyExc_ImportError,
4144 "WSAStartup failed: network not ready");
4145 break;
4146 case WSAVERNOTSUPPORTED:
4147 case WSAEINVAL:
4148 PyErr_SetString(
4149 PyExc_ImportError,
4150 "WSAStartup failed: requested version not supported");
4151 break;
4152 default:
4153 PyOS_snprintf(buf, sizeof(buf),
4154 "WSAStartup failed: error code %d", ret);
4155 PyErr_SetString(PyExc_ImportError, buf);
4156 break;
4158 return 0; /* Failure */
4161 #endif /* MS_WINDOWS */
4164 #ifdef PYOS_OS2
4165 #define OS_INIT_DEFINED
4167 /* Additional initialization for OS/2 */
4169 static int
4170 os_init(void)
4172 #ifndef PYCC_GCC
4173 char reason[64];
4174 int rc = sock_init();
4176 if (rc == 0) {
4177 return 1; /* Success */
4180 PyOS_snprintf(reason, sizeof(reason),
4181 "OS/2 TCP/IP Error# %d", sock_errno());
4182 PyErr_SetString(PyExc_ImportError, reason);
4184 return 0; /* Failure */
4185 #else
4186 /* No need to initialise sockets with GCC/EMX */
4187 return 1; /* Success */
4188 #endif
4191 #endif /* PYOS_OS2 */
4194 #ifndef OS_INIT_DEFINED
4195 static int
4196 os_init(void)
4198 return 1; /* Success */
4200 #endif
4203 /* C API table - always add new things to the end for binary
4204 compatibility. */
4205 static
4206 PySocketModule_APIObject PySocketModuleAPI =
4208 &sock_type,
4209 NULL
4213 /* Initialize the _socket module.
4215 This module is actually called "_socket", and there's a wrapper
4216 "socket.py" which implements some additional functionality. On some
4217 platforms (e.g. Windows and OS/2), socket.py also implements a
4218 wrapper for the socket type that provides missing functionality such
4219 as makefile(), dup() and fromfd(). The import of "_socket" may fail
4220 with an ImportError exception if os-specific initialization fails.
4221 On Windows, this does WINSOCK initialization. When WINSOCK is
4222 initialized succesfully, a call to WSACleanup() is scheduled to be
4223 made at exit time.
4226 PyDoc_STRVAR(socket_doc,
4227 "Implementation module for socket operations.\n\
4229 See the socket module for documentation.");
4231 PyMODINIT_FUNC
4232 init_socket(void)
4234 PyObject *m, *has_ipv6;
4236 if (!os_init())
4237 return;
4239 sock_type.ob_type = &PyType_Type;
4240 m = Py_InitModule3(PySocket_MODULE_NAME,
4241 socket_methods,
4242 socket_doc);
4243 if (m == NULL)
4244 return;
4246 socket_error = PyErr_NewException("socket.error", NULL, NULL);
4247 if (socket_error == NULL)
4248 return;
4249 PySocketModuleAPI.error = socket_error;
4250 Py_INCREF(socket_error);
4251 PyModule_AddObject(m, "error", socket_error);
4252 socket_herror = PyErr_NewException("socket.herror",
4253 socket_error, NULL);
4254 if (socket_herror == NULL)
4255 return;
4256 Py_INCREF(socket_herror);
4257 PyModule_AddObject(m, "herror", socket_herror);
4258 socket_gaierror = PyErr_NewException("socket.gaierror", socket_error,
4259 NULL);
4260 if (socket_gaierror == NULL)
4261 return;
4262 Py_INCREF(socket_gaierror);
4263 PyModule_AddObject(m, "gaierror", socket_gaierror);
4264 socket_timeout = PyErr_NewException("socket.timeout",
4265 socket_error, NULL);
4266 if (socket_timeout == NULL)
4267 return;
4268 Py_INCREF(socket_timeout);
4269 PyModule_AddObject(m, "timeout", socket_timeout);
4270 Py_INCREF((PyObject *)&sock_type);
4271 if (PyModule_AddObject(m, "SocketType",
4272 (PyObject *)&sock_type) != 0)
4273 return;
4274 Py_INCREF((PyObject *)&sock_type);
4275 if (PyModule_AddObject(m, "socket",
4276 (PyObject *)&sock_type) != 0)
4277 return;
4279 #ifdef ENABLE_IPV6
4280 has_ipv6 = Py_True;
4281 #else
4282 has_ipv6 = Py_False;
4283 #endif
4284 Py_INCREF(has_ipv6);
4285 PyModule_AddObject(m, "has_ipv6", has_ipv6);
4287 /* Export C API */
4288 if (PyModule_AddObject(m, PySocket_CAPI_NAME,
4289 PyCObject_FromVoidPtr((void *)&PySocketModuleAPI, NULL)
4290 ) != 0)
4291 return;
4293 /* Address families (we only support AF_INET and AF_UNIX) */
4294 #ifdef AF_UNSPEC
4295 PyModule_AddIntConstant(m, "AF_UNSPEC", AF_UNSPEC);
4296 #endif
4297 PyModule_AddIntConstant(m, "AF_INET", AF_INET);
4298 #ifdef AF_INET6
4299 PyModule_AddIntConstant(m, "AF_INET6", AF_INET6);
4300 #endif /* AF_INET6 */
4301 #if defined(AF_UNIX)
4302 PyModule_AddIntConstant(m, "AF_UNIX", AF_UNIX);
4303 #endif /* AF_UNIX */
4304 #ifdef AF_AX25
4305 /* Amateur Radio AX.25 */
4306 PyModule_AddIntConstant(m, "AF_AX25", AF_AX25);
4307 #endif
4308 #ifdef AF_IPX
4309 PyModule_AddIntConstant(m, "AF_IPX", AF_IPX); /* Novell IPX */
4310 #endif
4311 #ifdef AF_APPLETALK
4312 /* Appletalk DDP */
4313 PyModule_AddIntConstant(m, "AF_APPLETALK", AF_APPLETALK);
4314 #endif
4315 #ifdef AF_NETROM
4316 /* Amateur radio NetROM */
4317 PyModule_AddIntConstant(m, "AF_NETROM", AF_NETROM);
4318 #endif
4319 #ifdef AF_BRIDGE
4320 /* Multiprotocol bridge */
4321 PyModule_AddIntConstant(m, "AF_BRIDGE", AF_BRIDGE);
4322 #endif
4323 #ifdef AF_ATMPVC
4324 /* ATM PVCs */
4325 PyModule_AddIntConstant(m, "AF_ATMPVC", AF_ATMPVC);
4326 #endif
4327 #ifdef AF_AAL5
4328 /* Reserved for Werner's ATM */
4329 PyModule_AddIntConstant(m, "AF_AAL5", AF_AAL5);
4330 #endif
4331 #ifdef AF_X25
4332 /* Reserved for X.25 project */
4333 PyModule_AddIntConstant(m, "AF_X25", AF_X25);
4334 #endif
4335 #ifdef AF_INET6
4336 PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); /* IP version 6 */
4337 #endif
4338 #ifdef AF_ROSE
4339 /* Amateur Radio X.25 PLP */
4340 PyModule_AddIntConstant(m, "AF_ROSE", AF_ROSE);
4341 #endif
4342 #ifdef AF_DECnet
4343 /* Reserved for DECnet project */
4344 PyModule_AddIntConstant(m, "AF_DECnet", AF_DECnet);
4345 #endif
4346 #ifdef AF_NETBEUI
4347 /* Reserved for 802.2LLC project */
4348 PyModule_AddIntConstant(m, "AF_NETBEUI", AF_NETBEUI);
4349 #endif
4350 #ifdef AF_SECURITY
4351 /* Security callback pseudo AF */
4352 PyModule_AddIntConstant(m, "AF_SECURITY", AF_SECURITY);
4353 #endif
4354 #ifdef AF_KEY
4355 /* PF_KEY key management API */
4356 PyModule_AddIntConstant(m, "AF_KEY", AF_KEY);
4357 #endif
4358 #ifdef AF_NETLINK
4359 /* */
4360 PyModule_AddIntConstant(m, "AF_NETLINK", AF_NETLINK);
4361 PyModule_AddIntConstant(m, "NETLINK_ROUTE", NETLINK_ROUTE);
4362 #ifdef NETLINK_SKIP
4363 PyModule_AddIntConstant(m, "NETLINK_SKIP", NETLINK_SKIP);
4364 #endif
4365 #ifdef NETLINK_W1
4366 PyModule_AddIntConstant(m, "NETLINK_W1", NETLINK_W1);
4367 #endif
4368 PyModule_AddIntConstant(m, "NETLINK_USERSOCK", NETLINK_USERSOCK);
4369 PyModule_AddIntConstant(m, "NETLINK_FIREWALL", NETLINK_FIREWALL);
4370 #ifdef NETLINK_TCPDIAG
4371 PyModule_AddIntConstant(m, "NETLINK_TCPDIAG", NETLINK_TCPDIAG);
4372 #endif
4373 #ifdef NETLINK_NFLOG
4374 PyModule_AddIntConstant(m, "NETLINK_NFLOG", NETLINK_NFLOG);
4375 #endif
4376 #ifdef NETLINK_XFRM
4377 PyModule_AddIntConstant(m, "NETLINK_XFRM", NETLINK_XFRM);
4378 #endif
4379 #ifdef NETLINK_ARPD
4380 PyModule_AddIntConstant(m, "NETLINK_ARPD", NETLINK_ARPD);
4381 #endif
4382 #ifdef NETLINK_ROUTE6
4383 PyModule_AddIntConstant(m, "NETLINK_ROUTE6", NETLINK_ROUTE6);
4384 #endif
4385 PyModule_AddIntConstant(m, "NETLINK_IP6_FW", NETLINK_IP6_FW);
4386 PyModule_AddIntConstant(m, "NETLINK_DNRTMSG", NETLINK_DNRTMSG);
4387 #ifdef NETLINK_TAPBASE
4388 PyModule_AddIntConstant(m, "NETLINK_TAPBASE", NETLINK_TAPBASE);
4389 #endif
4390 #endif /* AF_NETLINK */
4391 #ifdef AF_ROUTE
4392 /* Alias to emulate 4.4BSD */
4393 PyModule_AddIntConstant(m, "AF_ROUTE", AF_ROUTE);
4394 #endif
4395 #ifdef AF_ASH
4396 /* Ash */
4397 PyModule_AddIntConstant(m, "AF_ASH", AF_ASH);
4398 #endif
4399 #ifdef AF_ECONET
4400 /* Acorn Econet */
4401 PyModule_AddIntConstant(m, "AF_ECONET", AF_ECONET);
4402 #endif
4403 #ifdef AF_ATMSVC
4404 /* ATM SVCs */
4405 PyModule_AddIntConstant(m, "AF_ATMSVC", AF_ATMSVC);
4406 #endif
4407 #ifdef AF_SNA
4408 /* Linux SNA Project (nutters!) */
4409 PyModule_AddIntConstant(m, "AF_SNA", AF_SNA);
4410 #endif
4411 #ifdef AF_IRDA
4412 /* IRDA sockets */
4413 PyModule_AddIntConstant(m, "AF_IRDA", AF_IRDA);
4414 #endif
4415 #ifdef AF_PPPOX
4416 /* PPPoX sockets */
4417 PyModule_AddIntConstant(m, "AF_PPPOX", AF_PPPOX);
4418 #endif
4419 #ifdef AF_WANPIPE
4420 /* Wanpipe API Sockets */
4421 PyModule_AddIntConstant(m, "AF_WANPIPE", AF_WANPIPE);
4422 #endif
4423 #ifdef AF_LLC
4424 /* Linux LLC */
4425 PyModule_AddIntConstant(m, "AF_LLC", AF_LLC);
4426 #endif
4428 #ifdef USE_BLUETOOTH
4429 PyModule_AddIntConstant(m, "AF_BLUETOOTH", AF_BLUETOOTH);
4430 PyModule_AddIntConstant(m, "BTPROTO_L2CAP", BTPROTO_L2CAP);
4431 #if !defined(__FreeBSD__)
4432 PyModule_AddIntConstant(m, "BTPROTO_SCO", BTPROTO_SCO);
4433 #endif
4434 PyModule_AddIntConstant(m, "BTPROTO_RFCOMM", BTPROTO_RFCOMM);
4435 PyModule_AddStringConstant(m, "BDADDR_ANY", "00:00:00:00:00:00");
4436 PyModule_AddStringConstant(m, "BDADDR_LOCAL", "00:00:00:FF:FF:FF");
4437 #endif
4439 #ifdef HAVE_NETPACKET_PACKET_H
4440 PyModule_AddIntConstant(m, "AF_PACKET", AF_PACKET);
4441 PyModule_AddIntConstant(m, "PF_PACKET", PF_PACKET);
4442 PyModule_AddIntConstant(m, "PACKET_HOST", PACKET_HOST);
4443 PyModule_AddIntConstant(m, "PACKET_BROADCAST", PACKET_BROADCAST);
4444 PyModule_AddIntConstant(m, "PACKET_MULTICAST", PACKET_MULTICAST);
4445 PyModule_AddIntConstant(m, "PACKET_OTHERHOST", PACKET_OTHERHOST);
4446 PyModule_AddIntConstant(m, "PACKET_OUTGOING", PACKET_OUTGOING);
4447 PyModule_AddIntConstant(m, "PACKET_LOOPBACK", PACKET_LOOPBACK);
4448 PyModule_AddIntConstant(m, "PACKET_FASTROUTE", PACKET_FASTROUTE);
4449 #endif
4451 /* Socket types */
4452 PyModule_AddIntConstant(m, "SOCK_STREAM", SOCK_STREAM);
4453 PyModule_AddIntConstant(m, "SOCK_DGRAM", SOCK_DGRAM);
4454 #ifndef __BEOS__
4455 /* We have incomplete socket support. */
4456 PyModule_AddIntConstant(m, "SOCK_RAW", SOCK_RAW);
4457 PyModule_AddIntConstant(m, "SOCK_SEQPACKET", SOCK_SEQPACKET);
4458 #if defined(SOCK_RDM)
4459 PyModule_AddIntConstant(m, "SOCK_RDM", SOCK_RDM);
4460 #endif
4461 #endif
4463 #ifdef SO_DEBUG
4464 PyModule_AddIntConstant(m, "SO_DEBUG", SO_DEBUG);
4465 #endif
4466 #ifdef SO_ACCEPTCONN
4467 PyModule_AddIntConstant(m, "SO_ACCEPTCONN", SO_ACCEPTCONN);
4468 #endif
4469 #ifdef SO_REUSEADDR
4470 PyModule_AddIntConstant(m, "SO_REUSEADDR", SO_REUSEADDR);
4471 #endif
4472 #ifdef SO_EXCLUSIVEADDRUSE
4473 PyModule_AddIntConstant(m, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE);
4474 #endif
4476 #ifdef SO_KEEPALIVE
4477 PyModule_AddIntConstant(m, "SO_KEEPALIVE", SO_KEEPALIVE);
4478 #endif
4479 #ifdef SO_DONTROUTE
4480 PyModule_AddIntConstant(m, "SO_DONTROUTE", SO_DONTROUTE);
4481 #endif
4482 #ifdef SO_BROADCAST
4483 PyModule_AddIntConstant(m, "SO_BROADCAST", SO_BROADCAST);
4484 #endif
4485 #ifdef SO_USELOOPBACK
4486 PyModule_AddIntConstant(m, "SO_USELOOPBACK", SO_USELOOPBACK);
4487 #endif
4488 #ifdef SO_LINGER
4489 PyModule_AddIntConstant(m, "SO_LINGER", SO_LINGER);
4490 #endif
4491 #ifdef SO_OOBINLINE
4492 PyModule_AddIntConstant(m, "SO_OOBINLINE", SO_OOBINLINE);
4493 #endif
4494 #ifdef SO_REUSEPORT
4495 PyModule_AddIntConstant(m, "SO_REUSEPORT", SO_REUSEPORT);
4496 #endif
4497 #ifdef SO_SNDBUF
4498 PyModule_AddIntConstant(m, "SO_SNDBUF", SO_SNDBUF);
4499 #endif
4500 #ifdef SO_RCVBUF
4501 PyModule_AddIntConstant(m, "SO_RCVBUF", SO_RCVBUF);
4502 #endif
4503 #ifdef SO_SNDLOWAT
4504 PyModule_AddIntConstant(m, "SO_SNDLOWAT", SO_SNDLOWAT);
4505 #endif
4506 #ifdef SO_RCVLOWAT
4507 PyModule_AddIntConstant(m, "SO_RCVLOWAT", SO_RCVLOWAT);
4508 #endif
4509 #ifdef SO_SNDTIMEO
4510 PyModule_AddIntConstant(m, "SO_SNDTIMEO", SO_SNDTIMEO);
4511 #endif
4512 #ifdef SO_RCVTIMEO
4513 PyModule_AddIntConstant(m, "SO_RCVTIMEO", SO_RCVTIMEO);
4514 #endif
4515 #ifdef SO_ERROR
4516 PyModule_AddIntConstant(m, "SO_ERROR", SO_ERROR);
4517 #endif
4518 #ifdef SO_TYPE
4519 PyModule_AddIntConstant(m, "SO_TYPE", SO_TYPE);
4520 #endif
4522 /* Maximum number of connections for "listen" */
4523 #ifdef SOMAXCONN
4524 PyModule_AddIntConstant(m, "SOMAXCONN", SOMAXCONN);
4525 #else
4526 PyModule_AddIntConstant(m, "SOMAXCONN", 5); /* Common value */
4527 #endif
4529 /* Flags for send, recv */
4530 #ifdef MSG_OOB
4531 PyModule_AddIntConstant(m, "MSG_OOB", MSG_OOB);
4532 #endif
4533 #ifdef MSG_PEEK
4534 PyModule_AddIntConstant(m, "MSG_PEEK", MSG_PEEK);
4535 #endif
4536 #ifdef MSG_DONTROUTE
4537 PyModule_AddIntConstant(m, "MSG_DONTROUTE", MSG_DONTROUTE);
4538 #endif
4539 #ifdef MSG_DONTWAIT
4540 PyModule_AddIntConstant(m, "MSG_DONTWAIT", MSG_DONTWAIT);
4541 #endif
4542 #ifdef MSG_EOR
4543 PyModule_AddIntConstant(m, "MSG_EOR", MSG_EOR);
4544 #endif
4545 #ifdef MSG_TRUNC
4546 PyModule_AddIntConstant(m, "MSG_TRUNC", MSG_TRUNC);
4547 #endif
4548 #ifdef MSG_CTRUNC
4549 PyModule_AddIntConstant(m, "MSG_CTRUNC", MSG_CTRUNC);
4550 #endif
4551 #ifdef MSG_WAITALL
4552 PyModule_AddIntConstant(m, "MSG_WAITALL", MSG_WAITALL);
4553 #endif
4554 #ifdef MSG_BTAG
4555 PyModule_AddIntConstant(m, "MSG_BTAG", MSG_BTAG);
4556 #endif
4557 #ifdef MSG_ETAG
4558 PyModule_AddIntConstant(m, "MSG_ETAG", MSG_ETAG);
4559 #endif
4561 /* Protocol level and numbers, usable for [gs]etsockopt */
4562 #ifdef SOL_SOCKET
4563 PyModule_AddIntConstant(m, "SOL_SOCKET", SOL_SOCKET);
4564 #endif
4565 #ifdef SOL_IP
4566 PyModule_AddIntConstant(m, "SOL_IP", SOL_IP);
4567 #else
4568 PyModule_AddIntConstant(m, "SOL_IP", 0);
4569 #endif
4570 #ifdef SOL_IPX
4571 PyModule_AddIntConstant(m, "SOL_IPX", SOL_IPX);
4572 #endif
4573 #ifdef SOL_AX25
4574 PyModule_AddIntConstant(m, "SOL_AX25", SOL_AX25);
4575 #endif
4576 #ifdef SOL_ATALK
4577 PyModule_AddIntConstant(m, "SOL_ATALK", SOL_ATALK);
4578 #endif
4579 #ifdef SOL_NETROM
4580 PyModule_AddIntConstant(m, "SOL_NETROM", SOL_NETROM);
4581 #endif
4582 #ifdef SOL_ROSE
4583 PyModule_AddIntConstant(m, "SOL_ROSE", SOL_ROSE);
4584 #endif
4585 #ifdef SOL_TCP
4586 PyModule_AddIntConstant(m, "SOL_TCP", SOL_TCP);
4587 #else
4588 PyModule_AddIntConstant(m, "SOL_TCP", 6);
4589 #endif
4590 #ifdef SOL_UDP
4591 PyModule_AddIntConstant(m, "SOL_UDP", SOL_UDP);
4592 #else
4593 PyModule_AddIntConstant(m, "SOL_UDP", 17);
4594 #endif
4595 #ifdef IPPROTO_IP
4596 PyModule_AddIntConstant(m, "IPPROTO_IP", IPPROTO_IP);
4597 #else
4598 PyModule_AddIntConstant(m, "IPPROTO_IP", 0);
4599 #endif
4600 #ifdef IPPROTO_HOPOPTS
4601 PyModule_AddIntConstant(m, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS);
4602 #endif
4603 #ifdef IPPROTO_ICMP
4604 PyModule_AddIntConstant(m, "IPPROTO_ICMP", IPPROTO_ICMP);
4605 #else
4606 PyModule_AddIntConstant(m, "IPPROTO_ICMP", 1);
4607 #endif
4608 #ifdef IPPROTO_IGMP
4609 PyModule_AddIntConstant(m, "IPPROTO_IGMP", IPPROTO_IGMP);
4610 #endif
4611 #ifdef IPPROTO_GGP
4612 PyModule_AddIntConstant(m, "IPPROTO_GGP", IPPROTO_GGP);
4613 #endif
4614 #ifdef IPPROTO_IPV4
4615 PyModule_AddIntConstant(m, "IPPROTO_IPV4", IPPROTO_IPV4);
4616 #endif
4617 #ifdef IPPROTO_IPV6
4618 PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
4619 #endif
4620 #ifdef IPPROTO_IPIP
4621 PyModule_AddIntConstant(m, "IPPROTO_IPIP", IPPROTO_IPIP);
4622 #endif
4623 #ifdef IPPROTO_TCP
4624 PyModule_AddIntConstant(m, "IPPROTO_TCP", IPPROTO_TCP);
4625 #else
4626 PyModule_AddIntConstant(m, "IPPROTO_TCP", 6);
4627 #endif
4628 #ifdef IPPROTO_EGP
4629 PyModule_AddIntConstant(m, "IPPROTO_EGP", IPPROTO_EGP);
4630 #endif
4631 #ifdef IPPROTO_PUP
4632 PyModule_AddIntConstant(m, "IPPROTO_PUP", IPPROTO_PUP);
4633 #endif
4634 #ifdef IPPROTO_UDP
4635 PyModule_AddIntConstant(m, "IPPROTO_UDP", IPPROTO_UDP);
4636 #else
4637 PyModule_AddIntConstant(m, "IPPROTO_UDP", 17);
4638 #endif
4639 #ifdef IPPROTO_IDP
4640 PyModule_AddIntConstant(m, "IPPROTO_IDP", IPPROTO_IDP);
4641 #endif
4642 #ifdef IPPROTO_HELLO
4643 PyModule_AddIntConstant(m, "IPPROTO_HELLO", IPPROTO_HELLO);
4644 #endif
4645 #ifdef IPPROTO_ND
4646 PyModule_AddIntConstant(m, "IPPROTO_ND", IPPROTO_ND);
4647 #endif
4648 #ifdef IPPROTO_TP
4649 PyModule_AddIntConstant(m, "IPPROTO_TP", IPPROTO_TP);
4650 #endif
4651 #ifdef IPPROTO_IPV6
4652 PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
4653 #endif
4654 #ifdef IPPROTO_ROUTING
4655 PyModule_AddIntConstant(m, "IPPROTO_ROUTING", IPPROTO_ROUTING);
4656 #endif
4657 #ifdef IPPROTO_FRAGMENT
4658 PyModule_AddIntConstant(m, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT);
4659 #endif
4660 #ifdef IPPROTO_RSVP
4661 PyModule_AddIntConstant(m, "IPPROTO_RSVP", IPPROTO_RSVP);
4662 #endif
4663 #ifdef IPPROTO_GRE
4664 PyModule_AddIntConstant(m, "IPPROTO_GRE", IPPROTO_GRE);
4665 #endif
4666 #ifdef IPPROTO_ESP
4667 PyModule_AddIntConstant(m, "IPPROTO_ESP", IPPROTO_ESP);
4668 #endif
4669 #ifdef IPPROTO_AH
4670 PyModule_AddIntConstant(m, "IPPROTO_AH", IPPROTO_AH);
4671 #endif
4672 #ifdef IPPROTO_MOBILE
4673 PyModule_AddIntConstant(m, "IPPROTO_MOBILE", IPPROTO_MOBILE);
4674 #endif
4675 #ifdef IPPROTO_ICMPV6
4676 PyModule_AddIntConstant(m, "IPPROTO_ICMPV6", IPPROTO_ICMPV6);
4677 #endif
4678 #ifdef IPPROTO_NONE
4679 PyModule_AddIntConstant(m, "IPPROTO_NONE", IPPROTO_NONE);
4680 #endif
4681 #ifdef IPPROTO_DSTOPTS
4682 PyModule_AddIntConstant(m, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS);
4683 #endif
4684 #ifdef IPPROTO_XTP
4685 PyModule_AddIntConstant(m, "IPPROTO_XTP", IPPROTO_XTP);
4686 #endif
4687 #ifdef IPPROTO_EON
4688 PyModule_AddIntConstant(m, "IPPROTO_EON", IPPROTO_EON);
4689 #endif
4690 #ifdef IPPROTO_PIM
4691 PyModule_AddIntConstant(m, "IPPROTO_PIM", IPPROTO_PIM);
4692 #endif
4693 #ifdef IPPROTO_IPCOMP
4694 PyModule_AddIntConstant(m, "IPPROTO_IPCOMP", IPPROTO_IPCOMP);
4695 #endif
4696 #ifdef IPPROTO_VRRP
4697 PyModule_AddIntConstant(m, "IPPROTO_VRRP", IPPROTO_VRRP);
4698 #endif
4699 #ifdef IPPROTO_BIP
4700 PyModule_AddIntConstant(m, "IPPROTO_BIP", IPPROTO_BIP);
4701 #endif
4702 /**/
4703 #ifdef IPPROTO_RAW
4704 PyModule_AddIntConstant(m, "IPPROTO_RAW", IPPROTO_RAW);
4705 #else
4706 PyModule_AddIntConstant(m, "IPPROTO_RAW", 255);
4707 #endif
4708 #ifdef IPPROTO_MAX
4709 PyModule_AddIntConstant(m, "IPPROTO_MAX", IPPROTO_MAX);
4710 #endif
4712 /* Some port configuration */
4713 #ifdef IPPORT_RESERVED
4714 PyModule_AddIntConstant(m, "IPPORT_RESERVED", IPPORT_RESERVED);
4715 #else
4716 PyModule_AddIntConstant(m, "IPPORT_RESERVED", 1024);
4717 #endif
4718 #ifdef IPPORT_USERRESERVED
4719 PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", IPPORT_USERRESERVED);
4720 #else
4721 PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", 5000);
4722 #endif
4724 /* Some reserved IP v.4 addresses */
4725 #ifdef INADDR_ANY
4726 PyModule_AddIntConstant(m, "INADDR_ANY", INADDR_ANY);
4727 #else
4728 PyModule_AddIntConstant(m, "INADDR_ANY", 0x00000000);
4729 #endif
4730 #ifdef INADDR_BROADCAST
4731 PyModule_AddIntConstant(m, "INADDR_BROADCAST", INADDR_BROADCAST);
4732 #else
4733 PyModule_AddIntConstant(m, "INADDR_BROADCAST", 0xffffffff);
4734 #endif
4735 #ifdef INADDR_LOOPBACK
4736 PyModule_AddIntConstant(m, "INADDR_LOOPBACK", INADDR_LOOPBACK);
4737 #else
4738 PyModule_AddIntConstant(m, "INADDR_LOOPBACK", 0x7F000001);
4739 #endif
4740 #ifdef INADDR_UNSPEC_GROUP
4741 PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
4742 #else
4743 PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", 0xe0000000);
4744 #endif
4745 #ifdef INADDR_ALLHOSTS_GROUP
4746 PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP",
4747 INADDR_ALLHOSTS_GROUP);
4748 #else
4749 PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
4750 #endif
4751 #ifdef INADDR_MAX_LOCAL_GROUP
4752 PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP",
4753 INADDR_MAX_LOCAL_GROUP);
4754 #else
4755 PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
4756 #endif
4757 #ifdef INADDR_NONE
4758 PyModule_AddIntConstant(m, "INADDR_NONE", INADDR_NONE);
4759 #else
4760 PyModule_AddIntConstant(m, "INADDR_NONE", 0xffffffff);
4761 #endif
4763 /* IPv4 [gs]etsockopt options */
4764 #ifdef IP_OPTIONS
4765 PyModule_AddIntConstant(m, "IP_OPTIONS", IP_OPTIONS);
4766 #endif
4767 #ifdef IP_HDRINCL
4768 PyModule_AddIntConstant(m, "IP_HDRINCL", IP_HDRINCL);
4769 #endif
4770 #ifdef IP_TOS
4771 PyModule_AddIntConstant(m, "IP_TOS", IP_TOS);
4772 #endif
4773 #ifdef IP_TTL
4774 PyModule_AddIntConstant(m, "IP_TTL", IP_TTL);
4775 #endif
4776 #ifdef IP_RECVOPTS
4777 PyModule_AddIntConstant(m, "IP_RECVOPTS", IP_RECVOPTS);
4778 #endif
4779 #ifdef IP_RECVRETOPTS
4780 PyModule_AddIntConstant(m, "IP_RECVRETOPTS", IP_RECVRETOPTS);
4781 #endif
4782 #ifdef IP_RECVDSTADDR
4783 PyModule_AddIntConstant(m, "IP_RECVDSTADDR", IP_RECVDSTADDR);
4784 #endif
4785 #ifdef IP_RETOPTS
4786 PyModule_AddIntConstant(m, "IP_RETOPTS", IP_RETOPTS);
4787 #endif
4788 #ifdef IP_MULTICAST_IF
4789 PyModule_AddIntConstant(m, "IP_MULTICAST_IF", IP_MULTICAST_IF);
4790 #endif
4791 #ifdef IP_MULTICAST_TTL
4792 PyModule_AddIntConstant(m, "IP_MULTICAST_TTL", IP_MULTICAST_TTL);
4793 #endif
4794 #ifdef IP_MULTICAST_LOOP
4795 PyModule_AddIntConstant(m, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
4796 #endif
4797 #ifdef IP_ADD_MEMBERSHIP
4798 PyModule_AddIntConstant(m, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
4799 #endif
4800 #ifdef IP_DROP_MEMBERSHIP
4801 PyModule_AddIntConstant(m, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
4802 #endif
4803 #ifdef IP_DEFAULT_MULTICAST_TTL
4804 PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_TTL",
4805 IP_DEFAULT_MULTICAST_TTL);
4806 #endif
4807 #ifdef IP_DEFAULT_MULTICAST_LOOP
4808 PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_LOOP",
4809 IP_DEFAULT_MULTICAST_LOOP);
4810 #endif
4811 #ifdef IP_MAX_MEMBERSHIPS
4812 PyModule_AddIntConstant(m, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS);
4813 #endif
4815 /* IPv6 [gs]etsockopt options, defined in RFC2553 */
4816 #ifdef IPV6_JOIN_GROUP
4817 PyModule_AddIntConstant(m, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP);
4818 #endif
4819 #ifdef IPV6_LEAVE_GROUP
4820 PyModule_AddIntConstant(m, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP);
4821 #endif
4822 #ifdef IPV6_MULTICAST_HOPS
4823 PyModule_AddIntConstant(m, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS);
4824 #endif
4825 #ifdef IPV6_MULTICAST_IF
4826 PyModule_AddIntConstant(m, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF);
4827 #endif
4828 #ifdef IPV6_MULTICAST_LOOP
4829 PyModule_AddIntConstant(m, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP);
4830 #endif
4831 #ifdef IPV6_UNICAST_HOPS
4832 PyModule_AddIntConstant(m, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS);
4833 #endif
4834 /* Additional IPV6 socket options, defined in RFC 3493 */
4835 #ifdef IPV6_V6ONLY
4836 PyModule_AddIntConstant(m, "IPV6_V6ONLY", IPV6_V6ONLY);
4837 #endif
4838 /* Advanced IPV6 socket options, from RFC 3542 */
4839 #ifdef IPV6_CHECKSUM
4840 PyModule_AddIntConstant(m, "IPV6_CHECKSUM", IPV6_CHECKSUM);
4841 #endif
4842 #ifdef IPV6_DONTFRAG
4843 PyModule_AddIntConstant(m, "IPV6_DONTFRAG", IPV6_DONTFRAG);
4844 #endif
4845 #ifdef IPV6_DSTOPTS
4846 PyModule_AddIntConstant(m, "IPV6_DSTOPTS", IPV6_DSTOPTS);
4847 #endif
4848 #ifdef IPV6_HOPLIMIT
4849 PyModule_AddIntConstant(m, "IPV6_HOPLIMIT", IPV6_HOPLIMIT);
4850 #endif
4851 #ifdef IPV6_HOPOPTS
4852 PyModule_AddIntConstant(m, "IPV6_HOPOPTS", IPV6_HOPOPTS);
4853 #endif
4854 #ifdef IPV6_NEXTHOP
4855 PyModule_AddIntConstant(m, "IPV6_NEXTHOP", IPV6_NEXTHOP);
4856 #endif
4857 #ifdef IPV6_PATHMTU
4858 PyModule_AddIntConstant(m, "IPV6_PATHMTU", IPV6_PATHMTU);
4859 #endif
4860 #ifdef IPV6_PKTINFO
4861 PyModule_AddIntConstant(m, "IPV6_PKTINFO", IPV6_PKTINFO);
4862 #endif
4863 #ifdef IPV6_RECVDSTOPTS
4864 PyModule_AddIntConstant(m, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS);
4865 #endif
4866 #ifdef IPV6_RECVHOPLIMIT
4867 PyModule_AddIntConstant(m, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT);
4868 #endif
4869 #ifdef IPV6_RECVHOPOPTS
4870 PyModule_AddIntConstant(m, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS);
4871 #endif
4872 #ifdef IPV6_RECVPKTINFO
4873 PyModule_AddIntConstant(m, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO);
4874 #endif
4875 #ifdef IPV6_RECVRTHDR
4876 PyModule_AddIntConstant(m, "IPV6_RECVRTHDR", IPV6_RECVRTHDR);
4877 #endif
4878 #ifdef IPV6_RECVTCLASS
4879 PyModule_AddIntConstant(m, "IPV6_RECVTCLASS", IPV6_RECVTCLASS);
4880 #endif
4881 #ifdef IPV6_RTHDR
4882 PyModule_AddIntConstant(m, "IPV6_RTHDR", IPV6_RTHDR);
4883 #endif
4884 #ifdef IPV6_RTHDRDSTOPTS
4885 PyModule_AddIntConstant(m, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS);
4886 #endif
4887 #ifdef IPV6_RTHDR_TYPE_0
4888 PyModule_AddIntConstant(m, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0);
4889 #endif
4890 #ifdef IPV6_RECVPATHMTU
4891 PyModule_AddIntConstant(m, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU);
4892 #endif
4893 #ifdef IPV6_TCLASS
4894 PyModule_AddIntConstant(m, "IPV6_TCLASS", IPV6_TCLASS);
4895 #endif
4896 #ifdef IPV6_USE_MIN_MTU
4897 PyModule_AddIntConstant(m, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU);
4898 #endif
4900 /* TCP options */
4901 #ifdef TCP_NODELAY
4902 PyModule_AddIntConstant(m, "TCP_NODELAY", TCP_NODELAY);
4903 #endif
4904 #ifdef TCP_MAXSEG
4905 PyModule_AddIntConstant(m, "TCP_MAXSEG", TCP_MAXSEG);
4906 #endif
4907 #ifdef TCP_CORK
4908 PyModule_AddIntConstant(m, "TCP_CORK", TCP_CORK);
4909 #endif
4910 #ifdef TCP_KEEPIDLE
4911 PyModule_AddIntConstant(m, "TCP_KEEPIDLE", TCP_KEEPIDLE);
4912 #endif
4913 #ifdef TCP_KEEPINTVL
4914 PyModule_AddIntConstant(m, "TCP_KEEPINTVL", TCP_KEEPINTVL);
4915 #endif
4916 #ifdef TCP_KEEPCNT
4917 PyModule_AddIntConstant(m, "TCP_KEEPCNT", TCP_KEEPCNT);
4918 #endif
4919 #ifdef TCP_SYNCNT
4920 PyModule_AddIntConstant(m, "TCP_SYNCNT", TCP_SYNCNT);
4921 #endif
4922 #ifdef TCP_LINGER2
4923 PyModule_AddIntConstant(m, "TCP_LINGER2", TCP_LINGER2);
4924 #endif
4925 #ifdef TCP_DEFER_ACCEPT
4926 PyModule_AddIntConstant(m, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT);
4927 #endif
4928 #ifdef TCP_WINDOW_CLAMP
4929 PyModule_AddIntConstant(m, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP);
4930 #endif
4931 #ifdef TCP_INFO
4932 PyModule_AddIntConstant(m, "TCP_INFO", TCP_INFO);
4933 #endif
4934 #ifdef TCP_QUICKACK
4935 PyModule_AddIntConstant(m, "TCP_QUICKACK", TCP_QUICKACK);
4936 #endif
4939 /* IPX options */
4940 #ifdef IPX_TYPE
4941 PyModule_AddIntConstant(m, "IPX_TYPE", IPX_TYPE);
4942 #endif
4944 /* get{addr,name}info parameters */
4945 #ifdef EAI_ADDRFAMILY
4946 PyModule_AddIntConstant(m, "EAI_ADDRFAMILY", EAI_ADDRFAMILY);
4947 #endif
4948 #ifdef EAI_AGAIN
4949 PyModule_AddIntConstant(m, "EAI_AGAIN", EAI_AGAIN);
4950 #endif
4951 #ifdef EAI_BADFLAGS
4952 PyModule_AddIntConstant(m, "EAI_BADFLAGS", EAI_BADFLAGS);
4953 #endif
4954 #ifdef EAI_FAIL
4955 PyModule_AddIntConstant(m, "EAI_FAIL", EAI_FAIL);
4956 #endif
4957 #ifdef EAI_FAMILY
4958 PyModule_AddIntConstant(m, "EAI_FAMILY", EAI_FAMILY);
4959 #endif
4960 #ifdef EAI_MEMORY
4961 PyModule_AddIntConstant(m, "EAI_MEMORY", EAI_MEMORY);
4962 #endif
4963 #ifdef EAI_NODATA
4964 PyModule_AddIntConstant(m, "EAI_NODATA", EAI_NODATA);
4965 #endif
4966 #ifdef EAI_NONAME
4967 PyModule_AddIntConstant(m, "EAI_NONAME", EAI_NONAME);
4968 #endif
4969 #ifdef EAI_OVERFLOW
4970 PyModule_AddIntConstant(m, "EAI_OVERFLOW", EAI_OVERFLOW);
4971 #endif
4972 #ifdef EAI_SERVICE
4973 PyModule_AddIntConstant(m, "EAI_SERVICE", EAI_SERVICE);
4974 #endif
4975 #ifdef EAI_SOCKTYPE
4976 PyModule_AddIntConstant(m, "EAI_SOCKTYPE", EAI_SOCKTYPE);
4977 #endif
4978 #ifdef EAI_SYSTEM
4979 PyModule_AddIntConstant(m, "EAI_SYSTEM", EAI_SYSTEM);
4980 #endif
4981 #ifdef EAI_BADHINTS
4982 PyModule_AddIntConstant(m, "EAI_BADHINTS", EAI_BADHINTS);
4983 #endif
4984 #ifdef EAI_PROTOCOL
4985 PyModule_AddIntConstant(m, "EAI_PROTOCOL", EAI_PROTOCOL);
4986 #endif
4987 #ifdef EAI_MAX
4988 PyModule_AddIntConstant(m, "EAI_MAX", EAI_MAX);
4989 #endif
4990 #ifdef AI_PASSIVE
4991 PyModule_AddIntConstant(m, "AI_PASSIVE", AI_PASSIVE);
4992 #endif
4993 #ifdef AI_CANONNAME
4994 PyModule_AddIntConstant(m, "AI_CANONNAME", AI_CANONNAME);
4995 #endif
4996 #ifdef AI_NUMERICHOST
4997 PyModule_AddIntConstant(m, "AI_NUMERICHOST", AI_NUMERICHOST);
4998 #endif
4999 #ifdef AI_NUMERICSERV
5000 PyModule_AddIntConstant(m, "AI_NUMERICSERV", AI_NUMERICSERV);
5001 #endif
5002 #ifdef AI_MASK
5003 PyModule_AddIntConstant(m, "AI_MASK", AI_MASK);
5004 #endif
5005 #ifdef AI_ALL
5006 PyModule_AddIntConstant(m, "AI_ALL", AI_ALL);
5007 #endif
5008 #ifdef AI_V4MAPPED_CFG
5009 PyModule_AddIntConstant(m, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG);
5010 #endif
5011 #ifdef AI_ADDRCONFIG
5012 PyModule_AddIntConstant(m, "AI_ADDRCONFIG", AI_ADDRCONFIG);
5013 #endif
5014 #ifdef AI_V4MAPPED
5015 PyModule_AddIntConstant(m, "AI_V4MAPPED", AI_V4MAPPED);
5016 #endif
5017 #ifdef AI_DEFAULT
5018 PyModule_AddIntConstant(m, "AI_DEFAULT", AI_DEFAULT);
5019 #endif
5020 #ifdef NI_MAXHOST
5021 PyModule_AddIntConstant(m, "NI_MAXHOST", NI_MAXHOST);
5022 #endif
5023 #ifdef NI_MAXSERV
5024 PyModule_AddIntConstant(m, "NI_MAXSERV", NI_MAXSERV);
5025 #endif
5026 #ifdef NI_NOFQDN
5027 PyModule_AddIntConstant(m, "NI_NOFQDN", NI_NOFQDN);
5028 #endif
5029 #ifdef NI_NUMERICHOST
5030 PyModule_AddIntConstant(m, "NI_NUMERICHOST", NI_NUMERICHOST);
5031 #endif
5032 #ifdef NI_NAMEREQD
5033 PyModule_AddIntConstant(m, "NI_NAMEREQD", NI_NAMEREQD);
5034 #endif
5035 #ifdef NI_NUMERICSERV
5036 PyModule_AddIntConstant(m, "NI_NUMERICSERV", NI_NUMERICSERV);
5037 #endif
5038 #ifdef NI_DGRAM
5039 PyModule_AddIntConstant(m, "NI_DGRAM", NI_DGRAM);
5040 #endif
5042 /* shutdown() parameters */
5043 #ifdef SHUT_RD
5044 PyModule_AddIntConstant(m, "SHUT_RD", SHUT_RD);
5045 #elif defined(SD_RECEIVE)
5046 PyModule_AddIntConstant(m, "SHUT_RD", SD_RECEIVE);
5047 #else
5048 PyModule_AddIntConstant(m, "SHUT_RD", 0);
5049 #endif
5050 #ifdef SHUT_WR
5051 PyModule_AddIntConstant(m, "SHUT_WR", SHUT_WR);
5052 #elif defined(SD_SEND)
5053 PyModule_AddIntConstant(m, "SHUT_WR", SD_SEND);
5054 #else
5055 PyModule_AddIntConstant(m, "SHUT_WR", 1);
5056 #endif
5057 #ifdef SHUT_RDWR
5058 PyModule_AddIntConstant(m, "SHUT_RDWR", SHUT_RDWR);
5059 #elif defined(SD_BOTH)
5060 PyModule_AddIntConstant(m, "SHUT_RDWR", SD_BOTH);
5061 #else
5062 PyModule_AddIntConstant(m, "SHUT_RDWR", 2);
5063 #endif
5065 /* Initialize gethostbyname lock */
5066 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
5067 netdb_lock = PyThread_allocate_lock();
5068 #endif
5072 #ifndef HAVE_INET_PTON
5074 /* Simplistic emulation code for inet_pton that only works for IPv4 */
5075 /* These are not exposed because they do not set errno properly */
5078 inet_pton(int af, const char *src, void *dst)
5080 if (af == AF_INET) {
5081 long packed_addr;
5082 packed_addr = inet_addr(src);
5083 if (packed_addr == INADDR_NONE)
5084 return 0;
5085 memcpy(dst, &packed_addr, 4);
5086 return 1;
5088 /* Should set errno to EAFNOSUPPORT */
5089 return -1;
5092 const char *
5093 inet_ntop(int af, const void *src, char *dst, socklen_t size)
5095 if (af == AF_INET) {
5096 struct in_addr packed_addr;
5097 if (size < 16)
5098 /* Should set errno to ENOSPC. */
5099 return NULL;
5100 memcpy(&packed_addr, src, sizeof(packed_addr));
5101 return strncpy(dst, inet_ntoa(packed_addr), size);
5103 /* Should set errno to EAFNOSUPPORT */
5104 return NULL;
5107 #endif