Updates of recent changes to logging.
[python.git] / Modules / socketmodule.c
blob21270a3d9f47b3200b0f2c53828a163c93270ac2
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 BTPROTO_HCI BLUETOOTH_PROTO_HCI
366 #define sockaddr_l2 sockaddr_l2cap
367 #define sockaddr_rc sockaddr_rfcomm
368 #define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb)
369 #define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)
370 #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
371 #elif defined(__NetBSD__)
372 #define sockaddr_l2 sockaddr_bt
373 #define sockaddr_rc sockaddr_bt
374 #define sockaddr_hci sockaddr_bt
375 #define sockaddr_sco sockaddr_bt
376 #define _BT_L2_MEMB(sa, memb) ((sa)->bt_##memb)
377 #define _BT_RC_MEMB(sa, memb) ((sa)->bt_##memb)
378 #define _BT_HCI_MEMB(sa, memb) ((sa)->bt_##memb)
379 #define _BT_SCO_MEMB(sa, memb) ((sa)->bt_##memb)
380 #else
381 #define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb)
382 #define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb)
383 #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
384 #define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)
385 #endif
386 #endif
388 #ifdef __VMS
389 /* TCP/IP Services for VMS uses a maximum send/recv buffer length */
390 #define SEGMENT_SIZE (32 * 1024 -1)
391 #endif
393 #define SAS2SA(x) ((struct sockaddr *)(x))
396 * Constants for getnameinfo()
398 #if !defined(NI_MAXHOST)
399 #define NI_MAXHOST 1025
400 #endif
401 #if !defined(NI_MAXSERV)
402 #define NI_MAXSERV 32
403 #endif
405 /* XXX There's a problem here: *static* functions are not supposed to have
406 a Py prefix (or use CapitalizedWords). Later... */
408 /* Global variable holding the exception type for errors detected
409 by this module (but not argument type or memory errors, etc.). */
410 static PyObject *socket_error;
411 static PyObject *socket_herror;
412 static PyObject *socket_gaierror;
413 static PyObject *socket_timeout;
415 #ifdef RISCOS
416 /* Global variable which is !=0 if Python is running in a RISC OS taskwindow */
417 static int taskwindow;
418 #endif
420 /* A forward reference to the socket type object.
421 The sock_type variable contains pointers to various functions,
422 some of which call new_sockobject(), which uses sock_type, so
423 there has to be a circular reference. */
424 static PyTypeObject sock_type;
426 #if defined(HAVE_POLL_H)
427 #include <poll.h>
428 #elif defined(HAVE_SYS_POLL_H)
429 #include <sys/poll.h>
430 #endif
432 #ifdef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
433 /* Platform can select file descriptors beyond FD_SETSIZE */
434 #define IS_SELECTABLE(s) 1
435 #elif defined(HAVE_POLL)
436 /* Instead of select(), we'll use poll() since poll() works on any fd. */
437 #define IS_SELECTABLE(s) 1
438 /* Can we call select() with this socket without a buffer overrun? */
439 #else
440 /* POSIX says selecting file descriptors beyond FD_SETSIZE
441 has undefined behaviour. If there's no timeout left, we don't have to
442 call select, so it's a safe, little white lie. */
443 #define IS_SELECTABLE(s) ((s)->sock_fd < FD_SETSIZE || s->sock_timeout <= 0.0)
444 #endif
446 static PyObject*
447 select_error(void)
449 PyErr_SetString(socket_error, "unable to select on socket");
450 return NULL;
453 /* Convenience function to raise an error according to errno
454 and return a NULL pointer from a function. */
456 static PyObject *
457 set_error(void)
459 #ifdef MS_WINDOWS
460 int err_no = WSAGetLastError();
461 static struct {
462 int no;
463 const char *msg;
464 } *msgp, msgs[] = {
465 {WSAEINTR, "Interrupted system call"},
466 {WSAEBADF, "Bad file descriptor"},
467 {WSAEACCES, "Permission denied"},
468 {WSAEFAULT, "Bad address"},
469 {WSAEINVAL, "Invalid argument"},
470 {WSAEMFILE, "Too many open files"},
471 {WSAEWOULDBLOCK,
472 "The socket operation could not complete "
473 "without blocking"},
474 {WSAEINPROGRESS, "Operation now in progress"},
475 {WSAEALREADY, "Operation already in progress"},
476 {WSAENOTSOCK, "Socket operation on non-socket"},
477 {WSAEDESTADDRREQ, "Destination address required"},
478 {WSAEMSGSIZE, "Message too long"},
479 {WSAEPROTOTYPE, "Protocol wrong type for socket"},
480 {WSAENOPROTOOPT, "Protocol not available"},
481 {WSAEPROTONOSUPPORT, "Protocol not supported"},
482 {WSAESOCKTNOSUPPORT, "Socket type not supported"},
483 {WSAEOPNOTSUPP, "Operation not supported"},
484 {WSAEPFNOSUPPORT, "Protocol family not supported"},
485 {WSAEAFNOSUPPORT, "Address family not supported"},
486 {WSAEADDRINUSE, "Address already in use"},
487 {WSAEADDRNOTAVAIL, "Can't assign requested address"},
488 {WSAENETDOWN, "Network is down"},
489 {WSAENETUNREACH, "Network is unreachable"},
490 {WSAENETRESET, "Network dropped connection on reset"},
491 {WSAECONNABORTED, "Software caused connection abort"},
492 {WSAECONNRESET, "Connection reset by peer"},
493 {WSAENOBUFS, "No buffer space available"},
494 {WSAEISCONN, "Socket is already connected"},
495 {WSAENOTCONN, "Socket is not connected"},
496 {WSAESHUTDOWN, "Can't send after socket shutdown"},
497 {WSAETOOMANYREFS, "Too many references: can't splice"},
498 {WSAETIMEDOUT, "Operation timed out"},
499 {WSAECONNREFUSED, "Connection refused"},
500 {WSAELOOP, "Too many levels of symbolic links"},
501 {WSAENAMETOOLONG, "File name too long"},
502 {WSAEHOSTDOWN, "Host is down"},
503 {WSAEHOSTUNREACH, "No route to host"},
504 {WSAENOTEMPTY, "Directory not empty"},
505 {WSAEPROCLIM, "Too many processes"},
506 {WSAEUSERS, "Too many users"},
507 {WSAEDQUOT, "Disc quota exceeded"},
508 {WSAESTALE, "Stale NFS file handle"},
509 {WSAEREMOTE, "Too many levels of remote in path"},
510 {WSASYSNOTREADY, "Network subsystem is unvailable"},
511 {WSAVERNOTSUPPORTED, "WinSock version is not supported"},
512 {WSANOTINITIALISED,
513 "Successful WSAStartup() not yet performed"},
514 {WSAEDISCON, "Graceful shutdown in progress"},
515 /* Resolver errors */
516 {WSAHOST_NOT_FOUND, "No such host is known"},
517 {WSATRY_AGAIN, "Host not found, or server failed"},
518 {WSANO_RECOVERY, "Unexpected server error encountered"},
519 {WSANO_DATA, "Valid name without requested data"},
520 {WSANO_ADDRESS, "No address, look for MX record"},
521 {0, NULL}
523 if (err_no) {
524 PyObject *v;
525 const char *msg = "winsock error";
527 for (msgp = msgs; msgp->msg; msgp++) {
528 if (err_no == msgp->no) {
529 msg = msgp->msg;
530 break;
534 v = Py_BuildValue("(is)", err_no, msg);
535 if (v != NULL) {
536 PyErr_SetObject(socket_error, v);
537 Py_DECREF(v);
539 return NULL;
541 else
542 #endif
544 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
545 if (sock_errno() != NO_ERROR) {
546 APIRET rc;
547 ULONG msglen;
548 char outbuf[100];
549 int myerrorcode = sock_errno();
551 /* Retrieve socket-related error message from MPTN.MSG file */
552 rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf),
553 myerrorcode - SOCBASEERR + 26,
554 "mptn.msg",
555 &msglen);
556 if (rc == NO_ERROR) {
557 PyObject *v;
559 /* OS/2 doesn't guarantee a terminator */
560 outbuf[msglen] = '\0';
561 if (strlen(outbuf) > 0) {
562 /* If non-empty msg, trim CRLF */
563 char *lastc = &outbuf[ strlen(outbuf)-1 ];
564 while (lastc > outbuf &&
565 isspace(Py_CHARMASK(*lastc))) {
566 /* Trim trailing whitespace (CRLF) */
567 *lastc-- = '\0';
570 v = Py_BuildValue("(is)", myerrorcode, outbuf);
571 if (v != NULL) {
572 PyErr_SetObject(socket_error, v);
573 Py_DECREF(v);
575 return NULL;
578 #endif
580 #if defined(RISCOS)
581 if (_inet_error.errnum != NULL) {
582 PyObject *v;
583 v = Py_BuildValue("(is)", errno, _inet_err());
584 if (v != NULL) {
585 PyErr_SetObject(socket_error, v);
586 Py_DECREF(v);
588 return NULL;
590 #endif
592 return PyErr_SetFromErrno(socket_error);
596 static PyObject *
597 set_herror(int h_error)
599 PyObject *v;
601 #ifdef HAVE_HSTRERROR
602 v = Py_BuildValue("(is)", h_error, (char *)hstrerror(h_error));
603 #else
604 v = Py_BuildValue("(is)", h_error, "host not found");
605 #endif
606 if (v != NULL) {
607 PyErr_SetObject(socket_herror, v);
608 Py_DECREF(v);
611 return NULL;
615 static PyObject *
616 set_gaierror(int error)
618 PyObject *v;
620 #ifdef EAI_SYSTEM
621 /* EAI_SYSTEM is not available on Windows XP. */
622 if (error == EAI_SYSTEM)
623 return set_error();
624 #endif
626 #ifdef HAVE_GAI_STRERROR
627 v = Py_BuildValue("(is)", error, gai_strerror(error));
628 #else
629 v = Py_BuildValue("(is)", error, "getaddrinfo failed");
630 #endif
631 if (v != NULL) {
632 PyErr_SetObject(socket_gaierror, v);
633 Py_DECREF(v);
636 return NULL;
639 #ifdef __VMS
640 /* Function to send in segments */
641 static int
642 sendsegmented(int sock_fd, char *buf, int len, int flags)
644 int n = 0;
645 int remaining = len;
647 while (remaining > 0) {
648 unsigned int segment;
650 segment = (remaining >= SEGMENT_SIZE ? SEGMENT_SIZE : remaining);
651 n = send(sock_fd, buf, segment, flags);
652 if (n < 0) {
653 return n;
655 remaining -= segment;
656 buf += segment;
657 } /* end while */
659 return len;
661 #endif
663 /* Function to perform the setting of socket blocking mode
664 internally. block = (1 | 0). */
665 static int
666 internal_setblocking(PySocketSockObject *s, int block)
668 #ifndef RISCOS
669 #ifndef MS_WINDOWS
670 int delay_flag;
671 #endif
672 #endif
674 Py_BEGIN_ALLOW_THREADS
675 #ifdef __BEOS__
676 block = !block;
677 setsockopt(s->sock_fd, SOL_SOCKET, SO_NONBLOCK,
678 (void *)(&block), sizeof(int));
679 #else
680 #ifndef RISCOS
681 #ifndef MS_WINDOWS
682 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
683 block = !block;
684 ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block));
685 #elif defined(__VMS)
686 block = !block;
687 ioctl(s->sock_fd, FIONBIO, (unsigned int *)&block);
688 #else /* !PYOS_OS2 && !__VMS */
689 delay_flag = fcntl(s->sock_fd, F_GETFL, 0);
690 if (block)
691 delay_flag &= (~O_NONBLOCK);
692 else
693 delay_flag |= O_NONBLOCK;
694 fcntl(s->sock_fd, F_SETFL, delay_flag);
695 #endif /* !PYOS_OS2 */
696 #else /* MS_WINDOWS */
697 block = !block;
698 ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
699 #endif /* MS_WINDOWS */
700 #else /* RISCOS */
701 block = !block;
702 socketioctl(s->sock_fd, FIONBIO, (u_long*)&block);
703 #endif /* RISCOS */
704 #endif /* __BEOS__ */
705 Py_END_ALLOW_THREADS
707 /* Since these don't return anything */
708 return 1;
711 /* Do a select()/poll() on the socket, if necessary (sock_timeout > 0).
712 The argument writing indicates the direction.
713 This does not raise an exception; we'll let our caller do that
714 after they've reacquired the interpreter lock.
715 Returns 1 on timeout, -1 on error, 0 otherwise. */
716 static int
717 internal_select(PySocketSockObject *s, int writing)
719 int n;
721 /* Nothing to do unless we're in timeout mode (not non-blocking) */
722 if (s->sock_timeout <= 0.0)
723 return 0;
725 /* Guard against closed socket */
726 if (s->sock_fd < 0)
727 return 0;
729 /* Prefer poll, if available, since you can poll() any fd
730 * which can't be done with select(). */
731 #ifdef HAVE_POLL
733 struct pollfd pollfd;
734 int timeout;
736 pollfd.fd = s->sock_fd;
737 pollfd.events = writing ? POLLOUT : POLLIN;
739 /* s->sock_timeout is in seconds, timeout in ms */
740 timeout = (int)(s->sock_timeout * 1000 + 0.5);
741 n = poll(&pollfd, 1, timeout);
743 #else
745 /* Construct the arguments to select */
746 fd_set fds;
747 struct timeval tv;
748 tv.tv_sec = (int)s->sock_timeout;
749 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
750 FD_ZERO(&fds);
751 FD_SET(s->sock_fd, &fds);
753 /* See if the socket is ready */
754 if (writing)
755 n = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
756 else
757 n = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
759 #endif
761 if (n < 0)
762 return -1;
763 if (n == 0)
764 return 1;
765 return 0;
768 /* Initialize a new socket object. */
770 static double defaulttimeout = -1.0; /* Default timeout for new sockets */
772 PyMODINIT_FUNC
773 init_sockobject(PySocketSockObject *s,
774 SOCKET_T fd, int family, int type, int proto)
776 #ifdef RISCOS
777 int block = 1;
778 #endif
779 s->sock_fd = fd;
780 s->sock_family = family;
781 s->sock_type = type;
782 s->sock_proto = proto;
783 s->sock_timeout = defaulttimeout;
785 s->errorhandler = &set_error;
787 if (defaulttimeout >= 0.0)
788 internal_setblocking(s, 0);
790 #ifdef RISCOS
791 if (taskwindow)
792 socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
793 #endif
797 /* Create a new socket object.
798 This just creates the object and initializes it.
799 If the creation fails, return NULL and set an exception (implicit
800 in NEWOBJ()). */
802 static PySocketSockObject *
803 new_sockobject(SOCKET_T fd, int family, int type, int proto)
805 PySocketSockObject *s;
806 s = (PySocketSockObject *)
807 PyType_GenericNew(&sock_type, NULL, NULL);
808 if (s != NULL)
809 init_sockobject(s, fd, family, type, proto);
810 return s;
814 /* Lock to allow python interpreter to continue, but only allow one
815 thread to be in gethostbyname or getaddrinfo */
816 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
817 PyThread_type_lock netdb_lock;
818 #endif
821 /* Convert a string specifying a host name or one of a few symbolic
822 names to a numeric IP address. This usually calls gethostbyname()
823 to do the work; the names "" and "<broadcast>" are special.
824 Return the length (IPv4 should be 4 bytes), or negative if
825 an error occurred; then an exception is raised. */
827 static int
828 setipaddr(char *name, struct sockaddr *addr_ret, size_t addr_ret_size, int af)
830 struct addrinfo hints, *res;
831 int error;
832 int d1, d2, d3, d4;
833 char ch;
835 memset((void *) addr_ret, '\0', sizeof(*addr_ret));
836 if (name[0] == '\0') {
837 int siz;
838 memset(&hints, 0, sizeof(hints));
839 hints.ai_family = af;
840 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
841 hints.ai_flags = AI_PASSIVE;
842 Py_BEGIN_ALLOW_THREADS
843 ACQUIRE_GETADDRINFO_LOCK
844 error = getaddrinfo(NULL, "0", &hints, &res);
845 Py_END_ALLOW_THREADS
846 /* We assume that those thread-unsafe getaddrinfo() versions
847 *are* safe regarding their return value, ie. that a
848 subsequent call to getaddrinfo() does not destroy the
849 outcome of the first call. */
850 RELEASE_GETADDRINFO_LOCK
851 if (error) {
852 set_gaierror(error);
853 return -1;
855 switch (res->ai_family) {
856 case AF_INET:
857 siz = 4;
858 break;
859 #ifdef ENABLE_IPV6
860 case AF_INET6:
861 siz = 16;
862 break;
863 #endif
864 default:
865 freeaddrinfo(res);
866 PyErr_SetString(socket_error,
867 "unsupported address family");
868 return -1;
870 if (res->ai_next) {
871 freeaddrinfo(res);
872 PyErr_SetString(socket_error,
873 "wildcard resolved to multiple address");
874 return -1;
876 if (res->ai_addrlen < addr_ret_size)
877 addr_ret_size = res->ai_addrlen;
878 memcpy(addr_ret, res->ai_addr, addr_ret_size);
879 freeaddrinfo(res);
880 return siz;
882 if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
883 struct sockaddr_in *sin;
884 if (af != AF_INET && af != AF_UNSPEC) {
885 PyErr_SetString(socket_error,
886 "address family mismatched");
887 return -1;
889 sin = (struct sockaddr_in *)addr_ret;
890 memset((void *) sin, '\0', sizeof(*sin));
891 sin->sin_family = AF_INET;
892 #ifdef HAVE_SOCKADDR_SA_LEN
893 sin->sin_len = sizeof(*sin);
894 #endif
895 sin->sin_addr.s_addr = INADDR_BROADCAST;
896 return sizeof(sin->sin_addr);
898 if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 &&
899 0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 &&
900 0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) {
901 struct sockaddr_in *sin;
902 sin = (struct sockaddr_in *)addr_ret;
903 sin->sin_addr.s_addr = htonl(
904 ((long) d1 << 24) | ((long) d2 << 16) |
905 ((long) d3 << 8) | ((long) d4 << 0));
906 sin->sin_family = AF_INET;
907 #ifdef HAVE_SOCKADDR_SA_LEN
908 sin->sin_len = sizeof(*sin);
909 #endif
910 return 4;
912 memset(&hints, 0, sizeof(hints));
913 hints.ai_family = af;
914 Py_BEGIN_ALLOW_THREADS
915 ACQUIRE_GETADDRINFO_LOCK
916 error = getaddrinfo(name, NULL, &hints, &res);
917 #if defined(__digital__) && defined(__unix__)
918 if (error == EAI_NONAME && af == AF_UNSPEC) {
919 /* On Tru64 V5.1, numeric-to-addr conversion fails
920 if no address family is given. Assume IPv4 for now.*/
921 hints.ai_family = AF_INET;
922 error = getaddrinfo(name, NULL, &hints, &res);
924 #endif
925 Py_END_ALLOW_THREADS
926 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
927 if (error) {
928 set_gaierror(error);
929 return -1;
931 if (res->ai_addrlen < addr_ret_size)
932 addr_ret_size = res->ai_addrlen;
933 memcpy((char *) addr_ret, res->ai_addr, addr_ret_size);
934 freeaddrinfo(res);
935 switch (addr_ret->sa_family) {
936 case AF_INET:
937 return 4;
938 #ifdef ENABLE_IPV6
939 case AF_INET6:
940 return 16;
941 #endif
942 default:
943 PyErr_SetString(socket_error, "unknown address family");
944 return -1;
949 /* Create a string object representing an IP address.
950 This is always a string of the form 'dd.dd.dd.dd' (with variable
951 size numbers). */
953 static PyObject *
954 makeipaddr(struct sockaddr *addr, int addrlen)
956 char buf[NI_MAXHOST];
957 int error;
959 error = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0,
960 NI_NUMERICHOST);
961 if (error) {
962 set_gaierror(error);
963 return NULL;
965 return PyString_FromString(buf);
969 #ifdef USE_BLUETOOTH
970 /* Convert a string representation of a Bluetooth address into a numeric
971 address. Returns the length (6), or raises an exception and returns -1 if
972 an error occurred. */
974 static int
975 setbdaddr(char *name, bdaddr_t *bdaddr)
977 unsigned int b0, b1, b2, b3, b4, b5;
978 char ch;
979 int n;
981 n = sscanf(name, "%X:%X:%X:%X:%X:%X%c",
982 &b5, &b4, &b3, &b2, &b1, &b0, &ch);
983 if (n == 6 && (b0 | b1 | b2 | b3 | b4 | b5) < 256) {
984 bdaddr->b[0] = b0;
985 bdaddr->b[1] = b1;
986 bdaddr->b[2] = b2;
987 bdaddr->b[3] = b3;
988 bdaddr->b[4] = b4;
989 bdaddr->b[5] = b5;
990 return 6;
991 } else {
992 PyErr_SetString(socket_error, "bad bluetooth address");
993 return -1;
997 /* Create a string representation of the Bluetooth address. This is always a
998 string of the form 'XX:XX:XX:XX:XX:XX' where XX is a two digit hexadecimal
999 value (zero padded if necessary). */
1001 static PyObject *
1002 makebdaddr(bdaddr_t *bdaddr)
1004 char buf[(6 * 2) + 5 + 1];
1006 sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
1007 bdaddr->b[5], bdaddr->b[4], bdaddr->b[3],
1008 bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]);
1009 return PyString_FromString(buf);
1011 #endif
1014 /* Create an object representing the given socket address,
1015 suitable for passing it back to bind(), connect() etc.
1016 The family field of the sockaddr structure is inspected
1017 to determine what kind of address it really is. */
1019 /*ARGSUSED*/
1020 static PyObject *
1021 makesockaddr(int sockfd, struct sockaddr *addr, int addrlen, int proto)
1023 if (addrlen == 0) {
1024 /* No address -- may be recvfrom() from known socket */
1025 Py_INCREF(Py_None);
1026 return Py_None;
1029 #ifdef __BEOS__
1030 /* XXX: BeOS version of accept() doesn't set family correctly */
1031 addr->sa_family = AF_INET;
1032 #endif
1034 switch (addr->sa_family) {
1036 case AF_INET:
1038 struct sockaddr_in *a;
1039 PyObject *addrobj = makeipaddr(addr, sizeof(*a));
1040 PyObject *ret = NULL;
1041 if (addrobj) {
1042 a = (struct sockaddr_in *)addr;
1043 ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
1044 Py_DECREF(addrobj);
1046 return ret;
1049 #if defined(AF_UNIX)
1050 case AF_UNIX:
1052 struct sockaddr_un *a = (struct sockaddr_un *) addr;
1053 #ifdef linux
1054 if (a->sun_path[0] == 0) { /* Linux abstract namespace */
1055 addrlen -= (sizeof(*a) - sizeof(a->sun_path));
1056 return PyString_FromStringAndSize(a->sun_path,
1057 addrlen);
1059 else
1060 #endif /* linux */
1062 /* regular NULL-terminated string */
1063 return PyString_FromString(a->sun_path);
1066 #endif /* AF_UNIX */
1068 #if defined(AF_NETLINK)
1069 case AF_NETLINK:
1071 struct sockaddr_nl *a = (struct sockaddr_nl *) addr;
1072 return Py_BuildValue("II", a->nl_pid, a->nl_groups);
1074 #endif /* AF_NETLINK */
1076 #ifdef ENABLE_IPV6
1077 case AF_INET6:
1079 struct sockaddr_in6 *a;
1080 PyObject *addrobj = makeipaddr(addr, sizeof(*a));
1081 PyObject *ret = NULL;
1082 if (addrobj) {
1083 a = (struct sockaddr_in6 *)addr;
1084 ret = Py_BuildValue("Oiii",
1085 addrobj,
1086 ntohs(a->sin6_port),
1087 a->sin6_flowinfo,
1088 a->sin6_scope_id);
1089 Py_DECREF(addrobj);
1091 return ret;
1093 #endif
1095 #ifdef USE_BLUETOOTH
1096 case AF_BLUETOOTH:
1097 switch (proto) {
1099 case BTPROTO_L2CAP:
1101 struct sockaddr_l2 *a = (struct sockaddr_l2 *) addr;
1102 PyObject *addrobj = makebdaddr(&_BT_L2_MEMB(a, bdaddr));
1103 PyObject *ret = NULL;
1104 if (addrobj) {
1105 ret = Py_BuildValue("Oi",
1106 addrobj,
1107 _BT_L2_MEMB(a, psm));
1108 Py_DECREF(addrobj);
1110 return ret;
1113 case BTPROTO_RFCOMM:
1115 struct sockaddr_rc *a = (struct sockaddr_rc *) addr;
1116 PyObject *addrobj = makebdaddr(&_BT_RC_MEMB(a, bdaddr));
1117 PyObject *ret = NULL;
1118 if (addrobj) {
1119 ret = Py_BuildValue("Oi",
1120 addrobj,
1121 _BT_RC_MEMB(a, channel));
1122 Py_DECREF(addrobj);
1124 return ret;
1127 case BTPROTO_HCI:
1129 struct sockaddr_hci *a = (struct sockaddr_hci *) addr;
1130 PyObject *ret = NULL;
1131 ret = Py_BuildValue("i", _BT_HCI_MEMB(a, dev));
1132 return ret;
1135 #if !defined(__FreeBSD__)
1136 case BTPROTO_SCO:
1138 struct sockaddr_sco *a = (struct sockaddr_sco *) addr;
1139 return makebdaddr(&_BT_SCO_MEMB(a, bdaddr));
1141 #endif
1144 #endif
1146 #ifdef HAVE_NETPACKET_PACKET_H
1147 case AF_PACKET:
1149 struct sockaddr_ll *a = (struct sockaddr_ll *)addr;
1150 char *ifname = "";
1151 struct ifreq ifr;
1152 /* need to look up interface name give index */
1153 if (a->sll_ifindex) {
1154 ifr.ifr_ifindex = a->sll_ifindex;
1155 if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0)
1156 ifname = ifr.ifr_name;
1158 return Py_BuildValue("shbhs#",
1159 ifname,
1160 ntohs(a->sll_protocol),
1161 a->sll_pkttype,
1162 a->sll_hatype,
1163 a->sll_addr,
1164 a->sll_halen);
1166 #endif
1168 /* More cases here... */
1170 default:
1171 /* If we don't know the address family, don't raise an
1172 exception -- return it as a tuple. */
1173 return Py_BuildValue("is#",
1174 addr->sa_family,
1175 addr->sa_data,
1176 sizeof(addr->sa_data));
1182 /* Parse a socket address argument according to the socket object's
1183 address family. Return 1 if the address was in the proper format,
1184 0 of not. The address is returned through addr_ret, its length
1185 through len_ret. */
1187 static int
1188 getsockaddrarg(PySocketSockObject *s, PyObject *args,
1189 struct sockaddr *addr_ret, int *len_ret)
1191 switch (s->sock_family) {
1193 #if defined(AF_UNIX)
1194 case AF_UNIX:
1196 struct sockaddr_un* addr;
1197 char *path;
1198 int len;
1199 if (!PyArg_Parse(args, "t#", &path, &len))
1200 return 0;
1202 addr = (struct sockaddr_un*)addr_ret;
1203 #ifdef linux
1204 if (len > 0 && path[0] == 0) {
1205 /* Linux abstract namespace extension */
1206 if (len > sizeof addr->sun_path) {
1207 PyErr_SetString(socket_error,
1208 "AF_UNIX path too long");
1209 return 0;
1212 else
1213 #endif /* linux */
1215 /* regular NULL-terminated string */
1216 if (len >= sizeof addr->sun_path) {
1217 PyErr_SetString(socket_error,
1218 "AF_UNIX path too long");
1219 return 0;
1221 addr->sun_path[len] = 0;
1223 addr->sun_family = s->sock_family;
1224 memcpy(addr->sun_path, path, len);
1225 #if defined(PYOS_OS2)
1226 *len_ret = sizeof(*addr);
1227 #else
1228 *len_ret = len + sizeof(*addr) - sizeof(addr->sun_path);
1229 #endif
1230 return 1;
1232 #endif /* AF_UNIX */
1234 #if defined(AF_NETLINK)
1235 case AF_NETLINK:
1237 struct sockaddr_nl* addr;
1238 int pid, groups;
1239 addr = (struct sockaddr_nl *)addr_ret;
1240 if (!PyTuple_Check(args)) {
1241 PyErr_Format(
1242 PyExc_TypeError,
1243 "getsockaddrarg: "
1244 "AF_NETLINK address must be tuple, not %.500s",
1245 args->ob_type->tp_name);
1246 return 0;
1248 if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &pid, &groups))
1249 return 0;
1250 addr->nl_family = AF_NETLINK;
1251 addr->nl_pid = pid;
1252 addr->nl_groups = groups;
1253 *len_ret = sizeof(*addr);
1254 return 1;
1256 #endif
1258 case AF_INET:
1260 struct sockaddr_in* addr;
1261 char *host;
1262 int port, result;
1263 if (!PyTuple_Check(args)) {
1264 PyErr_Format(
1265 PyExc_TypeError,
1266 "getsockaddrarg: "
1267 "AF_INET address must be tuple, not %.500s",
1268 args->ob_type->tp_name);
1269 return 0;
1271 if (!PyArg_ParseTuple(args, "eti:getsockaddrarg",
1272 "idna", &host, &port))
1273 return 0;
1274 addr=(struct sockaddr_in*)addr_ret;
1275 result = setipaddr(host, (struct sockaddr *)addr,
1276 sizeof(*addr), AF_INET);
1277 PyMem_Free(host);
1278 if (result < 0)
1279 return 0;
1280 addr->sin_family = AF_INET;
1281 addr->sin_port = htons((short)port);
1282 *len_ret = sizeof *addr;
1283 return 1;
1286 #ifdef ENABLE_IPV6
1287 case AF_INET6:
1289 struct sockaddr_in6* addr;
1290 char *host;
1291 int port, flowinfo, scope_id, result;
1292 flowinfo = scope_id = 0;
1293 if (!PyTuple_Check(args)) {
1294 PyErr_Format(
1295 PyExc_TypeError,
1296 "getsockaddrarg: "
1297 "AF_INET6 address must be tuple, not %.500s",
1298 args->ob_type->tp_name);
1299 return 0;
1301 if (!PyArg_ParseTuple(args, "eti|ii",
1302 "idna", &host, &port, &flowinfo,
1303 &scope_id)) {
1304 return 0;
1306 addr = (struct sockaddr_in6*)addr_ret;
1307 result = setipaddr(host, (struct sockaddr *)addr,
1308 sizeof(*addr), AF_INET6);
1309 PyMem_Free(host);
1310 if (result < 0)
1311 return 0;
1312 addr->sin6_family = s->sock_family;
1313 addr->sin6_port = htons((short)port);
1314 addr->sin6_flowinfo = flowinfo;
1315 addr->sin6_scope_id = scope_id;
1316 *len_ret = sizeof *addr;
1317 return 1;
1319 #endif
1321 #ifdef USE_BLUETOOTH
1322 case AF_BLUETOOTH:
1324 switch (s->sock_proto) {
1325 case BTPROTO_L2CAP:
1327 struct sockaddr_l2 *addr;
1328 char *straddr;
1330 addr = (struct sockaddr_l2 *)addr_ret;
1331 _BT_L2_MEMB(addr, family) = AF_BLUETOOTH;
1332 if (!PyArg_ParseTuple(args, "si", &straddr,
1333 &_BT_L2_MEMB(addr, psm))) {
1334 PyErr_SetString(socket_error, "getsockaddrarg: "
1335 "wrong format");
1336 return 0;
1338 if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0)
1339 return 0;
1341 *len_ret = sizeof *addr;
1342 return 1;
1344 case BTPROTO_RFCOMM:
1346 struct sockaddr_rc *addr;
1347 char *straddr;
1349 addr = (struct sockaddr_rc *)addr_ret;
1350 _BT_RC_MEMB(addr, family) = AF_BLUETOOTH;
1351 if (!PyArg_ParseTuple(args, "si", &straddr,
1352 &_BT_RC_MEMB(addr, channel))) {
1353 PyErr_SetString(socket_error, "getsockaddrarg: "
1354 "wrong format");
1355 return 0;
1357 if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0)
1358 return 0;
1360 *len_ret = sizeof *addr;
1361 return 1;
1363 case BTPROTO_HCI:
1365 struct sockaddr_hci *addr = (struct sockaddr_hci *)addr_ret;
1366 _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH;
1367 if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) {
1368 PyErr_SetString(socket_error, "getsockaddrarg: "
1369 "wrong format");
1370 return 0;
1372 *len_ret = sizeof *addr;
1373 return 1;
1375 #if !defined(__FreeBSD__)
1376 case BTPROTO_SCO:
1378 struct sockaddr_sco *addr;
1379 char *straddr;
1381 addr = (struct sockaddr_sco *)addr_ret;
1382 _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH;
1383 straddr = PyString_AsString(args);
1384 if (straddr == NULL) {
1385 PyErr_SetString(socket_error, "getsockaddrarg: "
1386 "wrong format");
1387 return 0;
1389 if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0)
1390 return 0;
1392 *len_ret = sizeof *addr;
1393 return 1;
1395 #endif
1396 default:
1397 PyErr_SetString(socket_error, "getsockaddrarg: unknown Bluetooth protocol");
1398 return 0;
1401 #endif
1403 #ifdef HAVE_NETPACKET_PACKET_H
1404 case AF_PACKET:
1406 struct sockaddr_ll* addr;
1407 struct ifreq ifr;
1408 char *interfaceName;
1409 int protoNumber;
1410 int hatype = 0;
1411 int pkttype = 0;
1412 char *haddr = NULL;
1413 unsigned int halen = 0;
1415 if (!PyTuple_Check(args)) {
1416 PyErr_Format(
1417 PyExc_TypeError,
1418 "getsockaddrarg: "
1419 "AF_PACKET address must be tuple, not %.500s",
1420 args->ob_type->tp_name);
1421 return 0;
1423 if (!PyArg_ParseTuple(args, "si|iis#", &interfaceName,
1424 &protoNumber, &pkttype, &hatype,
1425 &haddr, &halen))
1426 return 0;
1427 strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name));
1428 ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
1429 if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
1430 s->errorhandler();
1431 return 0;
1433 if (halen > 8) {
1434 PyErr_SetString(PyExc_ValueError,
1435 "Hardware address must be 8 bytes or less");
1436 return 0;
1438 addr = (struct sockaddr_ll*)addr_ret;
1439 addr->sll_family = AF_PACKET;
1440 addr->sll_protocol = htons((short)protoNumber);
1441 addr->sll_ifindex = ifr.ifr_ifindex;
1442 addr->sll_pkttype = pkttype;
1443 addr->sll_hatype = hatype;
1444 if (halen != 0) {
1445 memcpy(&addr->sll_addr, haddr, halen);
1447 addr->sll_halen = halen;
1448 *len_ret = sizeof *addr;
1449 return 1;
1451 #endif
1453 /* More cases here... */
1455 default:
1456 PyErr_SetString(socket_error, "getsockaddrarg: bad family");
1457 return 0;
1463 /* Get the address length according to the socket object's address family.
1464 Return 1 if the family is known, 0 otherwise. The length is returned
1465 through len_ret. */
1467 static int
1468 getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
1470 switch (s->sock_family) {
1472 #if defined(AF_UNIX)
1473 case AF_UNIX:
1475 *len_ret = sizeof (struct sockaddr_un);
1476 return 1;
1478 #endif /* AF_UNIX */
1479 #if defined(AF_NETLINK)
1480 case AF_NETLINK:
1482 *len_ret = sizeof (struct sockaddr_nl);
1483 return 1;
1485 #endif
1487 case AF_INET:
1489 *len_ret = sizeof (struct sockaddr_in);
1490 return 1;
1493 #ifdef ENABLE_IPV6
1494 case AF_INET6:
1496 *len_ret = sizeof (struct sockaddr_in6);
1497 return 1;
1499 #endif
1501 #ifdef USE_BLUETOOTH
1502 case AF_BLUETOOTH:
1504 switch(s->sock_proto)
1507 case BTPROTO_L2CAP:
1508 *len_ret = sizeof (struct sockaddr_l2);
1509 return 1;
1510 case BTPROTO_RFCOMM:
1511 *len_ret = sizeof (struct sockaddr_rc);
1512 return 1;
1513 case BTPROTO_HCI:
1514 *len_ret = sizeof (struct sockaddr_hci);
1515 return 1;
1516 #if !defined(__FreeBSD__)
1517 case BTPROTO_SCO:
1518 *len_ret = sizeof (struct sockaddr_sco);
1519 return 1;
1520 #endif
1521 default:
1522 PyErr_SetString(socket_error, "getsockaddrlen: "
1523 "unknown BT protocol");
1524 return 0;
1528 #endif
1530 #ifdef HAVE_NETPACKET_PACKET_H
1531 case AF_PACKET:
1533 *len_ret = sizeof (struct sockaddr_ll);
1534 return 1;
1536 #endif
1538 /* More cases here... */
1540 default:
1541 PyErr_SetString(socket_error, "getsockaddrlen: bad family");
1542 return 0;
1548 /* s.accept() method */
1550 static PyObject *
1551 sock_accept(PySocketSockObject *s)
1553 sock_addr_t addrbuf;
1554 SOCKET_T newfd;
1555 socklen_t addrlen;
1556 PyObject *sock = NULL;
1557 PyObject *addr = NULL;
1558 PyObject *res = NULL;
1559 int timeout;
1561 if (!getsockaddrlen(s, &addrlen))
1562 return NULL;
1563 memset(&addrbuf, 0, addrlen);
1565 #ifdef MS_WINDOWS
1566 newfd = INVALID_SOCKET;
1567 #else
1568 newfd = -1;
1569 #endif
1571 if (!IS_SELECTABLE(s))
1572 return select_error();
1574 Py_BEGIN_ALLOW_THREADS
1575 timeout = internal_select(s, 0);
1576 if (!timeout)
1577 newfd = accept(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
1578 Py_END_ALLOW_THREADS
1580 if (timeout == 1) {
1581 PyErr_SetString(socket_timeout, "timed out");
1582 return NULL;
1585 #ifdef MS_WINDOWS
1586 if (newfd == INVALID_SOCKET)
1587 #else
1588 if (newfd < 0)
1589 #endif
1590 return s->errorhandler();
1592 /* Create the new object with unspecified family,
1593 to avoid calls to bind() etc. on it. */
1594 sock = (PyObject *) new_sockobject(newfd,
1595 s->sock_family,
1596 s->sock_type,
1597 s->sock_proto);
1599 if (sock == NULL) {
1600 SOCKETCLOSE(newfd);
1601 goto finally;
1603 addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
1604 addrlen, s->sock_proto);
1605 if (addr == NULL)
1606 goto finally;
1608 res = PyTuple_Pack(2, sock, addr);
1610 finally:
1611 Py_XDECREF(sock);
1612 Py_XDECREF(addr);
1613 return res;
1616 PyDoc_STRVAR(accept_doc,
1617 "accept() -> (socket object, address info)\n\
1619 Wait for an incoming connection. Return a new socket representing the\n\
1620 connection, and the address of the client. For IP sockets, the address\n\
1621 info is a pair (hostaddr, port).");
1623 /* s.setblocking(flag) method. Argument:
1624 False -- non-blocking mode; same as settimeout(0)
1625 True -- blocking mode; same as settimeout(None)
1628 static PyObject *
1629 sock_setblocking(PySocketSockObject *s, PyObject *arg)
1631 int block;
1633 block = PyInt_AsLong(arg);
1634 if (block == -1 && PyErr_Occurred())
1635 return NULL;
1637 s->sock_timeout = block ? -1.0 : 0.0;
1638 internal_setblocking(s, block);
1640 Py_INCREF(Py_None);
1641 return Py_None;
1644 PyDoc_STRVAR(setblocking_doc,
1645 "setblocking(flag)\n\
1647 Set the socket to blocking (flag is true) or non-blocking (false).\n\
1648 setblocking(True) is equivalent to settimeout(None);\n\
1649 setblocking(False) is equivalent to settimeout(0.0).");
1651 /* s.settimeout(timeout) method. Argument:
1652 None -- no timeout, blocking mode; same as setblocking(True)
1653 0.0 -- non-blocking mode; same as setblocking(False)
1654 > 0 -- timeout mode; operations time out after timeout seconds
1655 < 0 -- illegal; raises an exception
1657 static PyObject *
1658 sock_settimeout(PySocketSockObject *s, PyObject *arg)
1660 double timeout;
1662 if (arg == Py_None)
1663 timeout = -1.0;
1664 else {
1665 timeout = PyFloat_AsDouble(arg);
1666 if (timeout < 0.0) {
1667 if (!PyErr_Occurred())
1668 PyErr_SetString(PyExc_ValueError,
1669 "Timeout value out of range");
1670 return NULL;
1674 s->sock_timeout = timeout;
1675 internal_setblocking(s, timeout < 0.0);
1677 Py_INCREF(Py_None);
1678 return Py_None;
1681 PyDoc_STRVAR(settimeout_doc,
1682 "settimeout(timeout)\n\
1684 Set a timeout on socket operations. 'timeout' can be a float,\n\
1685 giving in seconds, or None. Setting a timeout of None disables\n\
1686 the timeout feature and is equivalent to setblocking(1).\n\
1687 Setting a timeout of zero is the same as setblocking(0).");
1689 /* s.gettimeout() method.
1690 Returns the timeout associated with a socket. */
1691 static PyObject *
1692 sock_gettimeout(PySocketSockObject *s)
1694 if (s->sock_timeout < 0.0) {
1695 Py_INCREF(Py_None);
1696 return Py_None;
1698 else
1699 return PyFloat_FromDouble(s->sock_timeout);
1702 PyDoc_STRVAR(gettimeout_doc,
1703 "gettimeout() -> timeout\n\
1705 Returns the timeout in floating seconds associated with socket \n\
1706 operations. A timeout of None indicates that timeouts on socket \n\
1707 operations are disabled.");
1709 #ifdef RISCOS
1710 /* s.sleeptaskw(1 | 0) method */
1712 static PyObject *
1713 sock_sleeptaskw(PySocketSockObject *s,PyObject *arg)
1715 int block;
1716 block = PyInt_AsLong(arg);
1717 if (block == -1 && PyErr_Occurred())
1718 return NULL;
1719 Py_BEGIN_ALLOW_THREADS
1720 socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
1721 Py_END_ALLOW_THREADS
1723 Py_INCREF(Py_None);
1724 return Py_None;
1726 PyDoc_STRVAR(sleeptaskw_doc,
1727 "sleeptaskw(flag)\n\
1729 Allow sleeps in taskwindows.");
1730 #endif
1733 /* s.setsockopt() method.
1734 With an integer third argument, sets an integer option.
1735 With a string third argument, sets an option from a buffer;
1736 use optional built-in module 'struct' to encode the string. */
1738 static PyObject *
1739 sock_setsockopt(PySocketSockObject *s, PyObject *args)
1741 int level;
1742 int optname;
1743 int res;
1744 char *buf;
1745 int buflen;
1746 int flag;
1748 if (PyArg_ParseTuple(args, "iii:setsockopt",
1749 &level, &optname, &flag)) {
1750 buf = (char *) &flag;
1751 buflen = sizeof flag;
1753 else {
1754 PyErr_Clear();
1755 if (!PyArg_ParseTuple(args, "iis#:setsockopt",
1756 &level, &optname, &buf, &buflen))
1757 return NULL;
1759 res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen);
1760 if (res < 0)
1761 return s->errorhandler();
1762 Py_INCREF(Py_None);
1763 return Py_None;
1766 PyDoc_STRVAR(setsockopt_doc,
1767 "setsockopt(level, option, value)\n\
1769 Set a socket option. See the Unix manual for level and option.\n\
1770 The value argument can either be an integer or a string.");
1773 /* s.getsockopt() method.
1774 With two arguments, retrieves an integer option.
1775 With a third integer argument, retrieves a string buffer of that size;
1776 use optional built-in module 'struct' to decode the string. */
1778 static PyObject *
1779 sock_getsockopt(PySocketSockObject *s, PyObject *args)
1781 int level;
1782 int optname;
1783 int res;
1784 PyObject *buf;
1785 socklen_t buflen = 0;
1787 #ifdef __BEOS__
1788 /* We have incomplete socket support. */
1789 PyErr_SetString(socket_error, "getsockopt not supported");
1790 return NULL;
1791 #else
1793 if (!PyArg_ParseTuple(args, "ii|i:getsockopt",
1794 &level, &optname, &buflen))
1795 return NULL;
1797 if (buflen == 0) {
1798 int flag = 0;
1799 socklen_t flagsize = sizeof flag;
1800 res = getsockopt(s->sock_fd, level, optname,
1801 (void *)&flag, &flagsize);
1802 if (res < 0)
1803 return s->errorhandler();
1804 return PyInt_FromLong(flag);
1806 #ifdef __VMS
1807 /* socklen_t is unsigned so no negative test is needed,
1808 test buflen == 0 is previously done */
1809 if (buflen > 1024) {
1810 #else
1811 if (buflen <= 0 || buflen > 1024) {
1812 #endif
1813 PyErr_SetString(socket_error,
1814 "getsockopt buflen out of range");
1815 return NULL;
1817 buf = PyString_FromStringAndSize((char *)NULL, buflen);
1818 if (buf == NULL)
1819 return NULL;
1820 res = getsockopt(s->sock_fd, level, optname,
1821 (void *)PyString_AS_STRING(buf), &buflen);
1822 if (res < 0) {
1823 Py_DECREF(buf);
1824 return s->errorhandler();
1826 _PyString_Resize(&buf, buflen);
1827 return buf;
1828 #endif /* __BEOS__ */
1831 PyDoc_STRVAR(getsockopt_doc,
1832 "getsockopt(level, option[, buffersize]) -> value\n\
1834 Get a socket option. See the Unix manual for level and option.\n\
1835 If a nonzero buffersize argument is given, the return value is a\n\
1836 string of that length; otherwise it is an integer.");
1839 /* s.bind(sockaddr) method */
1841 static PyObject *
1842 sock_bind(PySocketSockObject *s, PyObject *addro)
1844 sock_addr_t addrbuf;
1845 int addrlen;
1846 int res;
1848 if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
1849 return NULL;
1850 Py_BEGIN_ALLOW_THREADS
1851 res = bind(s->sock_fd, SAS2SA(&addrbuf), addrlen);
1852 Py_END_ALLOW_THREADS
1853 if (res < 0)
1854 return s->errorhandler();
1855 Py_INCREF(Py_None);
1856 return Py_None;
1859 PyDoc_STRVAR(bind_doc,
1860 "bind(address)\n\
1862 Bind the socket to a local address. For IP sockets, the address is a\n\
1863 pair (host, port); the host must refer to the local host. For raw packet\n\
1864 sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");
1867 /* s.close() method.
1868 Set the file descriptor to -1 so operations tried subsequently
1869 will surely fail. */
1871 static PyObject *
1872 sock_close(PySocketSockObject *s)
1874 SOCKET_T fd;
1876 if ((fd = s->sock_fd) != -1) {
1877 s->sock_fd = -1;
1878 Py_BEGIN_ALLOW_THREADS
1879 (void) SOCKETCLOSE(fd);
1880 Py_END_ALLOW_THREADS
1882 Py_INCREF(Py_None);
1883 return Py_None;
1886 PyDoc_STRVAR(close_doc,
1887 "close()\n\
1889 Close the socket. It cannot be used after this call.");
1891 static int
1892 internal_connect(PySocketSockObject *s, struct sockaddr *addr, int addrlen,
1893 int *timeoutp)
1895 int res, timeout;
1897 timeout = 0;
1898 res = connect(s->sock_fd, addr, addrlen);
1900 #ifdef MS_WINDOWS
1902 if (s->sock_timeout > 0.0) {
1903 if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK &&
1904 IS_SELECTABLE(s)) {
1905 /* This is a mess. Best solution: trust select */
1906 fd_set fds;
1907 fd_set fds_exc;
1908 struct timeval tv;
1909 tv.tv_sec = (int)s->sock_timeout;
1910 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1911 FD_ZERO(&fds);
1912 FD_SET(s->sock_fd, &fds);
1913 FD_ZERO(&fds_exc);
1914 FD_SET(s->sock_fd, &fds_exc);
1915 res = select(s->sock_fd+1, NULL, &fds, &fds_exc, &tv);
1916 if (res == 0) {
1917 res = WSAEWOULDBLOCK;
1918 timeout = 1;
1919 } else if (res > 0) {
1920 if (FD_ISSET(s->sock_fd, &fds))
1921 /* The socket is in the writeable set - this
1922 means connected */
1923 res = 0;
1924 else {
1925 /* As per MS docs, we need to call getsockopt()
1926 to get the underlying error */
1927 int res_size = sizeof res;
1928 /* It must be in the exception set */
1929 assert(FD_ISSET(s->sock_fd, &fds_exc));
1930 if (0 == getsockopt(s->sock_fd, SOL_SOCKET, SO_ERROR,
1931 (char *)&res, &res_size))
1932 /* getsockopt also clears WSAGetLastError,
1933 so reset it back. */
1934 WSASetLastError(res);
1935 else
1936 res = WSAGetLastError();
1939 /* else if (res < 0) an error occurred */
1943 if (res < 0)
1944 res = WSAGetLastError();
1946 #else
1948 if (s->sock_timeout > 0.0) {
1949 if (res < 0 && errno == EINPROGRESS && IS_SELECTABLE(s)) {
1950 timeout = internal_select(s, 1);
1951 if (timeout == 0) {
1952 res = connect(s->sock_fd, addr, addrlen);
1953 if (res < 0 && errno == EISCONN)
1954 res = 0;
1956 else if (timeout == -1)
1957 res = errno; /* had error */
1958 else
1959 res = EWOULDBLOCK; /* timed out */
1963 if (res < 0)
1964 res = errno;
1966 #endif
1967 *timeoutp = timeout;
1969 return res;
1972 /* s.connect(sockaddr) method */
1974 static PyObject *
1975 sock_connect(PySocketSockObject *s, PyObject *addro)
1977 sock_addr_t addrbuf;
1978 int addrlen;
1979 int res;
1980 int timeout;
1982 if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
1983 return NULL;
1985 Py_BEGIN_ALLOW_THREADS
1986 res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
1987 Py_END_ALLOW_THREADS
1989 if (timeout == 1) {
1990 PyErr_SetString(socket_timeout, "timed out");
1991 return NULL;
1993 if (res != 0)
1994 return s->errorhandler();
1995 Py_INCREF(Py_None);
1996 return Py_None;
1999 PyDoc_STRVAR(connect_doc,
2000 "connect(address)\n\
2002 Connect the socket to a remote address. For IP sockets, the address\n\
2003 is a pair (host, port).");
2006 /* s.connect_ex(sockaddr) method */
2008 static PyObject *
2009 sock_connect_ex(PySocketSockObject *s, PyObject *addro)
2011 sock_addr_t addrbuf;
2012 int addrlen;
2013 int res;
2014 int timeout;
2016 if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
2017 return NULL;
2019 Py_BEGIN_ALLOW_THREADS
2020 res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
2021 Py_END_ALLOW_THREADS
2023 /* Signals are not errors (though they may raise exceptions). Adapted
2024 from PyErr_SetFromErrnoWithFilenameObject(). */
2025 #ifdef EINTR
2026 if (res == EINTR && PyErr_CheckSignals())
2027 return NULL;
2028 #endif
2030 return PyInt_FromLong((long) res);
2033 PyDoc_STRVAR(connect_ex_doc,
2034 "connect_ex(address) -> errno\n\
2036 This is like connect(address), but returns an error code (the errno value)\n\
2037 instead of raising an exception when an error occurs.");
2040 /* s.fileno() method */
2042 static PyObject *
2043 sock_fileno(PySocketSockObject *s)
2045 #if SIZEOF_SOCKET_T <= SIZEOF_LONG
2046 return PyInt_FromLong((long) s->sock_fd);
2047 #else
2048 return PyLong_FromLongLong((PY_LONG_LONG)s->sock_fd);
2049 #endif
2052 PyDoc_STRVAR(fileno_doc,
2053 "fileno() -> integer\n\
2055 Return the integer file descriptor of the socket.");
2058 #ifndef NO_DUP
2059 /* s.dup() method */
2061 static PyObject *
2062 sock_dup(PySocketSockObject *s)
2064 SOCKET_T newfd;
2065 PyObject *sock;
2067 newfd = dup(s->sock_fd);
2068 if (newfd < 0)
2069 return s->errorhandler();
2070 sock = (PyObject *) new_sockobject(newfd,
2071 s->sock_family,
2072 s->sock_type,
2073 s->sock_proto);
2074 if (sock == NULL)
2075 SOCKETCLOSE(newfd);
2076 return sock;
2079 PyDoc_STRVAR(dup_doc,
2080 "dup() -> socket object\n\
2082 Return a new socket object connected to the same system resource.");
2084 #endif
2087 /* s.getsockname() method */
2089 static PyObject *
2090 sock_getsockname(PySocketSockObject *s)
2092 sock_addr_t addrbuf;
2093 int res;
2094 socklen_t addrlen;
2096 if (!getsockaddrlen(s, &addrlen))
2097 return NULL;
2098 memset(&addrbuf, 0, addrlen);
2099 Py_BEGIN_ALLOW_THREADS
2100 res = getsockname(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
2101 Py_END_ALLOW_THREADS
2102 if (res < 0)
2103 return s->errorhandler();
2104 return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
2105 s->sock_proto);
2108 PyDoc_STRVAR(getsockname_doc,
2109 "getsockname() -> address info\n\
2111 Return the address of the local endpoint. For IP sockets, the address\n\
2112 info is a pair (hostaddr, port).");
2115 #ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
2116 /* s.getpeername() method */
2118 static PyObject *
2119 sock_getpeername(PySocketSockObject *s)
2121 sock_addr_t addrbuf;
2122 int res;
2123 socklen_t addrlen;
2125 if (!getsockaddrlen(s, &addrlen))
2126 return NULL;
2127 memset(&addrbuf, 0, addrlen);
2128 Py_BEGIN_ALLOW_THREADS
2129 res = getpeername(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
2130 Py_END_ALLOW_THREADS
2131 if (res < 0)
2132 return s->errorhandler();
2133 return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
2134 s->sock_proto);
2137 PyDoc_STRVAR(getpeername_doc,
2138 "getpeername() -> address info\n\
2140 Return the address of the remote endpoint. For IP sockets, the address\n\
2141 info is a pair (hostaddr, port).");
2143 #endif /* HAVE_GETPEERNAME */
2146 /* s.listen(n) method */
2148 static PyObject *
2149 sock_listen(PySocketSockObject *s, PyObject *arg)
2151 int backlog;
2152 int res;
2154 backlog = PyInt_AsLong(arg);
2155 if (backlog == -1 && PyErr_Occurred())
2156 return NULL;
2157 Py_BEGIN_ALLOW_THREADS
2158 if (backlog < 1)
2159 backlog = 1;
2160 res = listen(s->sock_fd, backlog);
2161 Py_END_ALLOW_THREADS
2162 if (res < 0)
2163 return s->errorhandler();
2164 Py_INCREF(Py_None);
2165 return Py_None;
2168 PyDoc_STRVAR(listen_doc,
2169 "listen(backlog)\n\
2171 Enable a server to accept connections. The backlog argument must be at\n\
2172 least 1; it specifies the number of unaccepted connection that the system\n\
2173 will allow before refusing new connections.");
2176 #ifndef NO_DUP
2177 /* s.makefile(mode) method.
2178 Create a new open file object referring to a dupped version of
2179 the socket's file descriptor. (The dup() call is necessary so
2180 that the open file and socket objects may be closed independent
2181 of each other.)
2182 The mode argument specifies 'r' or 'w' passed to fdopen(). */
2184 static PyObject *
2185 sock_makefile(PySocketSockObject *s, PyObject *args)
2187 extern int fclose(FILE *);
2188 char *mode = "r";
2189 int bufsize = -1;
2190 #ifdef MS_WIN32
2191 Py_intptr_t fd;
2192 #else
2193 int fd;
2194 #endif
2195 FILE *fp;
2196 PyObject *f;
2197 #ifdef __VMS
2198 char *mode_r = "r";
2199 char *mode_w = "w";
2200 #endif
2202 if (!PyArg_ParseTuple(args, "|si:makefile", &mode, &bufsize))
2203 return NULL;
2204 #ifdef __VMS
2205 if (strcmp(mode,"rb") == 0) {
2206 mode = mode_r;
2208 else {
2209 if (strcmp(mode,"wb") == 0) {
2210 mode = mode_w;
2213 #endif
2214 #ifdef MS_WIN32
2215 if (((fd = _open_osfhandle(s->sock_fd, _O_BINARY)) < 0) ||
2216 ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL))
2217 #else
2218 if ((fd = dup(s->sock_fd)) < 0 || (fp = fdopen(fd, mode)) == NULL)
2219 #endif
2221 if (fd >= 0)
2222 SOCKETCLOSE(fd);
2223 return s->errorhandler();
2225 f = PyFile_FromFile(fp, "<socket>", mode, fclose);
2226 if (f != NULL)
2227 PyFile_SetBufSize(f, bufsize);
2228 return f;
2231 PyDoc_STRVAR(makefile_doc,
2232 "makefile([mode[, buffersize]]) -> file object\n\
2234 Return a regular file object corresponding to the socket.\n\
2235 The mode and buffersize arguments are as for the built-in open() function.");
2237 #endif /* NO_DUP */
2240 * This is the guts of the recv() and recv_into() methods, which reads into a
2241 * char buffer. If you have any inc/dec ref to do to the objects that contain
2242 * the buffer, do it in the caller. This function returns the number of bytes
2243 * succesfully read. If there was an error, it returns -1. Note that it is
2244 * also possible that we return a number of bytes smaller than the request
2245 * bytes.
2247 static ssize_t
2248 sock_recv_guts(PySocketSockObject *s, char* cbuf, int len, int flags)
2250 ssize_t outlen = -1;
2251 int timeout;
2252 #ifdef __VMS
2253 int remaining;
2254 char *read_buf;
2255 #endif
2257 if (!IS_SELECTABLE(s)) {
2258 select_error();
2259 return -1;
2262 #ifndef __VMS
2263 Py_BEGIN_ALLOW_THREADS
2264 timeout = internal_select(s, 0);
2265 if (!timeout)
2266 outlen = recv(s->sock_fd, cbuf, len, flags);
2267 Py_END_ALLOW_THREADS
2269 if (timeout == 1) {
2270 PyErr_SetString(socket_timeout, "timed out");
2271 return -1;
2273 if (outlen < 0) {
2274 /* Note: the call to errorhandler() ALWAYS indirectly returned
2275 NULL, so ignore its return value */
2276 s->errorhandler();
2277 return -1;
2279 #else
2280 read_buf = cbuf;
2281 remaining = len;
2282 while (remaining != 0) {
2283 unsigned int segment;
2284 int nread = -1;
2286 segment = remaining /SEGMENT_SIZE;
2287 if (segment != 0) {
2288 segment = SEGMENT_SIZE;
2290 else {
2291 segment = remaining;
2294 Py_BEGIN_ALLOW_THREADS
2295 timeout = internal_select(s, 0);
2296 if (!timeout)
2297 nread = recv(s->sock_fd, read_buf, segment, flags);
2298 Py_END_ALLOW_THREADS
2300 if (timeout == 1) {
2301 PyErr_SetString(socket_timeout, "timed out");
2302 return -1;
2304 if (nread < 0) {
2305 s->errorhandler();
2306 return -1;
2308 if (nread != remaining) {
2309 read_buf += nread;
2310 break;
2313 remaining -= segment;
2314 read_buf += segment;
2316 outlen = read_buf - cbuf;
2317 #endif /* !__VMS */
2319 return outlen;
2323 /* s.recv(nbytes [,flags]) method */
2325 static PyObject *
2326 sock_recv(PySocketSockObject *s, PyObject *args)
2328 int recvlen, flags = 0;
2329 ssize_t outlen;
2330 PyObject *buf;
2332 if (!PyArg_ParseTuple(args, "i|i:recv", &recvlen, &flags))
2333 return NULL;
2335 if (recvlen < 0) {
2336 PyErr_SetString(PyExc_ValueError,
2337 "negative buffersize in recv");
2338 return NULL;
2341 /* Allocate a new string. */
2342 buf = PyString_FromStringAndSize((char *) 0, recvlen);
2343 if (buf == NULL)
2344 return NULL;
2346 /* Call the guts */
2347 outlen = sock_recv_guts(s, PyString_AS_STRING(buf), recvlen, flags);
2348 if (outlen < 0) {
2349 /* An error occurred, release the string and return an
2350 error. */
2351 Py_DECREF(buf);
2352 return NULL;
2354 if (outlen != recvlen) {
2355 /* We did not read as many bytes as we anticipated, resize the
2356 string if possible and be succesful. */
2357 if (_PyString_Resize(&buf, outlen) < 0)
2358 /* Oopsy, not so succesful after all. */
2359 return NULL;
2362 return buf;
2365 PyDoc_STRVAR(recv_doc,
2366 "recv(buffersize[, flags]) -> data\n\
2368 Receive up to buffersize bytes from the socket. For the optional flags\n\
2369 argument, see the Unix manual. When no data is available, block until\n\
2370 at least one byte is available or until the remote end is closed. When\n\
2371 the remote end is closed and all data is read, return the empty string.");
2374 /* s.recv_into(buffer, [nbytes [,flags]]) method */
2376 static PyObject*
2377 sock_recv_into(PySocketSockObject *s, PyObject *args, PyObject *kwds)
2379 static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
2381 int recvlen = 0, flags = 0;
2382 ssize_t readlen;
2383 char *buf;
2384 int buflen;
2386 /* Get the buffer's memory */
2387 if (!PyArg_ParseTupleAndKeywords(args, kwds, "w#|ii:recv_into", kwlist,
2388 &buf, &buflen, &recvlen, &flags))
2389 return NULL;
2390 assert(buf != 0 && buflen > 0);
2392 if (recvlen < 0) {
2393 PyErr_SetString(PyExc_ValueError,
2394 "negative buffersize in recv_into");
2395 return NULL;
2397 if (recvlen == 0) {
2398 /* If nbytes was not specified, use the buffer's length */
2399 recvlen = buflen;
2402 /* Check if the buffer is large enough */
2403 if (buflen < recvlen) {
2404 PyErr_SetString(PyExc_ValueError,
2405 "buffer too small for requested bytes");
2406 return NULL;
2409 /* Call the guts */
2410 readlen = sock_recv_guts(s, buf, recvlen, flags);
2411 if (readlen < 0) {
2412 /* Return an error. */
2413 return NULL;
2416 /* Return the number of bytes read. Note that we do not do anything
2417 special here in the case that readlen < recvlen. */
2418 return PyInt_FromSsize_t(readlen);
2421 PyDoc_STRVAR(recv_into_doc,
2422 "recv_into(buffer, [nbytes[, flags]]) -> nbytes_read\n\
2424 A version of recv() that stores its data into a buffer rather than creating \n\
2425 a new string. Receive up to buffersize bytes from the socket. If buffersize \n\
2426 is not specified (or 0), receive up to the size available in the given buffer.\n\
2428 See recv() for documentation about the flags.");
2432 * This is the guts of the recv() and recv_into() methods, which reads into a
2433 * char buffer. If you have any inc/def ref to do to the objects that contain
2434 * the buffer, do it in the caller. This function returns the number of bytes
2435 * succesfully read. If there was an error, it returns -1. Note that it is
2436 * also possible that we return a number of bytes smaller than the request
2437 * bytes.
2439 * 'addr' is a return value for the address object. Note that you must decref
2440 * it yourself.
2442 static ssize_t
2443 sock_recvfrom_guts(PySocketSockObject *s, char* cbuf, int len, int flags,
2444 PyObject** addr)
2446 sock_addr_t addrbuf;
2447 int timeout;
2448 ssize_t n = -1;
2449 socklen_t addrlen;
2451 *addr = NULL;
2453 if (!getsockaddrlen(s, &addrlen))
2454 return -1;
2456 if (!IS_SELECTABLE(s)) {
2457 select_error();
2458 return -1;
2461 Py_BEGIN_ALLOW_THREADS
2462 memset(&addrbuf, 0, addrlen);
2463 timeout = internal_select(s, 0);
2464 if (!timeout) {
2465 #ifndef MS_WINDOWS
2466 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
2467 n = recvfrom(s->sock_fd, cbuf, len, flags,
2468 SAS2SA(&addrbuf), &addrlen);
2469 #else
2470 n = recvfrom(s->sock_fd, cbuf, len, flags,
2471 (void *) &addrbuf, &addrlen);
2472 #endif
2473 #else
2474 n = recvfrom(s->sock_fd, cbuf, len, flags,
2475 SAS2SA(&addrbuf), &addrlen);
2476 #endif
2478 Py_END_ALLOW_THREADS
2480 if (timeout == 1) {
2481 PyErr_SetString(socket_timeout, "timed out");
2482 return -1;
2484 if (n < 0) {
2485 s->errorhandler();
2486 return -1;
2489 if (!(*addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
2490 addrlen, s->sock_proto)))
2491 return -1;
2493 return n;
2496 /* s.recvfrom(nbytes [,flags]) method */
2498 static PyObject *
2499 sock_recvfrom(PySocketSockObject *s, PyObject *args)
2501 PyObject *buf = NULL;
2502 PyObject *addr = NULL;
2503 PyObject *ret = NULL;
2504 int recvlen, flags = 0;
2505 ssize_t outlen;
2507 if (!PyArg_ParseTuple(args, "i|i:recvfrom", &recvlen, &flags))
2508 return NULL;
2510 if (recvlen < 0) {
2511 PyErr_SetString(PyExc_ValueError,
2512 "negative buffersize in recvfrom");
2513 return NULL;
2516 buf = PyString_FromStringAndSize((char *) 0, recvlen);
2517 if (buf == NULL)
2518 return NULL;
2520 outlen = sock_recvfrom_guts(s, PyString_AS_STRING(buf),
2521 recvlen, flags, &addr);
2522 if (outlen < 0) {
2523 goto finally;
2526 if (outlen != recvlen) {
2527 /* We did not read as many bytes as we anticipated, resize the
2528 string if possible and be succesful. */
2529 if (_PyString_Resize(&buf, outlen) < 0)
2530 /* Oopsy, not so succesful after all. */
2531 goto finally;
2534 ret = PyTuple_Pack(2, buf, addr);
2536 finally:
2537 Py_XDECREF(buf);
2538 Py_XDECREF(addr);
2539 return ret;
2542 PyDoc_STRVAR(recvfrom_doc,
2543 "recvfrom(buffersize[, flags]) -> (data, address info)\n\
2545 Like recv(buffersize, flags) but also return the sender's address info.");
2548 /* s.recvfrom_into(buffer[, nbytes [,flags]]) method */
2550 static PyObject *
2551 sock_recvfrom_into(PySocketSockObject *s, PyObject *args, PyObject* kwds)
2553 static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
2555 int recvlen = 0, flags = 0;
2556 ssize_t readlen;
2557 char *buf;
2558 int buflen;
2560 PyObject *addr = NULL;
2562 if (!PyArg_ParseTupleAndKeywords(args, kwds, "w#|ii:recvfrom_into",
2563 kwlist, &buf, &buflen,
2564 &recvlen, &flags))
2565 return NULL;
2566 assert(buf != 0 && buflen > 0);
2568 if (recvlen < 0) {
2569 PyErr_SetString(PyExc_ValueError,
2570 "negative buffersize in recvfrom_into");
2571 return NULL;
2573 if (recvlen == 0) {
2574 /* If nbytes was not specified, use the buffer's length */
2575 recvlen = buflen;
2578 readlen = sock_recvfrom_guts(s, buf, recvlen, flags, &addr);
2579 if (readlen < 0) {
2580 /* Return an error */
2581 Py_XDECREF(addr);
2582 return NULL;
2585 /* Return the number of bytes read and the address. Note that we do
2586 not do anything special here in the case that readlen < recvlen. */
2587 return Py_BuildValue("lN", readlen, addr);
2590 PyDoc_STRVAR(recvfrom_into_doc,
2591 "recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)\n\
2593 Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.");
2596 /* s.send(data [,flags]) method */
2598 static PyObject *
2599 sock_send(PySocketSockObject *s, PyObject *args)
2601 char *buf;
2602 int len, n = -1, flags = 0, timeout;
2604 if (!PyArg_ParseTuple(args, "s#|i:send", &buf, &len, &flags))
2605 return NULL;
2607 if (!IS_SELECTABLE(s))
2608 return select_error();
2610 Py_BEGIN_ALLOW_THREADS
2611 timeout = internal_select(s, 1);
2612 if (!timeout)
2613 #ifdef __VMS
2614 n = sendsegmented(s->sock_fd, buf, len, flags);
2615 #else
2616 n = send(s->sock_fd, buf, len, flags);
2617 #endif
2618 Py_END_ALLOW_THREADS
2620 if (timeout == 1) {
2621 PyErr_SetString(socket_timeout, "timed out");
2622 return NULL;
2624 if (n < 0)
2625 return s->errorhandler();
2626 return PyInt_FromLong((long)n);
2629 PyDoc_STRVAR(send_doc,
2630 "send(data[, flags]) -> count\n\
2632 Send a data string to the socket. For the optional flags\n\
2633 argument, see the Unix manual. Return the number of bytes\n\
2634 sent; this may be less than len(data) if the network is busy.");
2637 /* s.sendall(data [,flags]) method */
2639 static PyObject *
2640 sock_sendall(PySocketSockObject *s, PyObject *args)
2642 char *buf;
2643 int len, n = -1, flags = 0, timeout;
2645 if (!PyArg_ParseTuple(args, "s#|i:sendall", &buf, &len, &flags))
2646 return NULL;
2648 if (!IS_SELECTABLE(s))
2649 return select_error();
2651 Py_BEGIN_ALLOW_THREADS
2652 do {
2653 timeout = internal_select(s, 1);
2654 n = -1;
2655 if (timeout)
2656 break;
2657 #ifdef __VMS
2658 n = sendsegmented(s->sock_fd, buf, len, flags);
2659 #else
2660 n = send(s->sock_fd, buf, len, flags);
2661 #endif
2662 if (n < 0)
2663 break;
2664 buf += n;
2665 len -= n;
2666 } while (len > 0);
2667 Py_END_ALLOW_THREADS
2669 if (timeout == 1) {
2670 PyErr_SetString(socket_timeout, "timed out");
2671 return NULL;
2673 if (n < 0)
2674 return s->errorhandler();
2676 Py_INCREF(Py_None);
2677 return Py_None;
2680 PyDoc_STRVAR(sendall_doc,
2681 "sendall(data[, flags])\n\
2683 Send a data string to the socket. For the optional flags\n\
2684 argument, see the Unix manual. This calls send() repeatedly\n\
2685 until all data is sent. If an error occurs, it's impossible\n\
2686 to tell how much data has been sent.");
2689 /* s.sendto(data, [flags,] sockaddr) method */
2691 static PyObject *
2692 sock_sendto(PySocketSockObject *s, PyObject *args)
2694 PyObject *addro;
2695 char *buf;
2696 sock_addr_t addrbuf;
2697 int addrlen, len, n = -1, flags, timeout;
2699 flags = 0;
2700 if (!PyArg_ParseTuple(args, "s#O:sendto", &buf, &len, &addro)) {
2701 PyErr_Clear();
2702 if (!PyArg_ParseTuple(args, "s#iO:sendto",
2703 &buf, &len, &flags, &addro))
2704 return NULL;
2707 if (!IS_SELECTABLE(s))
2708 return select_error();
2710 if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
2711 return NULL;
2713 Py_BEGIN_ALLOW_THREADS
2714 timeout = internal_select(s, 1);
2715 if (!timeout)
2716 n = sendto(s->sock_fd, buf, len, flags, SAS2SA(&addrbuf), addrlen);
2717 Py_END_ALLOW_THREADS
2719 if (timeout == 1) {
2720 PyErr_SetString(socket_timeout, "timed out");
2721 return NULL;
2723 if (n < 0)
2724 return s->errorhandler();
2725 return PyInt_FromLong((long)n);
2728 PyDoc_STRVAR(sendto_doc,
2729 "sendto(data[, flags], address) -> count\n\
2731 Like send(data, flags) but allows specifying the destination address.\n\
2732 For IP sockets, the address is a pair (hostaddr, port).");
2735 /* s.shutdown(how) method */
2737 static PyObject *
2738 sock_shutdown(PySocketSockObject *s, PyObject *arg)
2740 int how;
2741 int res;
2743 how = PyInt_AsLong(arg);
2744 if (how == -1 && PyErr_Occurred())
2745 return NULL;
2746 Py_BEGIN_ALLOW_THREADS
2747 res = shutdown(s->sock_fd, how);
2748 Py_END_ALLOW_THREADS
2749 if (res < 0)
2750 return s->errorhandler();
2751 Py_INCREF(Py_None);
2752 return Py_None;
2755 PyDoc_STRVAR(shutdown_doc,
2756 "shutdown(flag)\n\
2758 Shut down the reading side of the socket (flag == SHUT_RD), the writing side\n\
2759 of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).");
2762 /* List of methods for socket objects */
2764 static PyMethodDef sock_methods[] = {
2765 {"accept", (PyCFunction)sock_accept, METH_NOARGS,
2766 accept_doc},
2767 {"bind", (PyCFunction)sock_bind, METH_O,
2768 bind_doc},
2769 {"close", (PyCFunction)sock_close, METH_NOARGS,
2770 close_doc},
2771 {"connect", (PyCFunction)sock_connect, METH_O,
2772 connect_doc},
2773 {"connect_ex", (PyCFunction)sock_connect_ex, METH_O,
2774 connect_ex_doc},
2775 #ifndef NO_DUP
2776 {"dup", (PyCFunction)sock_dup, METH_NOARGS,
2777 dup_doc},
2778 #endif
2779 {"fileno", (PyCFunction)sock_fileno, METH_NOARGS,
2780 fileno_doc},
2781 #ifdef HAVE_GETPEERNAME
2782 {"getpeername", (PyCFunction)sock_getpeername,
2783 METH_NOARGS, getpeername_doc},
2784 #endif
2785 {"getsockname", (PyCFunction)sock_getsockname,
2786 METH_NOARGS, getsockname_doc},
2787 {"getsockopt", (PyCFunction)sock_getsockopt, METH_VARARGS,
2788 getsockopt_doc},
2789 {"listen", (PyCFunction)sock_listen, METH_O,
2790 listen_doc},
2791 #ifndef NO_DUP
2792 {"makefile", (PyCFunction)sock_makefile, METH_VARARGS,
2793 makefile_doc},
2794 #endif
2795 {"recv", (PyCFunction)sock_recv, METH_VARARGS,
2796 recv_doc},
2797 {"recv_into", (PyCFunction)sock_recv_into, METH_VARARGS | METH_KEYWORDS,
2798 recv_into_doc},
2799 {"recvfrom", (PyCFunction)sock_recvfrom, METH_VARARGS,
2800 recvfrom_doc},
2801 {"recvfrom_into", (PyCFunction)sock_recvfrom_into, METH_VARARGS | METH_KEYWORDS,
2802 recvfrom_into_doc},
2803 {"send", (PyCFunction)sock_send, METH_VARARGS,
2804 send_doc},
2805 {"sendall", (PyCFunction)sock_sendall, METH_VARARGS,
2806 sendall_doc},
2807 {"sendto", (PyCFunction)sock_sendto, METH_VARARGS,
2808 sendto_doc},
2809 {"setblocking", (PyCFunction)sock_setblocking, METH_O,
2810 setblocking_doc},
2811 {"settimeout", (PyCFunction)sock_settimeout, METH_O,
2812 settimeout_doc},
2813 {"gettimeout", (PyCFunction)sock_gettimeout, METH_NOARGS,
2814 gettimeout_doc},
2815 {"setsockopt", (PyCFunction)sock_setsockopt, METH_VARARGS,
2816 setsockopt_doc},
2817 {"shutdown", (PyCFunction)sock_shutdown, METH_O,
2818 shutdown_doc},
2819 #ifdef RISCOS
2820 {"sleeptaskw", (PyCFunction)sock_sleeptaskw, METH_O,
2821 sleeptaskw_doc},
2822 #endif
2823 {NULL, NULL} /* sentinel */
2826 /* SockObject members */
2827 static PyMemberDef sock_memberlist[] = {
2828 {"family", T_INT, offsetof(PySocketSockObject, sock_family), READONLY, "the socket family"},
2829 {"type", T_INT, offsetof(PySocketSockObject, sock_type), READONLY, "the socket type"},
2830 {"proto", T_INT, offsetof(PySocketSockObject, sock_proto), READONLY, "the socket protocol"},
2831 {"timeout", T_DOUBLE, offsetof(PySocketSockObject, sock_timeout), READONLY, "the socket timeout"},
2832 {0},
2835 /* Deallocate a socket object in response to the last Py_DECREF().
2836 First close the file description. */
2838 static void
2839 sock_dealloc(PySocketSockObject *s)
2841 if (s->sock_fd != -1)
2842 (void) SOCKETCLOSE(s->sock_fd);
2843 s->ob_type->tp_free((PyObject *)s);
2847 static PyObject *
2848 sock_repr(PySocketSockObject *s)
2850 char buf[512];
2851 #if SIZEOF_SOCKET_T > SIZEOF_LONG
2852 if (s->sock_fd > LONG_MAX) {
2853 /* this can occur on Win64, and actually there is a special
2854 ugly printf formatter for decimal pointer length integer
2855 printing, only bother if necessary*/
2856 PyErr_SetString(PyExc_OverflowError,
2857 "no printf formatter to display "
2858 "the socket descriptor in decimal");
2859 return NULL;
2861 #endif
2862 PyOS_snprintf(
2863 buf, sizeof(buf),
2864 "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
2865 (long)s->sock_fd, s->sock_family,
2866 s->sock_type,
2867 s->sock_proto);
2868 return PyString_FromString(buf);
2872 /* Create a new, uninitialized socket object. */
2874 static PyObject *
2875 sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2877 PyObject *new;
2879 new = type->tp_alloc(type, 0);
2880 if (new != NULL) {
2881 ((PySocketSockObject *)new)->sock_fd = -1;
2882 ((PySocketSockObject *)new)->sock_timeout = -1.0;
2883 ((PySocketSockObject *)new)->errorhandler = &set_error;
2885 return new;
2889 /* Initialize a new socket object. */
2891 /*ARGSUSED*/
2892 static int
2893 sock_initobj(PyObject *self, PyObject *args, PyObject *kwds)
2895 PySocketSockObject *s = (PySocketSockObject *)self;
2896 SOCKET_T fd;
2897 int family = AF_INET, type = SOCK_STREAM, proto = 0;
2898 static char *keywords[] = {"family", "type", "proto", 0};
2900 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2901 "|iii:socket", keywords,
2902 &family, &type, &proto))
2903 return -1;
2905 Py_BEGIN_ALLOW_THREADS
2906 fd = socket(family, type, proto);
2907 Py_END_ALLOW_THREADS
2909 #ifdef MS_WINDOWS
2910 if (fd == INVALID_SOCKET)
2911 #else
2912 if (fd < 0)
2913 #endif
2915 set_error();
2916 return -1;
2918 init_sockobject(s, fd, family, type, proto);
2920 return 0;
2925 /* Type object for socket objects. */
2927 static PyTypeObject sock_type = {
2928 PyObject_HEAD_INIT(0) /* Must fill in type value later */
2929 0, /* ob_size */
2930 "_socket.socket", /* tp_name */
2931 sizeof(PySocketSockObject), /* tp_basicsize */
2932 0, /* tp_itemsize */
2933 (destructor)sock_dealloc, /* tp_dealloc */
2934 0, /* tp_print */
2935 0, /* tp_getattr */
2936 0, /* tp_setattr */
2937 0, /* tp_compare */
2938 (reprfunc)sock_repr, /* tp_repr */
2939 0, /* tp_as_number */
2940 0, /* tp_as_sequence */
2941 0, /* tp_as_mapping */
2942 0, /* tp_hash */
2943 0, /* tp_call */
2944 0, /* tp_str */
2945 PyObject_GenericGetAttr, /* tp_getattro */
2946 0, /* tp_setattro */
2947 0, /* tp_as_buffer */
2948 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2949 sock_doc, /* tp_doc */
2950 0, /* tp_traverse */
2951 0, /* tp_clear */
2952 0, /* tp_richcompare */
2953 0, /* tp_weaklistoffset */
2954 0, /* tp_iter */
2955 0, /* tp_iternext */
2956 sock_methods, /* tp_methods */
2957 sock_memberlist, /* tp_members */
2958 0, /* tp_getset */
2959 0, /* tp_base */
2960 0, /* tp_dict */
2961 0, /* tp_descr_get */
2962 0, /* tp_descr_set */
2963 0, /* tp_dictoffset */
2964 sock_initobj, /* tp_init */
2965 PyType_GenericAlloc, /* tp_alloc */
2966 sock_new, /* tp_new */
2967 PyObject_Del, /* tp_free */
2971 /* Python interface to gethostname(). */
2973 /*ARGSUSED*/
2974 static PyObject *
2975 socket_gethostname(PyObject *self, PyObject *unused)
2977 char buf[1024];
2978 int res;
2979 Py_BEGIN_ALLOW_THREADS
2980 res = gethostname(buf, (int) sizeof buf - 1);
2981 Py_END_ALLOW_THREADS
2982 if (res < 0)
2983 return set_error();
2984 buf[sizeof buf - 1] = '\0';
2985 return PyString_FromString(buf);
2988 PyDoc_STRVAR(gethostname_doc,
2989 "gethostname() -> string\n\
2991 Return the current host name.");
2994 /* Python interface to gethostbyname(name). */
2996 /*ARGSUSED*/
2997 static PyObject *
2998 socket_gethostbyname(PyObject *self, PyObject *args)
3000 char *name;
3001 sock_addr_t addrbuf;
3003 if (!PyArg_ParseTuple(args, "s:gethostbyname", &name))
3004 return NULL;
3005 if (setipaddr(name, SAS2SA(&addrbuf), sizeof(addrbuf), AF_INET) < 0)
3006 return NULL;
3007 return makeipaddr(SAS2SA(&addrbuf), sizeof(struct sockaddr_in));
3010 PyDoc_STRVAR(gethostbyname_doc,
3011 "gethostbyname(host) -> address\n\
3013 Return the IP address (a string of the form '255.255.255.255') for a host.");
3016 /* Convenience function common to gethostbyname_ex and gethostbyaddr */
3018 static PyObject *
3019 gethost_common(struct hostent *h, struct sockaddr *addr, int alen, int af)
3021 char **pch;
3022 PyObject *rtn_tuple = (PyObject *)NULL;
3023 PyObject *name_list = (PyObject *)NULL;
3024 PyObject *addr_list = (PyObject *)NULL;
3025 PyObject *tmp;
3027 if (h == NULL) {
3028 /* Let's get real error message to return */
3029 #ifndef RISCOS
3030 set_herror(h_errno);
3031 #else
3032 PyErr_SetString(socket_error, "host not found");
3033 #endif
3034 return NULL;
3037 if (h->h_addrtype != af) {
3038 #ifdef HAVE_STRERROR
3039 /* Let's get real error message to return */
3040 PyErr_SetString(socket_error,
3041 (char *)strerror(EAFNOSUPPORT));
3042 #else
3043 PyErr_SetString(
3044 socket_error,
3045 "Address family not supported by protocol family");
3046 #endif
3047 return NULL;
3050 switch (af) {
3052 case AF_INET:
3053 if (alen < sizeof(struct sockaddr_in))
3054 return NULL;
3055 break;
3057 #ifdef ENABLE_IPV6
3058 case AF_INET6:
3059 if (alen < sizeof(struct sockaddr_in6))
3060 return NULL;
3061 break;
3062 #endif
3066 if ((name_list = PyList_New(0)) == NULL)
3067 goto err;
3069 if ((addr_list = PyList_New(0)) == NULL)
3070 goto err;
3072 /* SF #1511317: h_aliases can be NULL */
3073 if (h->h_aliases) {
3074 for (pch = h->h_aliases; *pch != NULL; pch++) {
3075 int status;
3076 tmp = PyString_FromString(*pch);
3077 if (tmp == NULL)
3078 goto err;
3080 status = PyList_Append(name_list, tmp);
3081 Py_DECREF(tmp);
3083 if (status)
3084 goto err;
3088 for (pch = h->h_addr_list; *pch != NULL; pch++) {
3089 int status;
3091 switch (af) {
3093 case AF_INET:
3095 struct sockaddr_in sin;
3096 memset(&sin, 0, sizeof(sin));
3097 sin.sin_family = af;
3098 #ifdef HAVE_SOCKADDR_SA_LEN
3099 sin.sin_len = sizeof(sin);
3100 #endif
3101 memcpy(&sin.sin_addr, *pch, sizeof(sin.sin_addr));
3102 tmp = makeipaddr((struct sockaddr *)&sin, sizeof(sin));
3104 if (pch == h->h_addr_list && alen >= sizeof(sin))
3105 memcpy((char *) addr, &sin, sizeof(sin));
3106 break;
3109 #ifdef ENABLE_IPV6
3110 case AF_INET6:
3112 struct sockaddr_in6 sin6;
3113 memset(&sin6, 0, sizeof(sin6));
3114 sin6.sin6_family = af;
3115 #ifdef HAVE_SOCKADDR_SA_LEN
3116 sin6.sin6_len = sizeof(sin6);
3117 #endif
3118 memcpy(&sin6.sin6_addr, *pch, sizeof(sin6.sin6_addr));
3119 tmp = makeipaddr((struct sockaddr *)&sin6,
3120 sizeof(sin6));
3122 if (pch == h->h_addr_list && alen >= sizeof(sin6))
3123 memcpy((char *) addr, &sin6, sizeof(sin6));
3124 break;
3126 #endif
3128 default: /* can't happen */
3129 PyErr_SetString(socket_error,
3130 "unsupported address family");
3131 return NULL;
3134 if (tmp == NULL)
3135 goto err;
3137 status = PyList_Append(addr_list, tmp);
3138 Py_DECREF(tmp);
3140 if (status)
3141 goto err;
3144 rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list);
3146 err:
3147 Py_XDECREF(name_list);
3148 Py_XDECREF(addr_list);
3149 return rtn_tuple;
3153 /* Python interface to gethostbyname_ex(name). */
3155 /*ARGSUSED*/
3156 static PyObject *
3157 socket_gethostbyname_ex(PyObject *self, PyObject *args)
3159 char *name;
3160 struct hostent *h;
3161 #ifdef ENABLE_IPV6
3162 struct sockaddr_storage addr;
3163 #else
3164 struct sockaddr_in addr;
3165 #endif
3166 struct sockaddr *sa;
3167 PyObject *ret;
3168 #ifdef HAVE_GETHOSTBYNAME_R
3169 struct hostent hp_allocated;
3170 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
3171 struct hostent_data data;
3172 #else
3173 char buf[16384];
3174 int buf_len = (sizeof buf) - 1;
3175 int errnop;
3176 #endif
3177 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3178 int result;
3179 #endif
3180 #endif /* HAVE_GETHOSTBYNAME_R */
3182 if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name))
3183 return NULL;
3184 if (setipaddr(name, (struct sockaddr *)&addr, sizeof(addr), AF_INET) < 0)
3185 return NULL;
3186 Py_BEGIN_ALLOW_THREADS
3187 #ifdef HAVE_GETHOSTBYNAME_R
3188 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3189 result = gethostbyname_r(name, &hp_allocated, buf, buf_len,
3190 &h, &errnop);
3191 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
3192 h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
3193 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
3194 memset((void *) &data, '\0', sizeof(data));
3195 result = gethostbyname_r(name, &hp_allocated, &data);
3196 h = (result != 0) ? NULL : &hp_allocated;
3197 #endif
3198 #else /* not HAVE_GETHOSTBYNAME_R */
3199 #ifdef USE_GETHOSTBYNAME_LOCK
3200 PyThread_acquire_lock(netdb_lock, 1);
3201 #endif
3202 h = gethostbyname(name);
3203 #endif /* HAVE_GETHOSTBYNAME_R */
3204 Py_END_ALLOW_THREADS
3205 /* Some C libraries would require addr.__ss_family instead of
3206 addr.ss_family.
3207 Therefore, we cast the sockaddr_storage into sockaddr to
3208 access sa_family. */
3209 sa = (struct sockaddr*)&addr;
3210 ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr),
3211 sa->sa_family);
3212 #ifdef USE_GETHOSTBYNAME_LOCK
3213 PyThread_release_lock(netdb_lock);
3214 #endif
3215 return ret;
3218 PyDoc_STRVAR(ghbn_ex_doc,
3219 "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
3221 Return the true host name, a list of aliases, and a list of IP addresses,\n\
3222 for a host. The host argument is a string giving a host name or IP number.");
3225 /* Python interface to gethostbyaddr(IP). */
3227 /*ARGSUSED*/
3228 static PyObject *
3229 socket_gethostbyaddr(PyObject *self, PyObject *args)
3231 #ifdef ENABLE_IPV6
3232 struct sockaddr_storage addr;
3233 #else
3234 struct sockaddr_in addr;
3235 #endif
3236 struct sockaddr *sa = (struct sockaddr *)&addr;
3237 char *ip_num;
3238 struct hostent *h;
3239 PyObject *ret;
3240 #ifdef HAVE_GETHOSTBYNAME_R
3241 struct hostent hp_allocated;
3242 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
3243 struct hostent_data data;
3244 #else
3245 char buf[16384];
3246 int buf_len = (sizeof buf) - 1;
3247 int errnop;
3248 #endif
3249 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3250 int result;
3251 #endif
3252 #endif /* HAVE_GETHOSTBYNAME_R */
3253 char *ap;
3254 int al;
3255 int af;
3257 if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num))
3258 return NULL;
3259 af = AF_UNSPEC;
3260 if (setipaddr(ip_num, sa, sizeof(addr), af) < 0)
3261 return NULL;
3262 af = sa->sa_family;
3263 ap = NULL;
3264 al = 0;
3265 switch (af) {
3266 case AF_INET:
3267 ap = (char *)&((struct sockaddr_in *)sa)->sin_addr;
3268 al = sizeof(((struct sockaddr_in *)sa)->sin_addr);
3269 break;
3270 #ifdef ENABLE_IPV6
3271 case AF_INET6:
3272 ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr;
3273 al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr);
3274 break;
3275 #endif
3276 default:
3277 PyErr_SetString(socket_error, "unsupported address family");
3278 return NULL;
3280 Py_BEGIN_ALLOW_THREADS
3281 #ifdef HAVE_GETHOSTBYNAME_R
3282 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3283 result = gethostbyaddr_r(ap, al, af,
3284 &hp_allocated, buf, buf_len,
3285 &h, &errnop);
3286 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
3287 h = gethostbyaddr_r(ap, al, af,
3288 &hp_allocated, buf, buf_len, &errnop);
3289 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
3290 memset((void *) &data, '\0', sizeof(data));
3291 result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data);
3292 h = (result != 0) ? NULL : &hp_allocated;
3293 #endif
3294 #else /* not HAVE_GETHOSTBYNAME_R */
3295 #ifdef USE_GETHOSTBYNAME_LOCK
3296 PyThread_acquire_lock(netdb_lock, 1);
3297 #endif
3298 h = gethostbyaddr(ap, al, af);
3299 #endif /* HAVE_GETHOSTBYNAME_R */
3300 Py_END_ALLOW_THREADS
3301 ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), af);
3302 #ifdef USE_GETHOSTBYNAME_LOCK
3303 PyThread_release_lock(netdb_lock);
3304 #endif
3305 return ret;
3308 PyDoc_STRVAR(gethostbyaddr_doc,
3309 "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
3311 Return the true host name, a list of aliases, and a list of IP addresses,\n\
3312 for a host. The host argument is a string giving a host name or IP number.");
3315 /* Python interface to getservbyname(name).
3316 This only returns the port number, since the other info is already
3317 known or not useful (like the list of aliases). */
3319 /*ARGSUSED*/
3320 static PyObject *
3321 socket_getservbyname(PyObject *self, PyObject *args)
3323 char *name, *proto=NULL;
3324 struct servent *sp;
3325 if (!PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto))
3326 return NULL;
3327 Py_BEGIN_ALLOW_THREADS
3328 sp = getservbyname(name, proto);
3329 Py_END_ALLOW_THREADS
3330 if (sp == NULL) {
3331 PyErr_SetString(socket_error, "service/proto not found");
3332 return NULL;
3334 return PyInt_FromLong((long) ntohs(sp->s_port));
3337 PyDoc_STRVAR(getservbyname_doc,
3338 "getservbyname(servicename[, protocolname]) -> integer\n\
3340 Return a port number from a service name and protocol name.\n\
3341 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3342 otherwise any protocol will match.");
3345 /* Python interface to getservbyport(port).
3346 This only returns the service name, since the other info is already
3347 known or not useful (like the list of aliases). */
3349 /*ARGSUSED*/
3350 static PyObject *
3351 socket_getservbyport(PyObject *self, PyObject *args)
3353 unsigned short port;
3354 char *proto=NULL;
3355 struct servent *sp;
3356 if (!PyArg_ParseTuple(args, "H|s:getservbyport", &port, &proto))
3357 return NULL;
3358 Py_BEGIN_ALLOW_THREADS
3359 sp = getservbyport(htons(port), proto);
3360 Py_END_ALLOW_THREADS
3361 if (sp == NULL) {
3362 PyErr_SetString(socket_error, "port/proto not found");
3363 return NULL;
3365 return PyString_FromString(sp->s_name);
3368 PyDoc_STRVAR(getservbyport_doc,
3369 "getservbyport(port[, protocolname]) -> string\n\
3371 Return the service name from a port number and protocol name.\n\
3372 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3373 otherwise any protocol will match.");
3375 /* Python interface to getprotobyname(name).
3376 This only returns the protocol number, since the other info is
3377 already known or not useful (like the list of aliases). */
3379 /*ARGSUSED*/
3380 static PyObject *
3381 socket_getprotobyname(PyObject *self, PyObject *args)
3383 char *name;
3384 struct protoent *sp;
3385 #ifdef __BEOS__
3386 /* Not available in BeOS yet. - [cjh] */
3387 PyErr_SetString(socket_error, "getprotobyname not supported");
3388 return NULL;
3389 #else
3390 if (!PyArg_ParseTuple(args, "s:getprotobyname", &name))
3391 return NULL;
3392 Py_BEGIN_ALLOW_THREADS
3393 sp = getprotobyname(name);
3394 Py_END_ALLOW_THREADS
3395 if (sp == NULL) {
3396 PyErr_SetString(socket_error, "protocol not found");
3397 return NULL;
3399 return PyInt_FromLong((long) sp->p_proto);
3400 #endif
3403 PyDoc_STRVAR(getprotobyname_doc,
3404 "getprotobyname(name) -> integer\n\
3406 Return the protocol number for the named protocol. (Rarely used.)");
3409 #ifdef HAVE_SOCKETPAIR
3410 /* Create a pair of sockets using the socketpair() function.
3411 Arguments as for socket() except the default family is AF_UNIX if
3412 defined on the platform; otherwise, the default is AF_INET. */
3414 /*ARGSUSED*/
3415 static PyObject *
3416 socket_socketpair(PyObject *self, PyObject *args)
3418 PySocketSockObject *s0 = NULL, *s1 = NULL;
3419 SOCKET_T sv[2];
3420 int family, type = SOCK_STREAM, proto = 0;
3421 PyObject *res = NULL;
3423 #if defined(AF_UNIX)
3424 family = AF_UNIX;
3425 #else
3426 family = AF_INET;
3427 #endif
3428 if (!PyArg_ParseTuple(args, "|iii:socketpair",
3429 &family, &type, &proto))
3430 return NULL;
3431 /* Create a pair of socket fds */
3432 if (socketpair(family, type, proto, sv) < 0)
3433 return set_error();
3434 s0 = new_sockobject(sv[0], family, type, proto);
3435 if (s0 == NULL)
3436 goto finally;
3437 s1 = new_sockobject(sv[1], family, type, proto);
3438 if (s1 == NULL)
3439 goto finally;
3440 res = PyTuple_Pack(2, s0, s1);
3442 finally:
3443 if (res == NULL) {
3444 if (s0 == NULL)
3445 SOCKETCLOSE(sv[0]);
3446 if (s1 == NULL)
3447 SOCKETCLOSE(sv[1]);
3449 Py_XDECREF(s0);
3450 Py_XDECREF(s1);
3451 return res;
3454 PyDoc_STRVAR(socketpair_doc,
3455 "socketpair([family[, type[, proto]]]) -> (socket object, socket object)\n\
3457 Create a pair of socket objects from the sockets returned by the platform\n\
3458 socketpair() function.\n\
3459 The arguments are the same as for socket() except the default family is\n\
3460 AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");
3462 #endif /* HAVE_SOCKETPAIR */
3465 #ifndef NO_DUP
3466 /* Create a socket object from a numeric file description.
3467 Useful e.g. if stdin is a socket.
3468 Additional arguments as for socket(). */
3470 /*ARGSUSED*/
3471 static PyObject *
3472 socket_fromfd(PyObject *self, PyObject *args)
3474 PySocketSockObject *s;
3475 SOCKET_T fd;
3476 int family, type, proto = 0;
3477 if (!PyArg_ParseTuple(args, "iii|i:fromfd",
3478 &fd, &family, &type, &proto))
3479 return NULL;
3480 /* Dup the fd so it and the socket can be closed independently */
3481 fd = dup(fd);
3482 if (fd < 0)
3483 return set_error();
3484 s = new_sockobject(fd, family, type, proto);
3485 return (PyObject *) s;
3488 PyDoc_STRVAR(fromfd_doc,
3489 "fromfd(fd, family, type[, proto]) -> socket object\n\
3491 Create a socket object from a duplicate of the given\n\
3492 file descriptor.\n\
3493 The remaining arguments are the same as for socket().");
3495 #endif /* NO_DUP */
3498 static PyObject *
3499 socket_ntohs(PyObject *self, PyObject *args)
3501 int x1, x2;
3503 if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) {
3504 return NULL;
3506 if (x1 < 0) {
3507 PyErr_SetString(PyExc_OverflowError,
3508 "can't convert negative number to unsigned long");
3509 return NULL;
3511 x2 = (unsigned int)ntohs((unsigned short)x1);
3512 return PyInt_FromLong(x2);
3515 PyDoc_STRVAR(ntohs_doc,
3516 "ntohs(integer) -> integer\n\
3518 Convert a 16-bit integer from network to host byte order.");
3521 static PyObject *
3522 socket_ntohl(PyObject *self, PyObject *arg)
3524 unsigned long x;
3526 if (PyInt_Check(arg)) {
3527 x = PyInt_AS_LONG(arg);
3528 if (x == (unsigned long) -1 && PyErr_Occurred())
3529 return NULL;
3530 if ((long)x < 0) {
3531 PyErr_SetString(PyExc_OverflowError,
3532 "can't convert negative number to unsigned long");
3533 return NULL;
3536 else if (PyLong_Check(arg)) {
3537 x = PyLong_AsUnsignedLong(arg);
3538 if (x == (unsigned long) -1 && PyErr_Occurred())
3539 return NULL;
3540 #if SIZEOF_LONG > 4
3542 unsigned long y;
3543 /* only want the trailing 32 bits */
3544 y = x & 0xFFFFFFFFUL;
3545 if (y ^ x)
3546 return PyErr_Format(PyExc_OverflowError,
3547 "long int larger than 32 bits");
3548 x = y;
3550 #endif
3552 else
3553 return PyErr_Format(PyExc_TypeError,
3554 "expected int/long, %s found",
3555 arg->ob_type->tp_name);
3556 if (x == (unsigned long) -1 && PyErr_Occurred())
3557 return NULL;
3558 return PyLong_FromUnsignedLong(ntohl(x));
3561 PyDoc_STRVAR(ntohl_doc,
3562 "ntohl(integer) -> integer\n\
3564 Convert a 32-bit integer from network to host byte order.");
3567 static PyObject *
3568 socket_htons(PyObject *self, PyObject *args)
3570 int x1, x2;
3572 if (!PyArg_ParseTuple(args, "i:htons", &x1)) {
3573 return NULL;
3575 if (x1 < 0) {
3576 PyErr_SetString(PyExc_OverflowError,
3577 "can't convert negative number to unsigned long");
3578 return NULL;
3580 x2 = (unsigned int)htons((unsigned short)x1);
3581 return PyInt_FromLong(x2);
3584 PyDoc_STRVAR(htons_doc,
3585 "htons(integer) -> integer\n\
3587 Convert a 16-bit integer from host to network byte order.");
3590 static PyObject *
3591 socket_htonl(PyObject *self, PyObject *arg)
3593 unsigned long x;
3595 if (PyInt_Check(arg)) {
3596 x = PyInt_AS_LONG(arg);
3597 if (x == (unsigned long) -1 && PyErr_Occurred())
3598 return NULL;
3599 if ((long)x < 0) {
3600 PyErr_SetString(PyExc_OverflowError,
3601 "can't convert negative number to unsigned long");
3602 return NULL;
3605 else if (PyLong_Check(arg)) {
3606 x = PyLong_AsUnsignedLong(arg);
3607 if (x == (unsigned long) -1 && PyErr_Occurred())
3608 return NULL;
3609 #if SIZEOF_LONG > 4
3611 unsigned long y;
3612 /* only want the trailing 32 bits */
3613 y = x & 0xFFFFFFFFUL;
3614 if (y ^ x)
3615 return PyErr_Format(PyExc_OverflowError,
3616 "long int larger than 32 bits");
3617 x = y;
3619 #endif
3621 else
3622 return PyErr_Format(PyExc_TypeError,
3623 "expected int/long, %s found",
3624 arg->ob_type->tp_name);
3625 return PyLong_FromUnsignedLong(htonl((unsigned long)x));
3628 PyDoc_STRVAR(htonl_doc,
3629 "htonl(integer) -> integer\n\
3631 Convert a 32-bit integer from host to network byte order.");
3633 /* socket.inet_aton() and socket.inet_ntoa() functions. */
3635 PyDoc_STRVAR(inet_aton_doc,
3636 "inet_aton(string) -> packed 32-bit IP representation\n\
3638 Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
3639 binary format used in low-level network functions.");
3641 static PyObject*
3642 socket_inet_aton(PyObject *self, PyObject *args)
3644 #ifndef INADDR_NONE
3645 #define INADDR_NONE (-1)
3646 #endif
3647 #ifdef HAVE_INET_ATON
3648 struct in_addr buf;
3649 #endif
3651 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
3652 /* Have to use inet_addr() instead */
3653 unsigned long packed_addr;
3654 #endif
3655 char *ip_addr;
3657 if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr))
3658 return NULL;
3661 #ifdef HAVE_INET_ATON
3663 #ifdef USE_INET_ATON_WEAKLINK
3664 if (inet_aton != NULL) {
3665 #endif
3666 if (inet_aton(ip_addr, &buf))
3667 return PyString_FromStringAndSize((char *)(&buf),
3668 sizeof(buf));
3670 PyErr_SetString(socket_error,
3671 "illegal IP address string passed to inet_aton");
3672 return NULL;
3674 #ifdef USE_INET_ATON_WEAKLINK
3675 } else {
3676 #endif
3678 #endif
3680 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
3682 /* special-case this address as inet_addr might return INADDR_NONE
3683 * for this */
3684 if (strcmp(ip_addr, "255.255.255.255") == 0) {
3685 packed_addr = 0xFFFFFFFF;
3686 } else {
3688 packed_addr = inet_addr(ip_addr);
3690 if (packed_addr == INADDR_NONE) { /* invalid address */
3691 PyErr_SetString(socket_error,
3692 "illegal IP address string passed to inet_aton");
3693 return NULL;
3696 return PyString_FromStringAndSize((char *) &packed_addr,
3697 sizeof(packed_addr));
3699 #ifdef USE_INET_ATON_WEAKLINK
3701 #endif
3703 #endif
3706 PyDoc_STRVAR(inet_ntoa_doc,
3707 "inet_ntoa(packed_ip) -> ip_address_string\n\
3709 Convert an IP address from 32-bit packed binary format to string format");
3711 static PyObject*
3712 socket_inet_ntoa(PyObject *self, PyObject *args)
3714 char *packed_str;
3715 int addr_len;
3716 struct in_addr packed_addr;
3718 if (!PyArg_ParseTuple(args, "s#:inet_ntoa", &packed_str, &addr_len)) {
3719 return NULL;
3722 if (addr_len != sizeof(packed_addr)) {
3723 PyErr_SetString(socket_error,
3724 "packed IP wrong length for inet_ntoa");
3725 return NULL;
3728 memcpy(&packed_addr, packed_str, addr_len);
3730 return PyString_FromString(inet_ntoa(packed_addr));
3733 #ifdef HAVE_INET_PTON
3735 PyDoc_STRVAR(inet_pton_doc,
3736 "inet_pton(af, ip) -> packed IP address string\n\
3738 Convert an IP address from string format to a packed string suitable\n\
3739 for use with low-level network functions.");
3741 static PyObject *
3742 socket_inet_pton(PyObject *self, PyObject *args)
3744 int af;
3745 char* ip;
3746 int retval;
3747 #ifdef ENABLE_IPV6
3748 char packed[MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
3749 #else
3750 char packed[sizeof(struct in_addr)];
3751 #endif
3752 if (!PyArg_ParseTuple(args, "is:inet_pton", &af, &ip)) {
3753 return NULL;
3756 #if !defined(ENABLE_IPV6) && defined(AF_INET6)
3757 if(af == AF_INET6) {
3758 PyErr_SetString(socket_error,
3759 "can't use AF_INET6, IPv6 is disabled");
3760 return NULL;
3762 #endif
3764 retval = inet_pton(af, ip, packed);
3765 if (retval < 0) {
3766 PyErr_SetFromErrno(socket_error);
3767 return NULL;
3768 } else if (retval == 0) {
3769 PyErr_SetString(socket_error,
3770 "illegal IP address string passed to inet_pton");
3771 return NULL;
3772 } else if (af == AF_INET) {
3773 return PyString_FromStringAndSize(packed,
3774 sizeof(struct in_addr));
3775 #ifdef ENABLE_IPV6
3776 } else if (af == AF_INET6) {
3777 return PyString_FromStringAndSize(packed,
3778 sizeof(struct in6_addr));
3779 #endif
3780 } else {
3781 PyErr_SetString(socket_error, "unknown address family");
3782 return NULL;
3786 PyDoc_STRVAR(inet_ntop_doc,
3787 "inet_ntop(af, packed_ip) -> string formatted IP address\n\
3789 Convert a packed IP address of the given family to string format.");
3791 static PyObject *
3792 socket_inet_ntop(PyObject *self, PyObject *args)
3794 int af;
3795 char* packed;
3796 int len;
3797 const char* retval;
3798 #ifdef ENABLE_IPV6
3799 char ip[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) + 1];
3800 #else
3801 char ip[INET_ADDRSTRLEN + 1];
3802 #endif
3804 /* Guarantee NUL-termination for PyString_FromString() below */
3805 memset((void *) &ip[0], '\0', sizeof(ip));
3807 if (!PyArg_ParseTuple(args, "is#:inet_ntop", &af, &packed, &len)) {
3808 return NULL;
3811 if (af == AF_INET) {
3812 if (len != sizeof(struct in_addr)) {
3813 PyErr_SetString(PyExc_ValueError,
3814 "invalid length of packed IP address string");
3815 return NULL;
3817 #ifdef ENABLE_IPV6
3818 } else if (af == AF_INET6) {
3819 if (len != sizeof(struct in6_addr)) {
3820 PyErr_SetString(PyExc_ValueError,
3821 "invalid length of packed IP address string");
3822 return NULL;
3824 #endif
3825 } else {
3826 PyErr_Format(PyExc_ValueError,
3827 "unknown address family %d", af);
3828 return NULL;
3831 retval = inet_ntop(af, packed, ip, sizeof(ip));
3832 if (!retval) {
3833 PyErr_SetFromErrno(socket_error);
3834 return NULL;
3835 } else {
3836 return PyString_FromString(retval);
3839 /* NOTREACHED */
3840 PyErr_SetString(PyExc_RuntimeError, "invalid handling of inet_ntop");
3841 return NULL;
3844 #endif /* HAVE_INET_PTON */
3846 /* Python interface to getaddrinfo(host, port). */
3848 /*ARGSUSED*/
3849 static PyObject *
3850 socket_getaddrinfo(PyObject *self, PyObject *args)
3852 struct addrinfo hints, *res;
3853 struct addrinfo *res0 = NULL;
3854 PyObject *hobj = NULL;
3855 PyObject *pobj = (PyObject *)NULL;
3856 char pbuf[30];
3857 char *hptr, *pptr;
3858 int family, socktype, protocol, flags;
3859 int error;
3860 PyObject *all = (PyObject *)NULL;
3861 PyObject *single = (PyObject *)NULL;
3862 PyObject *idna = NULL;
3864 family = socktype = protocol = flags = 0;
3865 family = AF_UNSPEC;
3866 if (!PyArg_ParseTuple(args, "OO|iiii:getaddrinfo",
3867 &hobj, &pobj, &family, &socktype,
3868 &protocol, &flags)) {
3869 return NULL;
3871 if (hobj == Py_None) {
3872 hptr = NULL;
3873 } else if (PyUnicode_Check(hobj)) {
3874 idna = PyObject_CallMethod(hobj, "encode", "s", "idna");
3875 if (!idna)
3876 return NULL;
3877 hptr = PyString_AsString(idna);
3878 } else if (PyString_Check(hobj)) {
3879 hptr = PyString_AsString(hobj);
3880 } else {
3881 PyErr_SetString(PyExc_TypeError,
3882 "getaddrinfo() argument 1 must be string or None");
3883 return NULL;
3885 if (PyInt_Check(pobj)) {
3886 PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", PyInt_AsLong(pobj));
3887 pptr = pbuf;
3888 } else if (PyString_Check(pobj)) {
3889 pptr = PyString_AsString(pobj);
3890 } else if (pobj == Py_None) {
3891 pptr = (char *)NULL;
3892 } else {
3893 PyErr_SetString(socket_error, "Int or String expected");
3894 goto err;
3896 memset(&hints, 0, sizeof(hints));
3897 hints.ai_family = family;
3898 hints.ai_socktype = socktype;
3899 hints.ai_protocol = protocol;
3900 hints.ai_flags = flags;
3901 Py_BEGIN_ALLOW_THREADS
3902 ACQUIRE_GETADDRINFO_LOCK
3903 error = getaddrinfo(hptr, pptr, &hints, &res0);
3904 Py_END_ALLOW_THREADS
3905 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
3906 if (error) {
3907 set_gaierror(error);
3908 goto err;
3911 if ((all = PyList_New(0)) == NULL)
3912 goto err;
3913 for (res = res0; res; res = res->ai_next) {
3914 PyObject *addr =
3915 makesockaddr(-1, res->ai_addr, res->ai_addrlen, protocol);
3916 if (addr == NULL)
3917 goto err;
3918 single = Py_BuildValue("iiisO", res->ai_family,
3919 res->ai_socktype, res->ai_protocol,
3920 res->ai_canonname ? res->ai_canonname : "",
3921 addr);
3922 Py_DECREF(addr);
3923 if (single == NULL)
3924 goto err;
3926 if (PyList_Append(all, single))
3927 goto err;
3928 Py_XDECREF(single);
3930 Py_XDECREF(idna);
3931 if (res0)
3932 freeaddrinfo(res0);
3933 return all;
3934 err:
3935 Py_XDECREF(single);
3936 Py_XDECREF(all);
3937 Py_XDECREF(idna);
3938 if (res0)
3939 freeaddrinfo(res0);
3940 return (PyObject *)NULL;
3943 PyDoc_STRVAR(getaddrinfo_doc,
3944 "getaddrinfo(host, port [, family, socktype, proto, flags])\n\
3945 -> list of (family, socktype, proto, canonname, sockaddr)\n\
3947 Resolve host and port into addrinfo struct.");
3949 /* Python interface to getnameinfo(sa, flags). */
3951 /*ARGSUSED*/
3952 static PyObject *
3953 socket_getnameinfo(PyObject *self, PyObject *args)
3955 PyObject *sa = (PyObject *)NULL;
3956 int flags;
3957 char *hostp;
3958 int port, flowinfo, scope_id;
3959 char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
3960 struct addrinfo hints, *res = NULL;
3961 int error;
3962 PyObject *ret = (PyObject *)NULL;
3964 flags = flowinfo = scope_id = 0;
3965 if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags))
3966 return NULL;
3967 if (!PyArg_ParseTuple(sa, "si|ii",
3968 &hostp, &port, &flowinfo, &scope_id))
3969 return NULL;
3970 PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port);
3971 memset(&hints, 0, sizeof(hints));
3972 hints.ai_family = AF_UNSPEC;
3973 hints.ai_socktype = SOCK_DGRAM; /* make numeric port happy */
3974 Py_BEGIN_ALLOW_THREADS
3975 ACQUIRE_GETADDRINFO_LOCK
3976 error = getaddrinfo(hostp, pbuf, &hints, &res);
3977 Py_END_ALLOW_THREADS
3978 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
3979 if (error) {
3980 set_gaierror(error);
3981 goto fail;
3983 if (res->ai_next) {
3984 PyErr_SetString(socket_error,
3985 "sockaddr resolved to multiple addresses");
3986 goto fail;
3988 switch (res->ai_family) {
3989 case AF_INET:
3991 char *t1;
3992 int t2;
3993 if (PyArg_ParseTuple(sa, "si", &t1, &t2) == 0) {
3994 PyErr_SetString(socket_error,
3995 "IPv4 sockaddr must be 2 tuple");
3996 goto fail;
3998 break;
4000 #ifdef ENABLE_IPV6
4001 case AF_INET6:
4003 struct sockaddr_in6 *sin6;
4004 sin6 = (struct sockaddr_in6 *)res->ai_addr;
4005 sin6->sin6_flowinfo = flowinfo;
4006 sin6->sin6_scope_id = scope_id;
4007 break;
4009 #endif
4011 error = getnameinfo(res->ai_addr, res->ai_addrlen,
4012 hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags);
4013 if (error) {
4014 set_gaierror(error);
4015 goto fail;
4017 ret = Py_BuildValue("ss", hbuf, pbuf);
4019 fail:
4020 if (res)
4021 freeaddrinfo(res);
4022 return ret;
4025 PyDoc_STRVAR(getnameinfo_doc,
4026 "getnameinfo(sockaddr, flags) --> (host, port)\n\
4028 Get host and port for a sockaddr.");
4031 /* Python API to getting and setting the default timeout value. */
4033 static PyObject *
4034 socket_getdefaulttimeout(PyObject *self)
4036 if (defaulttimeout < 0.0) {
4037 Py_INCREF(Py_None);
4038 return Py_None;
4040 else
4041 return PyFloat_FromDouble(defaulttimeout);
4044 PyDoc_STRVAR(getdefaulttimeout_doc,
4045 "getdefaulttimeout() -> timeout\n\
4047 Returns the default timeout in floating seconds for new socket objects.\n\
4048 A value of None indicates that new socket objects have no timeout.\n\
4049 When the socket module is first imported, the default is None.");
4051 static PyObject *
4052 socket_setdefaulttimeout(PyObject *self, PyObject *arg)
4054 double timeout;
4056 if (arg == Py_None)
4057 timeout = -1.0;
4058 else {
4059 timeout = PyFloat_AsDouble(arg);
4060 if (timeout < 0.0) {
4061 if (!PyErr_Occurred())
4062 PyErr_SetString(PyExc_ValueError,
4063 "Timeout value out of range");
4064 return NULL;
4068 defaulttimeout = timeout;
4070 Py_INCREF(Py_None);
4071 return Py_None;
4074 PyDoc_STRVAR(setdefaulttimeout_doc,
4075 "setdefaulttimeout(timeout)\n\
4077 Set the default timeout in floating seconds for new socket objects.\n\
4078 A value of None indicates that new socket objects have no timeout.\n\
4079 When the socket module is first imported, the default is None.");
4082 /* List of functions exported by this module. */
4084 static PyMethodDef socket_methods[] = {
4085 {"gethostbyname", socket_gethostbyname,
4086 METH_VARARGS, gethostbyname_doc},
4087 {"gethostbyname_ex", socket_gethostbyname_ex,
4088 METH_VARARGS, ghbn_ex_doc},
4089 {"gethostbyaddr", socket_gethostbyaddr,
4090 METH_VARARGS, gethostbyaddr_doc},
4091 {"gethostname", socket_gethostname,
4092 METH_NOARGS, gethostname_doc},
4093 {"getservbyname", socket_getservbyname,
4094 METH_VARARGS, getservbyname_doc},
4095 {"getservbyport", socket_getservbyport,
4096 METH_VARARGS, getservbyport_doc},
4097 {"getprotobyname", socket_getprotobyname,
4098 METH_VARARGS, getprotobyname_doc},
4099 #ifndef NO_DUP
4100 {"fromfd", socket_fromfd,
4101 METH_VARARGS, fromfd_doc},
4102 #endif
4103 #ifdef HAVE_SOCKETPAIR
4104 {"socketpair", socket_socketpair,
4105 METH_VARARGS, socketpair_doc},
4106 #endif
4107 {"ntohs", socket_ntohs,
4108 METH_VARARGS, ntohs_doc},
4109 {"ntohl", socket_ntohl,
4110 METH_O, ntohl_doc},
4111 {"htons", socket_htons,
4112 METH_VARARGS, htons_doc},
4113 {"htonl", socket_htonl,
4114 METH_O, htonl_doc},
4115 {"inet_aton", socket_inet_aton,
4116 METH_VARARGS, inet_aton_doc},
4117 {"inet_ntoa", socket_inet_ntoa,
4118 METH_VARARGS, inet_ntoa_doc},
4119 #ifdef HAVE_INET_PTON
4120 {"inet_pton", socket_inet_pton,
4121 METH_VARARGS, inet_pton_doc},
4122 {"inet_ntop", socket_inet_ntop,
4123 METH_VARARGS, inet_ntop_doc},
4124 #endif
4125 {"getaddrinfo", socket_getaddrinfo,
4126 METH_VARARGS, getaddrinfo_doc},
4127 {"getnameinfo", socket_getnameinfo,
4128 METH_VARARGS, getnameinfo_doc},
4129 {"getdefaulttimeout", (PyCFunction)socket_getdefaulttimeout,
4130 METH_NOARGS, getdefaulttimeout_doc},
4131 {"setdefaulttimeout", socket_setdefaulttimeout,
4132 METH_O, setdefaulttimeout_doc},
4133 {NULL, NULL} /* Sentinel */
4137 #ifdef RISCOS
4138 #define OS_INIT_DEFINED
4140 static int
4141 os_init(void)
4143 _kernel_swi_regs r;
4145 r.r[0] = 0;
4146 _kernel_swi(0x43380, &r, &r);
4147 taskwindow = r.r[0];
4149 return 1;
4152 #endif /* RISCOS */
4155 #ifdef MS_WINDOWS
4156 #define OS_INIT_DEFINED
4158 /* Additional initialization and cleanup for Windows */
4160 static void
4161 os_cleanup(void)
4163 WSACleanup();
4166 static int
4167 os_init(void)
4169 WSADATA WSAData;
4170 int ret;
4171 char buf[100];
4172 ret = WSAStartup(0x0101, &WSAData);
4173 switch (ret) {
4174 case 0: /* No error */
4175 Py_AtExit(os_cleanup);
4176 return 1; /* Success */
4177 case WSASYSNOTREADY:
4178 PyErr_SetString(PyExc_ImportError,
4179 "WSAStartup failed: network not ready");
4180 break;
4181 case WSAVERNOTSUPPORTED:
4182 case WSAEINVAL:
4183 PyErr_SetString(
4184 PyExc_ImportError,
4185 "WSAStartup failed: requested version not supported");
4186 break;
4187 default:
4188 PyOS_snprintf(buf, sizeof(buf),
4189 "WSAStartup failed: error code %d", ret);
4190 PyErr_SetString(PyExc_ImportError, buf);
4191 break;
4193 return 0; /* Failure */
4196 #endif /* MS_WINDOWS */
4199 #ifdef PYOS_OS2
4200 #define OS_INIT_DEFINED
4202 /* Additional initialization for OS/2 */
4204 static int
4205 os_init(void)
4207 #ifndef PYCC_GCC
4208 char reason[64];
4209 int rc = sock_init();
4211 if (rc == 0) {
4212 return 1; /* Success */
4215 PyOS_snprintf(reason, sizeof(reason),
4216 "OS/2 TCP/IP Error# %d", sock_errno());
4217 PyErr_SetString(PyExc_ImportError, reason);
4219 return 0; /* Failure */
4220 #else
4221 /* No need to initialise sockets with GCC/EMX */
4222 return 1; /* Success */
4223 #endif
4226 #endif /* PYOS_OS2 */
4229 #ifndef OS_INIT_DEFINED
4230 static int
4231 os_init(void)
4233 return 1; /* Success */
4235 #endif
4238 /* C API table - always add new things to the end for binary
4239 compatibility. */
4240 static
4241 PySocketModule_APIObject PySocketModuleAPI =
4243 &sock_type,
4244 NULL
4248 /* Initialize the _socket module.
4250 This module is actually called "_socket", and there's a wrapper
4251 "socket.py" which implements some additional functionality. On some
4252 platforms (e.g. Windows and OS/2), socket.py also implements a
4253 wrapper for the socket type that provides missing functionality such
4254 as makefile(), dup() and fromfd(). The import of "_socket" may fail
4255 with an ImportError exception if os-specific initialization fails.
4256 On Windows, this does WINSOCK initialization. When WINSOCK is
4257 initialized succesfully, a call to WSACleanup() is scheduled to be
4258 made at exit time.
4261 PyDoc_STRVAR(socket_doc,
4262 "Implementation module for socket operations.\n\
4264 See the socket module for documentation.");
4266 PyMODINIT_FUNC
4267 init_socket(void)
4269 PyObject *m, *has_ipv6;
4271 if (!os_init())
4272 return;
4274 sock_type.ob_type = &PyType_Type;
4275 m = Py_InitModule3(PySocket_MODULE_NAME,
4276 socket_methods,
4277 socket_doc);
4278 if (m == NULL)
4279 return;
4281 socket_error = PyErr_NewException("socket.error", NULL, NULL);
4282 if (socket_error == NULL)
4283 return;
4284 PySocketModuleAPI.error = socket_error;
4285 Py_INCREF(socket_error);
4286 PyModule_AddObject(m, "error", socket_error);
4287 socket_herror = PyErr_NewException("socket.herror",
4288 socket_error, NULL);
4289 if (socket_herror == NULL)
4290 return;
4291 Py_INCREF(socket_herror);
4292 PyModule_AddObject(m, "herror", socket_herror);
4293 socket_gaierror = PyErr_NewException("socket.gaierror", socket_error,
4294 NULL);
4295 if (socket_gaierror == NULL)
4296 return;
4297 Py_INCREF(socket_gaierror);
4298 PyModule_AddObject(m, "gaierror", socket_gaierror);
4299 socket_timeout = PyErr_NewException("socket.timeout",
4300 socket_error, NULL);
4301 if (socket_timeout == NULL)
4302 return;
4303 Py_INCREF(socket_timeout);
4304 PyModule_AddObject(m, "timeout", socket_timeout);
4305 Py_INCREF((PyObject *)&sock_type);
4306 if (PyModule_AddObject(m, "SocketType",
4307 (PyObject *)&sock_type) != 0)
4308 return;
4309 Py_INCREF((PyObject *)&sock_type);
4310 if (PyModule_AddObject(m, "socket",
4311 (PyObject *)&sock_type) != 0)
4312 return;
4314 #ifdef ENABLE_IPV6
4315 has_ipv6 = Py_True;
4316 #else
4317 has_ipv6 = Py_False;
4318 #endif
4319 Py_INCREF(has_ipv6);
4320 PyModule_AddObject(m, "has_ipv6", has_ipv6);
4322 /* Export C API */
4323 if (PyModule_AddObject(m, PySocket_CAPI_NAME,
4324 PyCObject_FromVoidPtr((void *)&PySocketModuleAPI, NULL)
4325 ) != 0)
4326 return;
4328 /* Address families (we only support AF_INET and AF_UNIX) */
4329 #ifdef AF_UNSPEC
4330 PyModule_AddIntConstant(m, "AF_UNSPEC", AF_UNSPEC);
4331 #endif
4332 PyModule_AddIntConstant(m, "AF_INET", AF_INET);
4333 #ifdef AF_INET6
4334 PyModule_AddIntConstant(m, "AF_INET6", AF_INET6);
4335 #endif /* AF_INET6 */
4336 #if defined(AF_UNIX)
4337 PyModule_AddIntConstant(m, "AF_UNIX", AF_UNIX);
4338 #endif /* AF_UNIX */
4339 #ifdef AF_AX25
4340 /* Amateur Radio AX.25 */
4341 PyModule_AddIntConstant(m, "AF_AX25", AF_AX25);
4342 #endif
4343 #ifdef AF_IPX
4344 PyModule_AddIntConstant(m, "AF_IPX", AF_IPX); /* Novell IPX */
4345 #endif
4346 #ifdef AF_APPLETALK
4347 /* Appletalk DDP */
4348 PyModule_AddIntConstant(m, "AF_APPLETALK", AF_APPLETALK);
4349 #endif
4350 #ifdef AF_NETROM
4351 /* Amateur radio NetROM */
4352 PyModule_AddIntConstant(m, "AF_NETROM", AF_NETROM);
4353 #endif
4354 #ifdef AF_BRIDGE
4355 /* Multiprotocol bridge */
4356 PyModule_AddIntConstant(m, "AF_BRIDGE", AF_BRIDGE);
4357 #endif
4358 #ifdef AF_ATMPVC
4359 /* ATM PVCs */
4360 PyModule_AddIntConstant(m, "AF_ATMPVC", AF_ATMPVC);
4361 #endif
4362 #ifdef AF_AAL5
4363 /* Reserved for Werner's ATM */
4364 PyModule_AddIntConstant(m, "AF_AAL5", AF_AAL5);
4365 #endif
4366 #ifdef AF_X25
4367 /* Reserved for X.25 project */
4368 PyModule_AddIntConstant(m, "AF_X25", AF_X25);
4369 #endif
4370 #ifdef AF_INET6
4371 PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); /* IP version 6 */
4372 #endif
4373 #ifdef AF_ROSE
4374 /* Amateur Radio X.25 PLP */
4375 PyModule_AddIntConstant(m, "AF_ROSE", AF_ROSE);
4376 #endif
4377 #ifdef AF_DECnet
4378 /* Reserved for DECnet project */
4379 PyModule_AddIntConstant(m, "AF_DECnet", AF_DECnet);
4380 #endif
4381 #ifdef AF_NETBEUI
4382 /* Reserved for 802.2LLC project */
4383 PyModule_AddIntConstant(m, "AF_NETBEUI", AF_NETBEUI);
4384 #endif
4385 #ifdef AF_SECURITY
4386 /* Security callback pseudo AF */
4387 PyModule_AddIntConstant(m, "AF_SECURITY", AF_SECURITY);
4388 #endif
4389 #ifdef AF_KEY
4390 /* PF_KEY key management API */
4391 PyModule_AddIntConstant(m, "AF_KEY", AF_KEY);
4392 #endif
4393 #ifdef AF_NETLINK
4394 /* */
4395 PyModule_AddIntConstant(m, "AF_NETLINK", AF_NETLINK);
4396 PyModule_AddIntConstant(m, "NETLINK_ROUTE", NETLINK_ROUTE);
4397 #ifdef NETLINK_SKIP
4398 PyModule_AddIntConstant(m, "NETLINK_SKIP", NETLINK_SKIP);
4399 #endif
4400 #ifdef NETLINK_W1
4401 PyModule_AddIntConstant(m, "NETLINK_W1", NETLINK_W1);
4402 #endif
4403 PyModule_AddIntConstant(m, "NETLINK_USERSOCK", NETLINK_USERSOCK);
4404 PyModule_AddIntConstant(m, "NETLINK_FIREWALL", NETLINK_FIREWALL);
4405 #ifdef NETLINK_TCPDIAG
4406 PyModule_AddIntConstant(m, "NETLINK_TCPDIAG", NETLINK_TCPDIAG);
4407 #endif
4408 #ifdef NETLINK_NFLOG
4409 PyModule_AddIntConstant(m, "NETLINK_NFLOG", NETLINK_NFLOG);
4410 #endif
4411 #ifdef NETLINK_XFRM
4412 PyModule_AddIntConstant(m, "NETLINK_XFRM", NETLINK_XFRM);
4413 #endif
4414 #ifdef NETLINK_ARPD
4415 PyModule_AddIntConstant(m, "NETLINK_ARPD", NETLINK_ARPD);
4416 #endif
4417 #ifdef NETLINK_ROUTE6
4418 PyModule_AddIntConstant(m, "NETLINK_ROUTE6", NETLINK_ROUTE6);
4419 #endif
4420 PyModule_AddIntConstant(m, "NETLINK_IP6_FW", NETLINK_IP6_FW);
4421 #ifdef NETLINK_DNRTMSG
4422 PyModule_AddIntConstant(m, "NETLINK_DNRTMSG", NETLINK_DNRTMSG);
4423 #endif
4424 #ifdef NETLINK_TAPBASE
4425 PyModule_AddIntConstant(m, "NETLINK_TAPBASE", NETLINK_TAPBASE);
4426 #endif
4427 #endif /* AF_NETLINK */
4428 #ifdef AF_ROUTE
4429 /* Alias to emulate 4.4BSD */
4430 PyModule_AddIntConstant(m, "AF_ROUTE", AF_ROUTE);
4431 #endif
4432 #ifdef AF_ASH
4433 /* Ash */
4434 PyModule_AddIntConstant(m, "AF_ASH", AF_ASH);
4435 #endif
4436 #ifdef AF_ECONET
4437 /* Acorn Econet */
4438 PyModule_AddIntConstant(m, "AF_ECONET", AF_ECONET);
4439 #endif
4440 #ifdef AF_ATMSVC
4441 /* ATM SVCs */
4442 PyModule_AddIntConstant(m, "AF_ATMSVC", AF_ATMSVC);
4443 #endif
4444 #ifdef AF_SNA
4445 /* Linux SNA Project (nutters!) */
4446 PyModule_AddIntConstant(m, "AF_SNA", AF_SNA);
4447 #endif
4448 #ifdef AF_IRDA
4449 /* IRDA sockets */
4450 PyModule_AddIntConstant(m, "AF_IRDA", AF_IRDA);
4451 #endif
4452 #ifdef AF_PPPOX
4453 /* PPPoX sockets */
4454 PyModule_AddIntConstant(m, "AF_PPPOX", AF_PPPOX);
4455 #endif
4456 #ifdef AF_WANPIPE
4457 /* Wanpipe API Sockets */
4458 PyModule_AddIntConstant(m, "AF_WANPIPE", AF_WANPIPE);
4459 #endif
4460 #ifdef AF_LLC
4461 /* Linux LLC */
4462 PyModule_AddIntConstant(m, "AF_LLC", AF_LLC);
4463 #endif
4465 #ifdef USE_BLUETOOTH
4466 PyModule_AddIntConstant(m, "AF_BLUETOOTH", AF_BLUETOOTH);
4467 PyModule_AddIntConstant(m, "BTPROTO_L2CAP", BTPROTO_L2CAP);
4468 PyModule_AddIntConstant(m, "BTPROTO_HCI", BTPROTO_HCI);
4469 PyModule_AddIntConstant(m, "SOL_HCI", SOL_HCI);
4470 PyModule_AddIntConstant(m, "HCI_TIME_STAMP", HCI_TIME_STAMP);
4471 PyModule_AddIntConstant(m, "HCI_DATA_DIR", HCI_DATA_DIR);
4472 PyModule_AddIntConstant(m, "HCI_FILTER", HCI_FILTER);
4473 #if !defined(__FreeBSD__)
4474 PyModule_AddIntConstant(m, "BTPROTO_SCO", BTPROTO_SCO);
4475 #endif
4476 PyModule_AddIntConstant(m, "BTPROTO_RFCOMM", BTPROTO_RFCOMM);
4477 PyModule_AddStringConstant(m, "BDADDR_ANY", "00:00:00:00:00:00");
4478 PyModule_AddStringConstant(m, "BDADDR_LOCAL", "00:00:00:FF:FF:FF");
4479 #endif
4481 #ifdef HAVE_NETPACKET_PACKET_H
4482 PyModule_AddIntConstant(m, "AF_PACKET", AF_PACKET);
4483 PyModule_AddIntConstant(m, "PF_PACKET", PF_PACKET);
4484 PyModule_AddIntConstant(m, "PACKET_HOST", PACKET_HOST);
4485 PyModule_AddIntConstant(m, "PACKET_BROADCAST", PACKET_BROADCAST);
4486 PyModule_AddIntConstant(m, "PACKET_MULTICAST", PACKET_MULTICAST);
4487 PyModule_AddIntConstant(m, "PACKET_OTHERHOST", PACKET_OTHERHOST);
4488 PyModule_AddIntConstant(m, "PACKET_OUTGOING", PACKET_OUTGOING);
4489 PyModule_AddIntConstant(m, "PACKET_LOOPBACK", PACKET_LOOPBACK);
4490 PyModule_AddIntConstant(m, "PACKET_FASTROUTE", PACKET_FASTROUTE);
4491 #endif
4493 /* Socket types */
4494 PyModule_AddIntConstant(m, "SOCK_STREAM", SOCK_STREAM);
4495 PyModule_AddIntConstant(m, "SOCK_DGRAM", SOCK_DGRAM);
4496 #ifndef __BEOS__
4497 /* We have incomplete socket support. */
4498 PyModule_AddIntConstant(m, "SOCK_RAW", SOCK_RAW);
4499 PyModule_AddIntConstant(m, "SOCK_SEQPACKET", SOCK_SEQPACKET);
4500 #if defined(SOCK_RDM)
4501 PyModule_AddIntConstant(m, "SOCK_RDM", SOCK_RDM);
4502 #endif
4503 #endif
4505 #ifdef SO_DEBUG
4506 PyModule_AddIntConstant(m, "SO_DEBUG", SO_DEBUG);
4507 #endif
4508 #ifdef SO_ACCEPTCONN
4509 PyModule_AddIntConstant(m, "SO_ACCEPTCONN", SO_ACCEPTCONN);
4510 #endif
4511 #ifdef SO_REUSEADDR
4512 PyModule_AddIntConstant(m, "SO_REUSEADDR", SO_REUSEADDR);
4513 #endif
4514 #ifdef SO_EXCLUSIVEADDRUSE
4515 PyModule_AddIntConstant(m, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE);
4516 #endif
4518 #ifdef SO_KEEPALIVE
4519 PyModule_AddIntConstant(m, "SO_KEEPALIVE", SO_KEEPALIVE);
4520 #endif
4521 #ifdef SO_DONTROUTE
4522 PyModule_AddIntConstant(m, "SO_DONTROUTE", SO_DONTROUTE);
4523 #endif
4524 #ifdef SO_BROADCAST
4525 PyModule_AddIntConstant(m, "SO_BROADCAST", SO_BROADCAST);
4526 #endif
4527 #ifdef SO_USELOOPBACK
4528 PyModule_AddIntConstant(m, "SO_USELOOPBACK", SO_USELOOPBACK);
4529 #endif
4530 #ifdef SO_LINGER
4531 PyModule_AddIntConstant(m, "SO_LINGER", SO_LINGER);
4532 #endif
4533 #ifdef SO_OOBINLINE
4534 PyModule_AddIntConstant(m, "SO_OOBINLINE", SO_OOBINLINE);
4535 #endif
4536 #ifdef SO_REUSEPORT
4537 PyModule_AddIntConstant(m, "SO_REUSEPORT", SO_REUSEPORT);
4538 #endif
4539 #ifdef SO_SNDBUF
4540 PyModule_AddIntConstant(m, "SO_SNDBUF", SO_SNDBUF);
4541 #endif
4542 #ifdef SO_RCVBUF
4543 PyModule_AddIntConstant(m, "SO_RCVBUF", SO_RCVBUF);
4544 #endif
4545 #ifdef SO_SNDLOWAT
4546 PyModule_AddIntConstant(m, "SO_SNDLOWAT", SO_SNDLOWAT);
4547 #endif
4548 #ifdef SO_RCVLOWAT
4549 PyModule_AddIntConstant(m, "SO_RCVLOWAT", SO_RCVLOWAT);
4550 #endif
4551 #ifdef SO_SNDTIMEO
4552 PyModule_AddIntConstant(m, "SO_SNDTIMEO", SO_SNDTIMEO);
4553 #endif
4554 #ifdef SO_RCVTIMEO
4555 PyModule_AddIntConstant(m, "SO_RCVTIMEO", SO_RCVTIMEO);
4556 #endif
4557 #ifdef SO_ERROR
4558 PyModule_AddIntConstant(m, "SO_ERROR", SO_ERROR);
4559 #endif
4560 #ifdef SO_TYPE
4561 PyModule_AddIntConstant(m, "SO_TYPE", SO_TYPE);
4562 #endif
4564 /* Maximum number of connections for "listen" */
4565 #ifdef SOMAXCONN
4566 PyModule_AddIntConstant(m, "SOMAXCONN", SOMAXCONN);
4567 #else
4568 PyModule_AddIntConstant(m, "SOMAXCONN", 5); /* Common value */
4569 #endif
4571 /* Flags for send, recv */
4572 #ifdef MSG_OOB
4573 PyModule_AddIntConstant(m, "MSG_OOB", MSG_OOB);
4574 #endif
4575 #ifdef MSG_PEEK
4576 PyModule_AddIntConstant(m, "MSG_PEEK", MSG_PEEK);
4577 #endif
4578 #ifdef MSG_DONTROUTE
4579 PyModule_AddIntConstant(m, "MSG_DONTROUTE", MSG_DONTROUTE);
4580 #endif
4581 #ifdef MSG_DONTWAIT
4582 PyModule_AddIntConstant(m, "MSG_DONTWAIT", MSG_DONTWAIT);
4583 #endif
4584 #ifdef MSG_EOR
4585 PyModule_AddIntConstant(m, "MSG_EOR", MSG_EOR);
4586 #endif
4587 #ifdef MSG_TRUNC
4588 PyModule_AddIntConstant(m, "MSG_TRUNC", MSG_TRUNC);
4589 #endif
4590 #ifdef MSG_CTRUNC
4591 PyModule_AddIntConstant(m, "MSG_CTRUNC", MSG_CTRUNC);
4592 #endif
4593 #ifdef MSG_WAITALL
4594 PyModule_AddIntConstant(m, "MSG_WAITALL", MSG_WAITALL);
4595 #endif
4596 #ifdef MSG_BTAG
4597 PyModule_AddIntConstant(m, "MSG_BTAG", MSG_BTAG);
4598 #endif
4599 #ifdef MSG_ETAG
4600 PyModule_AddIntConstant(m, "MSG_ETAG", MSG_ETAG);
4601 #endif
4603 /* Protocol level and numbers, usable for [gs]etsockopt */
4604 #ifdef SOL_SOCKET
4605 PyModule_AddIntConstant(m, "SOL_SOCKET", SOL_SOCKET);
4606 #endif
4607 #ifdef SOL_IP
4608 PyModule_AddIntConstant(m, "SOL_IP", SOL_IP);
4609 #else
4610 PyModule_AddIntConstant(m, "SOL_IP", 0);
4611 #endif
4612 #ifdef SOL_IPX
4613 PyModule_AddIntConstant(m, "SOL_IPX", SOL_IPX);
4614 #endif
4615 #ifdef SOL_AX25
4616 PyModule_AddIntConstant(m, "SOL_AX25", SOL_AX25);
4617 #endif
4618 #ifdef SOL_ATALK
4619 PyModule_AddIntConstant(m, "SOL_ATALK", SOL_ATALK);
4620 #endif
4621 #ifdef SOL_NETROM
4622 PyModule_AddIntConstant(m, "SOL_NETROM", SOL_NETROM);
4623 #endif
4624 #ifdef SOL_ROSE
4625 PyModule_AddIntConstant(m, "SOL_ROSE", SOL_ROSE);
4626 #endif
4627 #ifdef SOL_TCP
4628 PyModule_AddIntConstant(m, "SOL_TCP", SOL_TCP);
4629 #else
4630 PyModule_AddIntConstant(m, "SOL_TCP", 6);
4631 #endif
4632 #ifdef SOL_UDP
4633 PyModule_AddIntConstant(m, "SOL_UDP", SOL_UDP);
4634 #else
4635 PyModule_AddIntConstant(m, "SOL_UDP", 17);
4636 #endif
4637 #ifdef IPPROTO_IP
4638 PyModule_AddIntConstant(m, "IPPROTO_IP", IPPROTO_IP);
4639 #else
4640 PyModule_AddIntConstant(m, "IPPROTO_IP", 0);
4641 #endif
4642 #ifdef IPPROTO_HOPOPTS
4643 PyModule_AddIntConstant(m, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS);
4644 #endif
4645 #ifdef IPPROTO_ICMP
4646 PyModule_AddIntConstant(m, "IPPROTO_ICMP", IPPROTO_ICMP);
4647 #else
4648 PyModule_AddIntConstant(m, "IPPROTO_ICMP", 1);
4649 #endif
4650 #ifdef IPPROTO_IGMP
4651 PyModule_AddIntConstant(m, "IPPROTO_IGMP", IPPROTO_IGMP);
4652 #endif
4653 #ifdef IPPROTO_GGP
4654 PyModule_AddIntConstant(m, "IPPROTO_GGP", IPPROTO_GGP);
4655 #endif
4656 #ifdef IPPROTO_IPV4
4657 PyModule_AddIntConstant(m, "IPPROTO_IPV4", IPPROTO_IPV4);
4658 #endif
4659 #ifdef IPPROTO_IPV6
4660 PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
4661 #endif
4662 #ifdef IPPROTO_IPIP
4663 PyModule_AddIntConstant(m, "IPPROTO_IPIP", IPPROTO_IPIP);
4664 #endif
4665 #ifdef IPPROTO_TCP
4666 PyModule_AddIntConstant(m, "IPPROTO_TCP", IPPROTO_TCP);
4667 #else
4668 PyModule_AddIntConstant(m, "IPPROTO_TCP", 6);
4669 #endif
4670 #ifdef IPPROTO_EGP
4671 PyModule_AddIntConstant(m, "IPPROTO_EGP", IPPROTO_EGP);
4672 #endif
4673 #ifdef IPPROTO_PUP
4674 PyModule_AddIntConstant(m, "IPPROTO_PUP", IPPROTO_PUP);
4675 #endif
4676 #ifdef IPPROTO_UDP
4677 PyModule_AddIntConstant(m, "IPPROTO_UDP", IPPROTO_UDP);
4678 #else
4679 PyModule_AddIntConstant(m, "IPPROTO_UDP", 17);
4680 #endif
4681 #ifdef IPPROTO_IDP
4682 PyModule_AddIntConstant(m, "IPPROTO_IDP", IPPROTO_IDP);
4683 #endif
4684 #ifdef IPPROTO_HELLO
4685 PyModule_AddIntConstant(m, "IPPROTO_HELLO", IPPROTO_HELLO);
4686 #endif
4687 #ifdef IPPROTO_ND
4688 PyModule_AddIntConstant(m, "IPPROTO_ND", IPPROTO_ND);
4689 #endif
4690 #ifdef IPPROTO_TP
4691 PyModule_AddIntConstant(m, "IPPROTO_TP", IPPROTO_TP);
4692 #endif
4693 #ifdef IPPROTO_IPV6
4694 PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
4695 #endif
4696 #ifdef IPPROTO_ROUTING
4697 PyModule_AddIntConstant(m, "IPPROTO_ROUTING", IPPROTO_ROUTING);
4698 #endif
4699 #ifdef IPPROTO_FRAGMENT
4700 PyModule_AddIntConstant(m, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT);
4701 #endif
4702 #ifdef IPPROTO_RSVP
4703 PyModule_AddIntConstant(m, "IPPROTO_RSVP", IPPROTO_RSVP);
4704 #endif
4705 #ifdef IPPROTO_GRE
4706 PyModule_AddIntConstant(m, "IPPROTO_GRE", IPPROTO_GRE);
4707 #endif
4708 #ifdef IPPROTO_ESP
4709 PyModule_AddIntConstant(m, "IPPROTO_ESP", IPPROTO_ESP);
4710 #endif
4711 #ifdef IPPROTO_AH
4712 PyModule_AddIntConstant(m, "IPPROTO_AH", IPPROTO_AH);
4713 #endif
4714 #ifdef IPPROTO_MOBILE
4715 PyModule_AddIntConstant(m, "IPPROTO_MOBILE", IPPROTO_MOBILE);
4716 #endif
4717 #ifdef IPPROTO_ICMPV6
4718 PyModule_AddIntConstant(m, "IPPROTO_ICMPV6", IPPROTO_ICMPV6);
4719 #endif
4720 #ifdef IPPROTO_NONE
4721 PyModule_AddIntConstant(m, "IPPROTO_NONE", IPPROTO_NONE);
4722 #endif
4723 #ifdef IPPROTO_DSTOPTS
4724 PyModule_AddIntConstant(m, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS);
4725 #endif
4726 #ifdef IPPROTO_XTP
4727 PyModule_AddIntConstant(m, "IPPROTO_XTP", IPPROTO_XTP);
4728 #endif
4729 #ifdef IPPROTO_EON
4730 PyModule_AddIntConstant(m, "IPPROTO_EON", IPPROTO_EON);
4731 #endif
4732 #ifdef IPPROTO_PIM
4733 PyModule_AddIntConstant(m, "IPPROTO_PIM", IPPROTO_PIM);
4734 #endif
4735 #ifdef IPPROTO_IPCOMP
4736 PyModule_AddIntConstant(m, "IPPROTO_IPCOMP", IPPROTO_IPCOMP);
4737 #endif
4738 #ifdef IPPROTO_VRRP
4739 PyModule_AddIntConstant(m, "IPPROTO_VRRP", IPPROTO_VRRP);
4740 #endif
4741 #ifdef IPPROTO_BIP
4742 PyModule_AddIntConstant(m, "IPPROTO_BIP", IPPROTO_BIP);
4743 #endif
4744 /**/
4745 #ifdef IPPROTO_RAW
4746 PyModule_AddIntConstant(m, "IPPROTO_RAW", IPPROTO_RAW);
4747 #else
4748 PyModule_AddIntConstant(m, "IPPROTO_RAW", 255);
4749 #endif
4750 #ifdef IPPROTO_MAX
4751 PyModule_AddIntConstant(m, "IPPROTO_MAX", IPPROTO_MAX);
4752 #endif
4754 /* Some port configuration */
4755 #ifdef IPPORT_RESERVED
4756 PyModule_AddIntConstant(m, "IPPORT_RESERVED", IPPORT_RESERVED);
4757 #else
4758 PyModule_AddIntConstant(m, "IPPORT_RESERVED", 1024);
4759 #endif
4760 #ifdef IPPORT_USERRESERVED
4761 PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", IPPORT_USERRESERVED);
4762 #else
4763 PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", 5000);
4764 #endif
4766 /* Some reserved IP v.4 addresses */
4767 #ifdef INADDR_ANY
4768 PyModule_AddIntConstant(m, "INADDR_ANY", INADDR_ANY);
4769 #else
4770 PyModule_AddIntConstant(m, "INADDR_ANY", 0x00000000);
4771 #endif
4772 #ifdef INADDR_BROADCAST
4773 PyModule_AddIntConstant(m, "INADDR_BROADCAST", INADDR_BROADCAST);
4774 #else
4775 PyModule_AddIntConstant(m, "INADDR_BROADCAST", 0xffffffff);
4776 #endif
4777 #ifdef INADDR_LOOPBACK
4778 PyModule_AddIntConstant(m, "INADDR_LOOPBACK", INADDR_LOOPBACK);
4779 #else
4780 PyModule_AddIntConstant(m, "INADDR_LOOPBACK", 0x7F000001);
4781 #endif
4782 #ifdef INADDR_UNSPEC_GROUP
4783 PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
4784 #else
4785 PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", 0xe0000000);
4786 #endif
4787 #ifdef INADDR_ALLHOSTS_GROUP
4788 PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP",
4789 INADDR_ALLHOSTS_GROUP);
4790 #else
4791 PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
4792 #endif
4793 #ifdef INADDR_MAX_LOCAL_GROUP
4794 PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP",
4795 INADDR_MAX_LOCAL_GROUP);
4796 #else
4797 PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
4798 #endif
4799 #ifdef INADDR_NONE
4800 PyModule_AddIntConstant(m, "INADDR_NONE", INADDR_NONE);
4801 #else
4802 PyModule_AddIntConstant(m, "INADDR_NONE", 0xffffffff);
4803 #endif
4805 /* IPv4 [gs]etsockopt options */
4806 #ifdef IP_OPTIONS
4807 PyModule_AddIntConstant(m, "IP_OPTIONS", IP_OPTIONS);
4808 #endif
4809 #ifdef IP_HDRINCL
4810 PyModule_AddIntConstant(m, "IP_HDRINCL", IP_HDRINCL);
4811 #endif
4812 #ifdef IP_TOS
4813 PyModule_AddIntConstant(m, "IP_TOS", IP_TOS);
4814 #endif
4815 #ifdef IP_TTL
4816 PyModule_AddIntConstant(m, "IP_TTL", IP_TTL);
4817 #endif
4818 #ifdef IP_RECVOPTS
4819 PyModule_AddIntConstant(m, "IP_RECVOPTS", IP_RECVOPTS);
4820 #endif
4821 #ifdef IP_RECVRETOPTS
4822 PyModule_AddIntConstant(m, "IP_RECVRETOPTS", IP_RECVRETOPTS);
4823 #endif
4824 #ifdef IP_RECVDSTADDR
4825 PyModule_AddIntConstant(m, "IP_RECVDSTADDR", IP_RECVDSTADDR);
4826 #endif
4827 #ifdef IP_RETOPTS
4828 PyModule_AddIntConstant(m, "IP_RETOPTS", IP_RETOPTS);
4829 #endif
4830 #ifdef IP_MULTICAST_IF
4831 PyModule_AddIntConstant(m, "IP_MULTICAST_IF", IP_MULTICAST_IF);
4832 #endif
4833 #ifdef IP_MULTICAST_TTL
4834 PyModule_AddIntConstant(m, "IP_MULTICAST_TTL", IP_MULTICAST_TTL);
4835 #endif
4836 #ifdef IP_MULTICAST_LOOP
4837 PyModule_AddIntConstant(m, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
4838 #endif
4839 #ifdef IP_ADD_MEMBERSHIP
4840 PyModule_AddIntConstant(m, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
4841 #endif
4842 #ifdef IP_DROP_MEMBERSHIP
4843 PyModule_AddIntConstant(m, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
4844 #endif
4845 #ifdef IP_DEFAULT_MULTICAST_TTL
4846 PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_TTL",
4847 IP_DEFAULT_MULTICAST_TTL);
4848 #endif
4849 #ifdef IP_DEFAULT_MULTICAST_LOOP
4850 PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_LOOP",
4851 IP_DEFAULT_MULTICAST_LOOP);
4852 #endif
4853 #ifdef IP_MAX_MEMBERSHIPS
4854 PyModule_AddIntConstant(m, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS);
4855 #endif
4857 /* IPv6 [gs]etsockopt options, defined in RFC2553 */
4858 #ifdef IPV6_JOIN_GROUP
4859 PyModule_AddIntConstant(m, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP);
4860 #endif
4861 #ifdef IPV6_LEAVE_GROUP
4862 PyModule_AddIntConstant(m, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP);
4863 #endif
4864 #ifdef IPV6_MULTICAST_HOPS
4865 PyModule_AddIntConstant(m, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS);
4866 #endif
4867 #ifdef IPV6_MULTICAST_IF
4868 PyModule_AddIntConstant(m, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF);
4869 #endif
4870 #ifdef IPV6_MULTICAST_LOOP
4871 PyModule_AddIntConstant(m, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP);
4872 #endif
4873 #ifdef IPV6_UNICAST_HOPS
4874 PyModule_AddIntConstant(m, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS);
4875 #endif
4876 /* Additional IPV6 socket options, defined in RFC 3493 */
4877 #ifdef IPV6_V6ONLY
4878 PyModule_AddIntConstant(m, "IPV6_V6ONLY", IPV6_V6ONLY);
4879 #endif
4880 /* Advanced IPV6 socket options, from RFC 3542 */
4881 #ifdef IPV6_CHECKSUM
4882 PyModule_AddIntConstant(m, "IPV6_CHECKSUM", IPV6_CHECKSUM);
4883 #endif
4884 #ifdef IPV6_DONTFRAG
4885 PyModule_AddIntConstant(m, "IPV6_DONTFRAG", IPV6_DONTFRAG);
4886 #endif
4887 #ifdef IPV6_DSTOPTS
4888 PyModule_AddIntConstant(m, "IPV6_DSTOPTS", IPV6_DSTOPTS);
4889 #endif
4890 #ifdef IPV6_HOPLIMIT
4891 PyModule_AddIntConstant(m, "IPV6_HOPLIMIT", IPV6_HOPLIMIT);
4892 #endif
4893 #ifdef IPV6_HOPOPTS
4894 PyModule_AddIntConstant(m, "IPV6_HOPOPTS", IPV6_HOPOPTS);
4895 #endif
4896 #ifdef IPV6_NEXTHOP
4897 PyModule_AddIntConstant(m, "IPV6_NEXTHOP", IPV6_NEXTHOP);
4898 #endif
4899 #ifdef IPV6_PATHMTU
4900 PyModule_AddIntConstant(m, "IPV6_PATHMTU", IPV6_PATHMTU);
4901 #endif
4902 #ifdef IPV6_PKTINFO
4903 PyModule_AddIntConstant(m, "IPV6_PKTINFO", IPV6_PKTINFO);
4904 #endif
4905 #ifdef IPV6_RECVDSTOPTS
4906 PyModule_AddIntConstant(m, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS);
4907 #endif
4908 #ifdef IPV6_RECVHOPLIMIT
4909 PyModule_AddIntConstant(m, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT);
4910 #endif
4911 #ifdef IPV6_RECVHOPOPTS
4912 PyModule_AddIntConstant(m, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS);
4913 #endif
4914 #ifdef IPV6_RECVPKTINFO
4915 PyModule_AddIntConstant(m, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO);
4916 #endif
4917 #ifdef IPV6_RECVRTHDR
4918 PyModule_AddIntConstant(m, "IPV6_RECVRTHDR", IPV6_RECVRTHDR);
4919 #endif
4920 #ifdef IPV6_RECVTCLASS
4921 PyModule_AddIntConstant(m, "IPV6_RECVTCLASS", IPV6_RECVTCLASS);
4922 #endif
4923 #ifdef IPV6_RTHDR
4924 PyModule_AddIntConstant(m, "IPV6_RTHDR", IPV6_RTHDR);
4925 #endif
4926 #ifdef IPV6_RTHDRDSTOPTS
4927 PyModule_AddIntConstant(m, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS);
4928 #endif
4929 #ifdef IPV6_RTHDR_TYPE_0
4930 PyModule_AddIntConstant(m, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0);
4931 #endif
4932 #ifdef IPV6_RECVPATHMTU
4933 PyModule_AddIntConstant(m, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU);
4934 #endif
4935 #ifdef IPV6_TCLASS
4936 PyModule_AddIntConstant(m, "IPV6_TCLASS", IPV6_TCLASS);
4937 #endif
4938 #ifdef IPV6_USE_MIN_MTU
4939 PyModule_AddIntConstant(m, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU);
4940 #endif
4942 /* TCP options */
4943 #ifdef TCP_NODELAY
4944 PyModule_AddIntConstant(m, "TCP_NODELAY", TCP_NODELAY);
4945 #endif
4946 #ifdef TCP_MAXSEG
4947 PyModule_AddIntConstant(m, "TCP_MAXSEG", TCP_MAXSEG);
4948 #endif
4949 #ifdef TCP_CORK
4950 PyModule_AddIntConstant(m, "TCP_CORK", TCP_CORK);
4951 #endif
4952 #ifdef TCP_KEEPIDLE
4953 PyModule_AddIntConstant(m, "TCP_KEEPIDLE", TCP_KEEPIDLE);
4954 #endif
4955 #ifdef TCP_KEEPINTVL
4956 PyModule_AddIntConstant(m, "TCP_KEEPINTVL", TCP_KEEPINTVL);
4957 #endif
4958 #ifdef TCP_KEEPCNT
4959 PyModule_AddIntConstant(m, "TCP_KEEPCNT", TCP_KEEPCNT);
4960 #endif
4961 #ifdef TCP_SYNCNT
4962 PyModule_AddIntConstant(m, "TCP_SYNCNT", TCP_SYNCNT);
4963 #endif
4964 #ifdef TCP_LINGER2
4965 PyModule_AddIntConstant(m, "TCP_LINGER2", TCP_LINGER2);
4966 #endif
4967 #ifdef TCP_DEFER_ACCEPT
4968 PyModule_AddIntConstant(m, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT);
4969 #endif
4970 #ifdef TCP_WINDOW_CLAMP
4971 PyModule_AddIntConstant(m, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP);
4972 #endif
4973 #ifdef TCP_INFO
4974 PyModule_AddIntConstant(m, "TCP_INFO", TCP_INFO);
4975 #endif
4976 #ifdef TCP_QUICKACK
4977 PyModule_AddIntConstant(m, "TCP_QUICKACK", TCP_QUICKACK);
4978 #endif
4981 /* IPX options */
4982 #ifdef IPX_TYPE
4983 PyModule_AddIntConstant(m, "IPX_TYPE", IPX_TYPE);
4984 #endif
4986 /* get{addr,name}info parameters */
4987 #ifdef EAI_ADDRFAMILY
4988 PyModule_AddIntConstant(m, "EAI_ADDRFAMILY", EAI_ADDRFAMILY);
4989 #endif
4990 #ifdef EAI_AGAIN
4991 PyModule_AddIntConstant(m, "EAI_AGAIN", EAI_AGAIN);
4992 #endif
4993 #ifdef EAI_BADFLAGS
4994 PyModule_AddIntConstant(m, "EAI_BADFLAGS", EAI_BADFLAGS);
4995 #endif
4996 #ifdef EAI_FAIL
4997 PyModule_AddIntConstant(m, "EAI_FAIL", EAI_FAIL);
4998 #endif
4999 #ifdef EAI_FAMILY
5000 PyModule_AddIntConstant(m, "EAI_FAMILY", EAI_FAMILY);
5001 #endif
5002 #ifdef EAI_MEMORY
5003 PyModule_AddIntConstant(m, "EAI_MEMORY", EAI_MEMORY);
5004 #endif
5005 #ifdef EAI_NODATA
5006 PyModule_AddIntConstant(m, "EAI_NODATA", EAI_NODATA);
5007 #endif
5008 #ifdef EAI_NONAME
5009 PyModule_AddIntConstant(m, "EAI_NONAME", EAI_NONAME);
5010 #endif
5011 #ifdef EAI_OVERFLOW
5012 PyModule_AddIntConstant(m, "EAI_OVERFLOW", EAI_OVERFLOW);
5013 #endif
5014 #ifdef EAI_SERVICE
5015 PyModule_AddIntConstant(m, "EAI_SERVICE", EAI_SERVICE);
5016 #endif
5017 #ifdef EAI_SOCKTYPE
5018 PyModule_AddIntConstant(m, "EAI_SOCKTYPE", EAI_SOCKTYPE);
5019 #endif
5020 #ifdef EAI_SYSTEM
5021 PyModule_AddIntConstant(m, "EAI_SYSTEM", EAI_SYSTEM);
5022 #endif
5023 #ifdef EAI_BADHINTS
5024 PyModule_AddIntConstant(m, "EAI_BADHINTS", EAI_BADHINTS);
5025 #endif
5026 #ifdef EAI_PROTOCOL
5027 PyModule_AddIntConstant(m, "EAI_PROTOCOL", EAI_PROTOCOL);
5028 #endif
5029 #ifdef EAI_MAX
5030 PyModule_AddIntConstant(m, "EAI_MAX", EAI_MAX);
5031 #endif
5032 #ifdef AI_PASSIVE
5033 PyModule_AddIntConstant(m, "AI_PASSIVE", AI_PASSIVE);
5034 #endif
5035 #ifdef AI_CANONNAME
5036 PyModule_AddIntConstant(m, "AI_CANONNAME", AI_CANONNAME);
5037 #endif
5038 #ifdef AI_NUMERICHOST
5039 PyModule_AddIntConstant(m, "AI_NUMERICHOST", AI_NUMERICHOST);
5040 #endif
5041 #ifdef AI_NUMERICSERV
5042 PyModule_AddIntConstant(m, "AI_NUMERICSERV", AI_NUMERICSERV);
5043 #endif
5044 #ifdef AI_MASK
5045 PyModule_AddIntConstant(m, "AI_MASK", AI_MASK);
5046 #endif
5047 #ifdef AI_ALL
5048 PyModule_AddIntConstant(m, "AI_ALL", AI_ALL);
5049 #endif
5050 #ifdef AI_V4MAPPED_CFG
5051 PyModule_AddIntConstant(m, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG);
5052 #endif
5053 #ifdef AI_ADDRCONFIG
5054 PyModule_AddIntConstant(m, "AI_ADDRCONFIG", AI_ADDRCONFIG);
5055 #endif
5056 #ifdef AI_V4MAPPED
5057 PyModule_AddIntConstant(m, "AI_V4MAPPED", AI_V4MAPPED);
5058 #endif
5059 #ifdef AI_DEFAULT
5060 PyModule_AddIntConstant(m, "AI_DEFAULT", AI_DEFAULT);
5061 #endif
5062 #ifdef NI_MAXHOST
5063 PyModule_AddIntConstant(m, "NI_MAXHOST", NI_MAXHOST);
5064 #endif
5065 #ifdef NI_MAXSERV
5066 PyModule_AddIntConstant(m, "NI_MAXSERV", NI_MAXSERV);
5067 #endif
5068 #ifdef NI_NOFQDN
5069 PyModule_AddIntConstant(m, "NI_NOFQDN", NI_NOFQDN);
5070 #endif
5071 #ifdef NI_NUMERICHOST
5072 PyModule_AddIntConstant(m, "NI_NUMERICHOST", NI_NUMERICHOST);
5073 #endif
5074 #ifdef NI_NAMEREQD
5075 PyModule_AddIntConstant(m, "NI_NAMEREQD", NI_NAMEREQD);
5076 #endif
5077 #ifdef NI_NUMERICSERV
5078 PyModule_AddIntConstant(m, "NI_NUMERICSERV", NI_NUMERICSERV);
5079 #endif
5080 #ifdef NI_DGRAM
5081 PyModule_AddIntConstant(m, "NI_DGRAM", NI_DGRAM);
5082 #endif
5084 /* shutdown() parameters */
5085 #ifdef SHUT_RD
5086 PyModule_AddIntConstant(m, "SHUT_RD", SHUT_RD);
5087 #elif defined(SD_RECEIVE)
5088 PyModule_AddIntConstant(m, "SHUT_RD", SD_RECEIVE);
5089 #else
5090 PyModule_AddIntConstant(m, "SHUT_RD", 0);
5091 #endif
5092 #ifdef SHUT_WR
5093 PyModule_AddIntConstant(m, "SHUT_WR", SHUT_WR);
5094 #elif defined(SD_SEND)
5095 PyModule_AddIntConstant(m, "SHUT_WR", SD_SEND);
5096 #else
5097 PyModule_AddIntConstant(m, "SHUT_WR", 1);
5098 #endif
5099 #ifdef SHUT_RDWR
5100 PyModule_AddIntConstant(m, "SHUT_RDWR", SHUT_RDWR);
5101 #elif defined(SD_BOTH)
5102 PyModule_AddIntConstant(m, "SHUT_RDWR", SD_BOTH);
5103 #else
5104 PyModule_AddIntConstant(m, "SHUT_RDWR", 2);
5105 #endif
5107 /* Initialize gethostbyname lock */
5108 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
5109 netdb_lock = PyThread_allocate_lock();
5110 #endif
5114 #ifndef HAVE_INET_PTON
5116 /* Simplistic emulation code for inet_pton that only works for IPv4 */
5117 /* These are not exposed because they do not set errno properly */
5120 inet_pton(int af, const char *src, void *dst)
5122 if (af == AF_INET) {
5123 long packed_addr;
5124 packed_addr = inet_addr(src);
5125 if (packed_addr == INADDR_NONE)
5126 return 0;
5127 memcpy(dst, &packed_addr, 4);
5128 return 1;
5130 /* Should set errno to EAFNOSUPPORT */
5131 return -1;
5134 const char *
5135 inet_ntop(int af, const void *src, char *dst, socklen_t size)
5137 if (af == AF_INET) {
5138 struct in_addr packed_addr;
5139 if (size < 16)
5140 /* Should set errno to ENOSPC. */
5141 return NULL;
5142 memcpy(&packed_addr, src, sizeof(packed_addr));
5143 return strncpy(dst, inet_ntoa(packed_addr), size);
5145 /* Should set errno to EAFNOSUPPORT */
5146 return NULL;
5149 #endif