Adding basic imputil documentation.
[python.git] / Modules / socketmodule.c
blobd319ca3a6ab1926ca168f54c8835d81c1a2b429c
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 SOL_HCI SOL_HCI_RAW
367 #define HCI_FILTER SO_HCI_RAW_FILTER
368 #define sockaddr_l2 sockaddr_l2cap
369 #define sockaddr_rc sockaddr_rfcomm
370 #define hci_dev hci_node
371 #define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb)
372 #define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)
373 #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
374 #elif defined(__NetBSD__)
375 #define sockaddr_l2 sockaddr_bt
376 #define sockaddr_rc sockaddr_bt
377 #define sockaddr_hci sockaddr_bt
378 #define sockaddr_sco sockaddr_bt
379 #define _BT_L2_MEMB(sa, memb) ((sa)->bt_##memb)
380 #define _BT_RC_MEMB(sa, memb) ((sa)->bt_##memb)
381 #define _BT_HCI_MEMB(sa, memb) ((sa)->bt_##memb)
382 #define _BT_SCO_MEMB(sa, memb) ((sa)->bt_##memb)
383 #else
384 #define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb)
385 #define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb)
386 #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
387 #define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)
388 #endif
389 #endif
391 #ifdef __VMS
392 /* TCP/IP Services for VMS uses a maximum send/recv buffer length */
393 #define SEGMENT_SIZE (32 * 1024 -1)
394 #endif
396 #define SAS2SA(x) ((struct sockaddr *)(x))
399 * Constants for getnameinfo()
401 #if !defined(NI_MAXHOST)
402 #define NI_MAXHOST 1025
403 #endif
404 #if !defined(NI_MAXSERV)
405 #define NI_MAXSERV 32
406 #endif
408 /* XXX There's a problem here: *static* functions are not supposed to have
409 a Py prefix (or use CapitalizedWords). Later... */
411 /* Global variable holding the exception type for errors detected
412 by this module (but not argument type or memory errors, etc.). */
413 static PyObject *socket_error;
414 static PyObject *socket_herror;
415 static PyObject *socket_gaierror;
416 static PyObject *socket_timeout;
418 #ifdef RISCOS
419 /* Global variable which is !=0 if Python is running in a RISC OS taskwindow */
420 static int taskwindow;
421 #endif
423 /* A forward reference to the socket type object.
424 The sock_type variable contains pointers to various functions,
425 some of which call new_sockobject(), which uses sock_type, so
426 there has to be a circular reference. */
427 static PyTypeObject sock_type;
429 #if defined(HAVE_POLL_H)
430 #include <poll.h>
431 #elif defined(HAVE_SYS_POLL_H)
432 #include <sys/poll.h>
433 #endif
435 #ifdef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
436 /* Platform can select file descriptors beyond FD_SETSIZE */
437 #define IS_SELECTABLE(s) 1
438 #elif defined(HAVE_POLL)
439 /* Instead of select(), we'll use poll() since poll() works on any fd. */
440 #define IS_SELECTABLE(s) 1
441 /* Can we call select() with this socket without a buffer overrun? */
442 #else
443 /* POSIX says selecting file descriptors beyond FD_SETSIZE
444 has undefined behaviour. If there's no timeout left, we don't have to
445 call select, so it's a safe, little white lie. */
446 #define IS_SELECTABLE(s) ((s)->sock_fd < FD_SETSIZE || s->sock_timeout <= 0.0)
447 #endif
449 static PyObject*
450 select_error(void)
452 PyErr_SetString(socket_error, "unable to select on socket");
453 return NULL;
456 /* Convenience function to raise an error according to errno
457 and return a NULL pointer from a function. */
459 static PyObject *
460 set_error(void)
462 #ifdef MS_WINDOWS
463 int err_no = WSAGetLastError();
464 static struct {
465 int no;
466 const char *msg;
467 } *msgp, msgs[] = {
468 {WSAEINTR, "Interrupted system call"},
469 {WSAEBADF, "Bad file descriptor"},
470 {WSAEACCES, "Permission denied"},
471 {WSAEFAULT, "Bad address"},
472 {WSAEINVAL, "Invalid argument"},
473 {WSAEMFILE, "Too many open files"},
474 {WSAEWOULDBLOCK,
475 "The socket operation could not complete "
476 "without blocking"},
477 {WSAEINPROGRESS, "Operation now in progress"},
478 {WSAEALREADY, "Operation already in progress"},
479 {WSAENOTSOCK, "Socket operation on non-socket"},
480 {WSAEDESTADDRREQ, "Destination address required"},
481 {WSAEMSGSIZE, "Message too long"},
482 {WSAEPROTOTYPE, "Protocol wrong type for socket"},
483 {WSAENOPROTOOPT, "Protocol not available"},
484 {WSAEPROTONOSUPPORT, "Protocol not supported"},
485 {WSAESOCKTNOSUPPORT, "Socket type not supported"},
486 {WSAEOPNOTSUPP, "Operation not supported"},
487 {WSAEPFNOSUPPORT, "Protocol family not supported"},
488 {WSAEAFNOSUPPORT, "Address family not supported"},
489 {WSAEADDRINUSE, "Address already in use"},
490 {WSAEADDRNOTAVAIL, "Can't assign requested address"},
491 {WSAENETDOWN, "Network is down"},
492 {WSAENETUNREACH, "Network is unreachable"},
493 {WSAENETRESET, "Network dropped connection on reset"},
494 {WSAECONNABORTED, "Software caused connection abort"},
495 {WSAECONNRESET, "Connection reset by peer"},
496 {WSAENOBUFS, "No buffer space available"},
497 {WSAEISCONN, "Socket is already connected"},
498 {WSAENOTCONN, "Socket is not connected"},
499 {WSAESHUTDOWN, "Can't send after socket shutdown"},
500 {WSAETOOMANYREFS, "Too many references: can't splice"},
501 {WSAETIMEDOUT, "Operation timed out"},
502 {WSAECONNREFUSED, "Connection refused"},
503 {WSAELOOP, "Too many levels of symbolic links"},
504 {WSAENAMETOOLONG, "File name too long"},
505 {WSAEHOSTDOWN, "Host is down"},
506 {WSAEHOSTUNREACH, "No route to host"},
507 {WSAENOTEMPTY, "Directory not empty"},
508 {WSAEPROCLIM, "Too many processes"},
509 {WSAEUSERS, "Too many users"},
510 {WSAEDQUOT, "Disc quota exceeded"},
511 {WSAESTALE, "Stale NFS file handle"},
512 {WSAEREMOTE, "Too many levels of remote in path"},
513 {WSASYSNOTREADY, "Network subsystem is unvailable"},
514 {WSAVERNOTSUPPORTED, "WinSock version is not supported"},
515 {WSANOTINITIALISED,
516 "Successful WSAStartup() not yet performed"},
517 {WSAEDISCON, "Graceful shutdown in progress"},
518 /* Resolver errors */
519 {WSAHOST_NOT_FOUND, "No such host is known"},
520 {WSATRY_AGAIN, "Host not found, or server failed"},
521 {WSANO_RECOVERY, "Unexpected server error encountered"},
522 {WSANO_DATA, "Valid name without requested data"},
523 {WSANO_ADDRESS, "No address, look for MX record"},
524 {0, NULL}
526 if (err_no) {
527 PyObject *v;
528 const char *msg = "winsock error";
530 for (msgp = msgs; msgp->msg; msgp++) {
531 if (err_no == msgp->no) {
532 msg = msgp->msg;
533 break;
537 v = Py_BuildValue("(is)", err_no, msg);
538 if (v != NULL) {
539 PyErr_SetObject(socket_error, v);
540 Py_DECREF(v);
542 return NULL;
544 else
545 #endif
547 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
548 if (sock_errno() != NO_ERROR) {
549 APIRET rc;
550 ULONG msglen;
551 char outbuf[100];
552 int myerrorcode = sock_errno();
554 /* Retrieve socket-related error message from MPTN.MSG file */
555 rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf),
556 myerrorcode - SOCBASEERR + 26,
557 "mptn.msg",
558 &msglen);
559 if (rc == NO_ERROR) {
560 PyObject *v;
562 /* OS/2 doesn't guarantee a terminator */
563 outbuf[msglen] = '\0';
564 if (strlen(outbuf) > 0) {
565 /* If non-empty msg, trim CRLF */
566 char *lastc = &outbuf[ strlen(outbuf)-1 ];
567 while (lastc > outbuf &&
568 isspace(Py_CHARMASK(*lastc))) {
569 /* Trim trailing whitespace (CRLF) */
570 *lastc-- = '\0';
573 v = Py_BuildValue("(is)", myerrorcode, outbuf);
574 if (v != NULL) {
575 PyErr_SetObject(socket_error, v);
576 Py_DECREF(v);
578 return NULL;
581 #endif
583 #if defined(RISCOS)
584 if (_inet_error.errnum != NULL) {
585 PyObject *v;
586 v = Py_BuildValue("(is)", errno, _inet_err());
587 if (v != NULL) {
588 PyErr_SetObject(socket_error, v);
589 Py_DECREF(v);
591 return NULL;
593 #endif
595 return PyErr_SetFromErrno(socket_error);
599 static PyObject *
600 set_herror(int h_error)
602 PyObject *v;
604 #ifdef HAVE_HSTRERROR
605 v = Py_BuildValue("(is)", h_error, (char *)hstrerror(h_error));
606 #else
607 v = Py_BuildValue("(is)", h_error, "host not found");
608 #endif
609 if (v != NULL) {
610 PyErr_SetObject(socket_herror, v);
611 Py_DECREF(v);
614 return NULL;
618 static PyObject *
619 set_gaierror(int error)
621 PyObject *v;
623 #ifdef EAI_SYSTEM
624 /* EAI_SYSTEM is not available on Windows XP. */
625 if (error == EAI_SYSTEM)
626 return set_error();
627 #endif
629 #ifdef HAVE_GAI_STRERROR
630 v = Py_BuildValue("(is)", error, gai_strerror(error));
631 #else
632 v = Py_BuildValue("(is)", error, "getaddrinfo failed");
633 #endif
634 if (v != NULL) {
635 PyErr_SetObject(socket_gaierror, v);
636 Py_DECREF(v);
639 return NULL;
642 #ifdef __VMS
643 /* Function to send in segments */
644 static int
645 sendsegmented(int sock_fd, char *buf, int len, int flags)
647 int n = 0;
648 int remaining = len;
650 while (remaining > 0) {
651 unsigned int segment;
653 segment = (remaining >= SEGMENT_SIZE ? SEGMENT_SIZE : remaining);
654 n = send(sock_fd, buf, segment, flags);
655 if (n < 0) {
656 return n;
658 remaining -= segment;
659 buf += segment;
660 } /* end while */
662 return len;
664 #endif
666 /* Function to perform the setting of socket blocking mode
667 internally. block = (1 | 0). */
668 static int
669 internal_setblocking(PySocketSockObject *s, int block)
671 #ifndef RISCOS
672 #ifndef MS_WINDOWS
673 int delay_flag;
674 #endif
675 #endif
677 Py_BEGIN_ALLOW_THREADS
678 #ifdef __BEOS__
679 block = !block;
680 setsockopt(s->sock_fd, SOL_SOCKET, SO_NONBLOCK,
681 (void *)(&block), sizeof(int));
682 #else
683 #ifndef RISCOS
684 #ifndef MS_WINDOWS
685 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
686 block = !block;
687 ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block));
688 #elif defined(__VMS)
689 block = !block;
690 ioctl(s->sock_fd, FIONBIO, (unsigned int *)&block);
691 #else /* !PYOS_OS2 && !__VMS */
692 delay_flag = fcntl(s->sock_fd, F_GETFL, 0);
693 if (block)
694 delay_flag &= (~O_NONBLOCK);
695 else
696 delay_flag |= O_NONBLOCK;
697 fcntl(s->sock_fd, F_SETFL, delay_flag);
698 #endif /* !PYOS_OS2 */
699 #else /* MS_WINDOWS */
700 block = !block;
701 ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
702 #endif /* MS_WINDOWS */
703 #else /* RISCOS */
704 block = !block;
705 socketioctl(s->sock_fd, FIONBIO, (u_long*)&block);
706 #endif /* RISCOS */
707 #endif /* __BEOS__ */
708 Py_END_ALLOW_THREADS
710 /* Since these don't return anything */
711 return 1;
714 /* Do a select()/poll() on the socket, if necessary (sock_timeout > 0).
715 The argument writing indicates the direction.
716 This does not raise an exception; we'll let our caller do that
717 after they've reacquired the interpreter lock.
718 Returns 1 on timeout, -1 on error, 0 otherwise. */
719 static int
720 internal_select(PySocketSockObject *s, int writing)
722 int n;
724 /* Nothing to do unless we're in timeout mode (not non-blocking) */
725 if (s->sock_timeout <= 0.0)
726 return 0;
728 /* Guard against closed socket */
729 if (s->sock_fd < 0)
730 return 0;
732 /* Prefer poll, if available, since you can poll() any fd
733 * which can't be done with select(). */
734 #ifdef HAVE_POLL
736 struct pollfd pollfd;
737 int timeout;
739 pollfd.fd = s->sock_fd;
740 pollfd.events = writing ? POLLOUT : POLLIN;
742 /* s->sock_timeout is in seconds, timeout in ms */
743 timeout = (int)(s->sock_timeout * 1000 + 0.5);
744 n = poll(&pollfd, 1, timeout);
746 #else
748 /* Construct the arguments to select */
749 fd_set fds;
750 struct timeval tv;
751 tv.tv_sec = (int)s->sock_timeout;
752 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
753 FD_ZERO(&fds);
754 FD_SET(s->sock_fd, &fds);
756 /* See if the socket is ready */
757 if (writing)
758 n = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
759 else
760 n = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
762 #endif
764 if (n < 0)
765 return -1;
766 if (n == 0)
767 return 1;
768 return 0;
771 /* Initialize a new socket object. */
773 static double defaulttimeout = -1.0; /* Default timeout for new sockets */
775 PyMODINIT_FUNC
776 init_sockobject(PySocketSockObject *s,
777 SOCKET_T fd, int family, int type, int proto)
779 #ifdef RISCOS
780 int block = 1;
781 #endif
782 s->sock_fd = fd;
783 s->sock_family = family;
784 s->sock_type = type;
785 s->sock_proto = proto;
786 s->sock_timeout = defaulttimeout;
788 s->errorhandler = &set_error;
790 if (defaulttimeout >= 0.0)
791 internal_setblocking(s, 0);
793 #ifdef RISCOS
794 if (taskwindow)
795 socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
796 #endif
800 /* Create a new socket object.
801 This just creates the object and initializes it.
802 If the creation fails, return NULL and set an exception (implicit
803 in NEWOBJ()). */
805 static PySocketSockObject *
806 new_sockobject(SOCKET_T fd, int family, int type, int proto)
808 PySocketSockObject *s;
809 s = (PySocketSockObject *)
810 PyType_GenericNew(&sock_type, NULL, NULL);
811 if (s != NULL)
812 init_sockobject(s, fd, family, type, proto);
813 return s;
817 /* Lock to allow python interpreter to continue, but only allow one
818 thread to be in gethostbyname or getaddrinfo */
819 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
820 PyThread_type_lock netdb_lock;
821 #endif
824 /* Convert a string specifying a host name or one of a few symbolic
825 names to a numeric IP address. This usually calls gethostbyname()
826 to do the work; the names "" and "<broadcast>" are special.
827 Return the length (IPv4 should be 4 bytes), or negative if
828 an error occurred; then an exception is raised. */
830 static int
831 setipaddr(char *name, struct sockaddr *addr_ret, size_t addr_ret_size, int af)
833 struct addrinfo hints, *res;
834 int error;
835 int d1, d2, d3, d4;
836 char ch;
838 memset((void *) addr_ret, '\0', sizeof(*addr_ret));
839 if (name[0] == '\0') {
840 int siz;
841 memset(&hints, 0, sizeof(hints));
842 hints.ai_family = af;
843 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
844 hints.ai_flags = AI_PASSIVE;
845 Py_BEGIN_ALLOW_THREADS
846 ACQUIRE_GETADDRINFO_LOCK
847 error = getaddrinfo(NULL, "0", &hints, &res);
848 Py_END_ALLOW_THREADS
849 /* We assume that those thread-unsafe getaddrinfo() versions
850 *are* safe regarding their return value, ie. that a
851 subsequent call to getaddrinfo() does not destroy the
852 outcome of the first call. */
853 RELEASE_GETADDRINFO_LOCK
854 if (error) {
855 set_gaierror(error);
856 return -1;
858 switch (res->ai_family) {
859 case AF_INET:
860 siz = 4;
861 break;
862 #ifdef ENABLE_IPV6
863 case AF_INET6:
864 siz = 16;
865 break;
866 #endif
867 default:
868 freeaddrinfo(res);
869 PyErr_SetString(socket_error,
870 "unsupported address family");
871 return -1;
873 if (res->ai_next) {
874 freeaddrinfo(res);
875 PyErr_SetString(socket_error,
876 "wildcard resolved to multiple address");
877 return -1;
879 if (res->ai_addrlen < addr_ret_size)
880 addr_ret_size = res->ai_addrlen;
881 memcpy(addr_ret, res->ai_addr, addr_ret_size);
882 freeaddrinfo(res);
883 return siz;
885 if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
886 struct sockaddr_in *sin;
887 if (af != AF_INET && af != AF_UNSPEC) {
888 PyErr_SetString(socket_error,
889 "address family mismatched");
890 return -1;
892 sin = (struct sockaddr_in *)addr_ret;
893 memset((void *) sin, '\0', sizeof(*sin));
894 sin->sin_family = AF_INET;
895 #ifdef HAVE_SOCKADDR_SA_LEN
896 sin->sin_len = sizeof(*sin);
897 #endif
898 sin->sin_addr.s_addr = INADDR_BROADCAST;
899 return sizeof(sin->sin_addr);
901 if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 &&
902 0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 &&
903 0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) {
904 struct sockaddr_in *sin;
905 sin = (struct sockaddr_in *)addr_ret;
906 sin->sin_addr.s_addr = htonl(
907 ((long) d1 << 24) | ((long) d2 << 16) |
908 ((long) d3 << 8) | ((long) d4 << 0));
909 sin->sin_family = AF_INET;
910 #ifdef HAVE_SOCKADDR_SA_LEN
911 sin->sin_len = sizeof(*sin);
912 #endif
913 return 4;
915 memset(&hints, 0, sizeof(hints));
916 hints.ai_family = af;
917 Py_BEGIN_ALLOW_THREADS
918 ACQUIRE_GETADDRINFO_LOCK
919 error = getaddrinfo(name, NULL, &hints, &res);
920 #if defined(__digital__) && defined(__unix__)
921 if (error == EAI_NONAME && af == AF_UNSPEC) {
922 /* On Tru64 V5.1, numeric-to-addr conversion fails
923 if no address family is given. Assume IPv4 for now.*/
924 hints.ai_family = AF_INET;
925 error = getaddrinfo(name, NULL, &hints, &res);
927 #endif
928 Py_END_ALLOW_THREADS
929 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
930 if (error) {
931 set_gaierror(error);
932 return -1;
934 if (res->ai_addrlen < addr_ret_size)
935 addr_ret_size = res->ai_addrlen;
936 memcpy((char *) addr_ret, res->ai_addr, addr_ret_size);
937 freeaddrinfo(res);
938 switch (addr_ret->sa_family) {
939 case AF_INET:
940 return 4;
941 #ifdef ENABLE_IPV6
942 case AF_INET6:
943 return 16;
944 #endif
945 default:
946 PyErr_SetString(socket_error, "unknown address family");
947 return -1;
952 /* Create a string object representing an IP address.
953 This is always a string of the form 'dd.dd.dd.dd' (with variable
954 size numbers). */
956 static PyObject *
957 makeipaddr(struct sockaddr *addr, int addrlen)
959 char buf[NI_MAXHOST];
960 int error;
962 error = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0,
963 NI_NUMERICHOST);
964 if (error) {
965 set_gaierror(error);
966 return NULL;
968 return PyString_FromString(buf);
972 #ifdef USE_BLUETOOTH
973 /* Convert a string representation of a Bluetooth address into a numeric
974 address. Returns the length (6), or raises an exception and returns -1 if
975 an error occurred. */
977 static int
978 setbdaddr(char *name, bdaddr_t *bdaddr)
980 unsigned int b0, b1, b2, b3, b4, b5;
981 char ch;
982 int n;
984 n = sscanf(name, "%X:%X:%X:%X:%X:%X%c",
985 &b5, &b4, &b3, &b2, &b1, &b0, &ch);
986 if (n == 6 && (b0 | b1 | b2 | b3 | b4 | b5) < 256) {
987 bdaddr->b[0] = b0;
988 bdaddr->b[1] = b1;
989 bdaddr->b[2] = b2;
990 bdaddr->b[3] = b3;
991 bdaddr->b[4] = b4;
992 bdaddr->b[5] = b5;
993 return 6;
994 } else {
995 PyErr_SetString(socket_error, "bad bluetooth address");
996 return -1;
1000 /* Create a string representation of the Bluetooth address. This is always a
1001 string of the form 'XX:XX:XX:XX:XX:XX' where XX is a two digit hexadecimal
1002 value (zero padded if necessary). */
1004 static PyObject *
1005 makebdaddr(bdaddr_t *bdaddr)
1007 char buf[(6 * 2) + 5 + 1];
1009 sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
1010 bdaddr->b[5], bdaddr->b[4], bdaddr->b[3],
1011 bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]);
1012 return PyString_FromString(buf);
1014 #endif
1017 /* Create an object representing the given socket address,
1018 suitable for passing it back to bind(), connect() etc.
1019 The family field of the sockaddr structure is inspected
1020 to determine what kind of address it really is. */
1022 /*ARGSUSED*/
1023 static PyObject *
1024 makesockaddr(int sockfd, struct sockaddr *addr, int addrlen, int proto)
1026 if (addrlen == 0) {
1027 /* No address -- may be recvfrom() from known socket */
1028 Py_INCREF(Py_None);
1029 return Py_None;
1032 #ifdef __BEOS__
1033 /* XXX: BeOS version of accept() doesn't set family correctly */
1034 addr->sa_family = AF_INET;
1035 #endif
1037 switch (addr->sa_family) {
1039 case AF_INET:
1041 struct sockaddr_in *a;
1042 PyObject *addrobj = makeipaddr(addr, sizeof(*a));
1043 PyObject *ret = NULL;
1044 if (addrobj) {
1045 a = (struct sockaddr_in *)addr;
1046 ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
1047 Py_DECREF(addrobj);
1049 return ret;
1052 #if defined(AF_UNIX)
1053 case AF_UNIX:
1055 struct sockaddr_un *a = (struct sockaddr_un *) addr;
1056 #ifdef linux
1057 if (a->sun_path[0] == 0) { /* Linux abstract namespace */
1058 addrlen -= (sizeof(*a) - sizeof(a->sun_path));
1059 return PyString_FromStringAndSize(a->sun_path,
1060 addrlen);
1062 else
1063 #endif /* linux */
1065 /* regular NULL-terminated string */
1066 return PyString_FromString(a->sun_path);
1069 #endif /* AF_UNIX */
1071 #if defined(AF_NETLINK)
1072 case AF_NETLINK:
1074 struct sockaddr_nl *a = (struct sockaddr_nl *) addr;
1075 return Py_BuildValue("II", a->nl_pid, a->nl_groups);
1077 #endif /* AF_NETLINK */
1079 #ifdef ENABLE_IPV6
1080 case AF_INET6:
1082 struct sockaddr_in6 *a;
1083 PyObject *addrobj = makeipaddr(addr, sizeof(*a));
1084 PyObject *ret = NULL;
1085 if (addrobj) {
1086 a = (struct sockaddr_in6 *)addr;
1087 ret = Py_BuildValue("Oiii",
1088 addrobj,
1089 ntohs(a->sin6_port),
1090 a->sin6_flowinfo,
1091 a->sin6_scope_id);
1092 Py_DECREF(addrobj);
1094 return ret;
1096 #endif
1098 #ifdef USE_BLUETOOTH
1099 case AF_BLUETOOTH:
1100 switch (proto) {
1102 case BTPROTO_L2CAP:
1104 struct sockaddr_l2 *a = (struct sockaddr_l2 *) addr;
1105 PyObject *addrobj = makebdaddr(&_BT_L2_MEMB(a, bdaddr));
1106 PyObject *ret = NULL;
1107 if (addrobj) {
1108 ret = Py_BuildValue("Oi",
1109 addrobj,
1110 _BT_L2_MEMB(a, psm));
1111 Py_DECREF(addrobj);
1113 return ret;
1116 case BTPROTO_RFCOMM:
1118 struct sockaddr_rc *a = (struct sockaddr_rc *) addr;
1119 PyObject *addrobj = makebdaddr(&_BT_RC_MEMB(a, bdaddr));
1120 PyObject *ret = NULL;
1121 if (addrobj) {
1122 ret = Py_BuildValue("Oi",
1123 addrobj,
1124 _BT_RC_MEMB(a, channel));
1125 Py_DECREF(addrobj);
1127 return ret;
1130 case BTPROTO_HCI:
1132 struct sockaddr_hci *a = (struct sockaddr_hci *) addr;
1133 PyObject *ret = NULL;
1134 ret = Py_BuildValue("i", _BT_HCI_MEMB(a, dev));
1135 return ret;
1138 #if !defined(__FreeBSD__)
1139 case BTPROTO_SCO:
1141 struct sockaddr_sco *a = (struct sockaddr_sco *) addr;
1142 return makebdaddr(&_BT_SCO_MEMB(a, bdaddr));
1144 #endif
1147 #endif
1149 #ifdef HAVE_NETPACKET_PACKET_H
1150 case AF_PACKET:
1152 struct sockaddr_ll *a = (struct sockaddr_ll *)addr;
1153 char *ifname = "";
1154 struct ifreq ifr;
1155 /* need to look up interface name give index */
1156 if (a->sll_ifindex) {
1157 ifr.ifr_ifindex = a->sll_ifindex;
1158 if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0)
1159 ifname = ifr.ifr_name;
1161 return Py_BuildValue("shbhs#",
1162 ifname,
1163 ntohs(a->sll_protocol),
1164 a->sll_pkttype,
1165 a->sll_hatype,
1166 a->sll_addr,
1167 a->sll_halen);
1169 #endif
1171 /* More cases here... */
1173 default:
1174 /* If we don't know the address family, don't raise an
1175 exception -- return it as a tuple. */
1176 return Py_BuildValue("is#",
1177 addr->sa_family,
1178 addr->sa_data,
1179 sizeof(addr->sa_data));
1185 /* Parse a socket address argument according to the socket object's
1186 address family. Return 1 if the address was in the proper format,
1187 0 of not. The address is returned through addr_ret, its length
1188 through len_ret. */
1190 static int
1191 getsockaddrarg(PySocketSockObject *s, PyObject *args,
1192 struct sockaddr *addr_ret, int *len_ret)
1194 switch (s->sock_family) {
1196 #if defined(AF_UNIX)
1197 case AF_UNIX:
1199 struct sockaddr_un* addr;
1200 char *path;
1201 int len;
1202 if (!PyArg_Parse(args, "t#", &path, &len))
1203 return 0;
1205 addr = (struct sockaddr_un*)addr_ret;
1206 #ifdef linux
1207 if (len > 0 && path[0] == 0) {
1208 /* Linux abstract namespace extension */
1209 if (len > sizeof addr->sun_path) {
1210 PyErr_SetString(socket_error,
1211 "AF_UNIX path too long");
1212 return 0;
1215 else
1216 #endif /* linux */
1218 /* regular NULL-terminated string */
1219 if (len >= sizeof addr->sun_path) {
1220 PyErr_SetString(socket_error,
1221 "AF_UNIX path too long");
1222 return 0;
1224 addr->sun_path[len] = 0;
1226 addr->sun_family = s->sock_family;
1227 memcpy(addr->sun_path, path, len);
1228 #if defined(PYOS_OS2)
1229 *len_ret = sizeof(*addr);
1230 #else
1231 *len_ret = len + sizeof(*addr) - sizeof(addr->sun_path);
1232 #endif
1233 return 1;
1235 #endif /* AF_UNIX */
1237 #if defined(AF_NETLINK)
1238 case AF_NETLINK:
1240 struct sockaddr_nl* addr;
1241 int pid, groups;
1242 addr = (struct sockaddr_nl *)addr_ret;
1243 if (!PyTuple_Check(args)) {
1244 PyErr_Format(
1245 PyExc_TypeError,
1246 "getsockaddrarg: "
1247 "AF_NETLINK address must be tuple, not %.500s",
1248 Py_Type(args)->tp_name);
1249 return 0;
1251 if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &pid, &groups))
1252 return 0;
1253 addr->nl_family = AF_NETLINK;
1254 addr->nl_pid = pid;
1255 addr->nl_groups = groups;
1256 *len_ret = sizeof(*addr);
1257 return 1;
1259 #endif
1261 case AF_INET:
1263 struct sockaddr_in* addr;
1264 char *host;
1265 int port, result;
1266 if (!PyTuple_Check(args)) {
1267 PyErr_Format(
1268 PyExc_TypeError,
1269 "getsockaddrarg: "
1270 "AF_INET address must be tuple, not %.500s",
1271 Py_Type(args)->tp_name);
1272 return 0;
1274 if (!PyArg_ParseTuple(args, "eti:getsockaddrarg",
1275 "idna", &host, &port))
1276 return 0;
1277 addr=(struct sockaddr_in*)addr_ret;
1278 result = setipaddr(host, (struct sockaddr *)addr,
1279 sizeof(*addr), AF_INET);
1280 PyMem_Free(host);
1281 if (result < 0)
1282 return 0;
1283 addr->sin_family = AF_INET;
1284 addr->sin_port = htons((short)port);
1285 *len_ret = sizeof *addr;
1286 return 1;
1289 #ifdef ENABLE_IPV6
1290 case AF_INET6:
1292 struct sockaddr_in6* addr;
1293 char *host;
1294 int port, flowinfo, scope_id, result;
1295 flowinfo = scope_id = 0;
1296 if (!PyTuple_Check(args)) {
1297 PyErr_Format(
1298 PyExc_TypeError,
1299 "getsockaddrarg: "
1300 "AF_INET6 address must be tuple, not %.500s",
1301 Py_Type(args)->tp_name);
1302 return 0;
1304 if (!PyArg_ParseTuple(args, "eti|ii",
1305 "idna", &host, &port, &flowinfo,
1306 &scope_id)) {
1307 return 0;
1309 addr = (struct sockaddr_in6*)addr_ret;
1310 result = setipaddr(host, (struct sockaddr *)addr,
1311 sizeof(*addr), AF_INET6);
1312 PyMem_Free(host);
1313 if (result < 0)
1314 return 0;
1315 addr->sin6_family = s->sock_family;
1316 addr->sin6_port = htons((short)port);
1317 addr->sin6_flowinfo = flowinfo;
1318 addr->sin6_scope_id = scope_id;
1319 *len_ret = sizeof *addr;
1320 return 1;
1322 #endif
1324 #ifdef USE_BLUETOOTH
1325 case AF_BLUETOOTH:
1327 switch (s->sock_proto) {
1328 case BTPROTO_L2CAP:
1330 struct sockaddr_l2 *addr;
1331 char *straddr;
1333 addr = (struct sockaddr_l2 *)addr_ret;
1334 _BT_L2_MEMB(addr, family) = AF_BLUETOOTH;
1335 if (!PyArg_ParseTuple(args, "si", &straddr,
1336 &_BT_L2_MEMB(addr, psm))) {
1337 PyErr_SetString(socket_error, "getsockaddrarg: "
1338 "wrong format");
1339 return 0;
1341 if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0)
1342 return 0;
1344 *len_ret = sizeof *addr;
1345 return 1;
1347 case BTPROTO_RFCOMM:
1349 struct sockaddr_rc *addr;
1350 char *straddr;
1352 addr = (struct sockaddr_rc *)addr_ret;
1353 _BT_RC_MEMB(addr, family) = AF_BLUETOOTH;
1354 if (!PyArg_ParseTuple(args, "si", &straddr,
1355 &_BT_RC_MEMB(addr, channel))) {
1356 PyErr_SetString(socket_error, "getsockaddrarg: "
1357 "wrong format");
1358 return 0;
1360 if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0)
1361 return 0;
1363 *len_ret = sizeof *addr;
1364 return 1;
1366 case BTPROTO_HCI:
1368 struct sockaddr_hci *addr = (struct sockaddr_hci *)addr_ret;
1369 _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH;
1370 if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) {
1371 PyErr_SetString(socket_error, "getsockaddrarg: "
1372 "wrong format");
1373 return 0;
1375 *len_ret = sizeof *addr;
1376 return 1;
1378 #if !defined(__FreeBSD__)
1379 case BTPROTO_SCO:
1381 struct sockaddr_sco *addr;
1382 char *straddr;
1384 addr = (struct sockaddr_sco *)addr_ret;
1385 _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH;
1386 straddr = PyString_AsString(args);
1387 if (straddr == NULL) {
1388 PyErr_SetString(socket_error, "getsockaddrarg: "
1389 "wrong format");
1390 return 0;
1392 if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0)
1393 return 0;
1395 *len_ret = sizeof *addr;
1396 return 1;
1398 #endif
1399 default:
1400 PyErr_SetString(socket_error, "getsockaddrarg: unknown Bluetooth protocol");
1401 return 0;
1404 #endif
1406 #ifdef HAVE_NETPACKET_PACKET_H
1407 case AF_PACKET:
1409 struct sockaddr_ll* addr;
1410 struct ifreq ifr;
1411 char *interfaceName;
1412 int protoNumber;
1413 int hatype = 0;
1414 int pkttype = 0;
1415 char *haddr = NULL;
1416 unsigned int halen = 0;
1418 if (!PyTuple_Check(args)) {
1419 PyErr_Format(
1420 PyExc_TypeError,
1421 "getsockaddrarg: "
1422 "AF_PACKET address must be tuple, not %.500s",
1423 Py_Type(args)->tp_name);
1424 return 0;
1426 if (!PyArg_ParseTuple(args, "si|iis#", &interfaceName,
1427 &protoNumber, &pkttype, &hatype,
1428 &haddr, &halen))
1429 return 0;
1430 strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name));
1431 ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
1432 if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
1433 s->errorhandler();
1434 return 0;
1436 if (halen > 8) {
1437 PyErr_SetString(PyExc_ValueError,
1438 "Hardware address must be 8 bytes or less");
1439 return 0;
1441 addr = (struct sockaddr_ll*)addr_ret;
1442 addr->sll_family = AF_PACKET;
1443 addr->sll_protocol = htons((short)protoNumber);
1444 addr->sll_ifindex = ifr.ifr_ifindex;
1445 addr->sll_pkttype = pkttype;
1446 addr->sll_hatype = hatype;
1447 if (halen != 0) {
1448 memcpy(&addr->sll_addr, haddr, halen);
1450 addr->sll_halen = halen;
1451 *len_ret = sizeof *addr;
1452 return 1;
1454 #endif
1456 /* More cases here... */
1458 default:
1459 PyErr_SetString(socket_error, "getsockaddrarg: bad family");
1460 return 0;
1466 /* Get the address length according to the socket object's address family.
1467 Return 1 if the family is known, 0 otherwise. The length is returned
1468 through len_ret. */
1470 static int
1471 getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
1473 switch (s->sock_family) {
1475 #if defined(AF_UNIX)
1476 case AF_UNIX:
1478 *len_ret = sizeof (struct sockaddr_un);
1479 return 1;
1481 #endif /* AF_UNIX */
1482 #if defined(AF_NETLINK)
1483 case AF_NETLINK:
1485 *len_ret = sizeof (struct sockaddr_nl);
1486 return 1;
1488 #endif
1490 case AF_INET:
1492 *len_ret = sizeof (struct sockaddr_in);
1493 return 1;
1496 #ifdef ENABLE_IPV6
1497 case AF_INET6:
1499 *len_ret = sizeof (struct sockaddr_in6);
1500 return 1;
1502 #endif
1504 #ifdef USE_BLUETOOTH
1505 case AF_BLUETOOTH:
1507 switch(s->sock_proto)
1510 case BTPROTO_L2CAP:
1511 *len_ret = sizeof (struct sockaddr_l2);
1512 return 1;
1513 case BTPROTO_RFCOMM:
1514 *len_ret = sizeof (struct sockaddr_rc);
1515 return 1;
1516 case BTPROTO_HCI:
1517 *len_ret = sizeof (struct sockaddr_hci);
1518 return 1;
1519 #if !defined(__FreeBSD__)
1520 case BTPROTO_SCO:
1521 *len_ret = sizeof (struct sockaddr_sco);
1522 return 1;
1523 #endif
1524 default:
1525 PyErr_SetString(socket_error, "getsockaddrlen: "
1526 "unknown BT protocol");
1527 return 0;
1531 #endif
1533 #ifdef HAVE_NETPACKET_PACKET_H
1534 case AF_PACKET:
1536 *len_ret = sizeof (struct sockaddr_ll);
1537 return 1;
1539 #endif
1541 /* More cases here... */
1543 default:
1544 PyErr_SetString(socket_error, "getsockaddrlen: bad family");
1545 return 0;
1551 /* s.accept() method */
1553 static PyObject *
1554 sock_accept(PySocketSockObject *s)
1556 sock_addr_t addrbuf;
1557 SOCKET_T newfd;
1558 socklen_t addrlen;
1559 PyObject *sock = NULL;
1560 PyObject *addr = NULL;
1561 PyObject *res = NULL;
1562 int timeout;
1564 if (!getsockaddrlen(s, &addrlen))
1565 return NULL;
1566 memset(&addrbuf, 0, addrlen);
1568 #ifdef MS_WINDOWS
1569 newfd = INVALID_SOCKET;
1570 #else
1571 newfd = -1;
1572 #endif
1574 if (!IS_SELECTABLE(s))
1575 return select_error();
1577 Py_BEGIN_ALLOW_THREADS
1578 timeout = internal_select(s, 0);
1579 if (!timeout)
1580 newfd = accept(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
1581 Py_END_ALLOW_THREADS
1583 if (timeout == 1) {
1584 PyErr_SetString(socket_timeout, "timed out");
1585 return NULL;
1588 #ifdef MS_WINDOWS
1589 if (newfd == INVALID_SOCKET)
1590 #else
1591 if (newfd < 0)
1592 #endif
1593 return s->errorhandler();
1595 /* Create the new object with unspecified family,
1596 to avoid calls to bind() etc. on it. */
1597 sock = (PyObject *) new_sockobject(newfd,
1598 s->sock_family,
1599 s->sock_type,
1600 s->sock_proto);
1602 if (sock == NULL) {
1603 SOCKETCLOSE(newfd);
1604 goto finally;
1606 addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
1607 addrlen, s->sock_proto);
1608 if (addr == NULL)
1609 goto finally;
1611 res = PyTuple_Pack(2, sock, addr);
1613 finally:
1614 Py_XDECREF(sock);
1615 Py_XDECREF(addr);
1616 return res;
1619 PyDoc_STRVAR(accept_doc,
1620 "accept() -> (socket object, address info)\n\
1622 Wait for an incoming connection. Return a new socket representing the\n\
1623 connection, and the address of the client. For IP sockets, the address\n\
1624 info is a pair (hostaddr, port).");
1626 /* s.setblocking(flag) method. Argument:
1627 False -- non-blocking mode; same as settimeout(0)
1628 True -- blocking mode; same as settimeout(None)
1631 static PyObject *
1632 sock_setblocking(PySocketSockObject *s, PyObject *arg)
1634 int block;
1636 block = PyInt_AsLong(arg);
1637 if (block == -1 && PyErr_Occurred())
1638 return NULL;
1640 s->sock_timeout = block ? -1.0 : 0.0;
1641 internal_setblocking(s, block);
1643 Py_INCREF(Py_None);
1644 return Py_None;
1647 PyDoc_STRVAR(setblocking_doc,
1648 "setblocking(flag)\n\
1650 Set the socket to blocking (flag is true) or non-blocking (false).\n\
1651 setblocking(True) is equivalent to settimeout(None);\n\
1652 setblocking(False) is equivalent to settimeout(0.0).");
1654 /* s.settimeout(timeout) method. Argument:
1655 None -- no timeout, blocking mode; same as setblocking(True)
1656 0.0 -- non-blocking mode; same as setblocking(False)
1657 > 0 -- timeout mode; operations time out after timeout seconds
1658 < 0 -- illegal; raises an exception
1660 static PyObject *
1661 sock_settimeout(PySocketSockObject *s, PyObject *arg)
1663 double timeout;
1665 if (arg == Py_None)
1666 timeout = -1.0;
1667 else {
1668 timeout = PyFloat_AsDouble(arg);
1669 if (timeout < 0.0) {
1670 if (!PyErr_Occurred())
1671 PyErr_SetString(PyExc_ValueError,
1672 "Timeout value out of range");
1673 return NULL;
1677 s->sock_timeout = timeout;
1678 internal_setblocking(s, timeout < 0.0);
1680 Py_INCREF(Py_None);
1681 return Py_None;
1684 PyDoc_STRVAR(settimeout_doc,
1685 "settimeout(timeout)\n\
1687 Set a timeout on socket operations. 'timeout' can be a float,\n\
1688 giving in seconds, or None. Setting a timeout of None disables\n\
1689 the timeout feature and is equivalent to setblocking(1).\n\
1690 Setting a timeout of zero is the same as setblocking(0).");
1692 /* s.gettimeout() method.
1693 Returns the timeout associated with a socket. */
1694 static PyObject *
1695 sock_gettimeout(PySocketSockObject *s)
1697 if (s->sock_timeout < 0.0) {
1698 Py_INCREF(Py_None);
1699 return Py_None;
1701 else
1702 return PyFloat_FromDouble(s->sock_timeout);
1705 PyDoc_STRVAR(gettimeout_doc,
1706 "gettimeout() -> timeout\n\
1708 Returns the timeout in floating seconds associated with socket \n\
1709 operations. A timeout of None indicates that timeouts on socket \n\
1710 operations are disabled.");
1712 #ifdef RISCOS
1713 /* s.sleeptaskw(1 | 0) method */
1715 static PyObject *
1716 sock_sleeptaskw(PySocketSockObject *s,PyObject *arg)
1718 int block;
1719 block = PyInt_AsLong(arg);
1720 if (block == -1 && PyErr_Occurred())
1721 return NULL;
1722 Py_BEGIN_ALLOW_THREADS
1723 socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
1724 Py_END_ALLOW_THREADS
1726 Py_INCREF(Py_None);
1727 return Py_None;
1729 PyDoc_STRVAR(sleeptaskw_doc,
1730 "sleeptaskw(flag)\n\
1732 Allow sleeps in taskwindows.");
1733 #endif
1736 /* s.setsockopt() method.
1737 With an integer third argument, sets an integer option.
1738 With a string third argument, sets an option from a buffer;
1739 use optional built-in module 'struct' to encode the string. */
1741 static PyObject *
1742 sock_setsockopt(PySocketSockObject *s, PyObject *args)
1744 int level;
1745 int optname;
1746 int res;
1747 char *buf;
1748 int buflen;
1749 int flag;
1751 if (PyArg_ParseTuple(args, "iii:setsockopt",
1752 &level, &optname, &flag)) {
1753 buf = (char *) &flag;
1754 buflen = sizeof flag;
1756 else {
1757 PyErr_Clear();
1758 if (!PyArg_ParseTuple(args, "iis#:setsockopt",
1759 &level, &optname, &buf, &buflen))
1760 return NULL;
1762 res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen);
1763 if (res < 0)
1764 return s->errorhandler();
1765 Py_INCREF(Py_None);
1766 return Py_None;
1769 PyDoc_STRVAR(setsockopt_doc,
1770 "setsockopt(level, option, value)\n\
1772 Set a socket option. See the Unix manual for level and option.\n\
1773 The value argument can either be an integer or a string.");
1776 /* s.getsockopt() method.
1777 With two arguments, retrieves an integer option.
1778 With a third integer argument, retrieves a string buffer of that size;
1779 use optional built-in module 'struct' to decode the string. */
1781 static PyObject *
1782 sock_getsockopt(PySocketSockObject *s, PyObject *args)
1784 int level;
1785 int optname;
1786 int res;
1787 PyObject *buf;
1788 socklen_t buflen = 0;
1790 #ifdef __BEOS__
1791 /* We have incomplete socket support. */
1792 PyErr_SetString(socket_error, "getsockopt not supported");
1793 return NULL;
1794 #else
1796 if (!PyArg_ParseTuple(args, "ii|i:getsockopt",
1797 &level, &optname, &buflen))
1798 return NULL;
1800 if (buflen == 0) {
1801 int flag = 0;
1802 socklen_t flagsize = sizeof flag;
1803 res = getsockopt(s->sock_fd, level, optname,
1804 (void *)&flag, &flagsize);
1805 if (res < 0)
1806 return s->errorhandler();
1807 return PyInt_FromLong(flag);
1809 #ifdef __VMS
1810 /* socklen_t is unsigned so no negative test is needed,
1811 test buflen == 0 is previously done */
1812 if (buflen > 1024) {
1813 #else
1814 if (buflen <= 0 || buflen > 1024) {
1815 #endif
1816 PyErr_SetString(socket_error,
1817 "getsockopt buflen out of range");
1818 return NULL;
1820 buf = PyString_FromStringAndSize((char *)NULL, buflen);
1821 if (buf == NULL)
1822 return NULL;
1823 res = getsockopt(s->sock_fd, level, optname,
1824 (void *)PyString_AS_STRING(buf), &buflen);
1825 if (res < 0) {
1826 Py_DECREF(buf);
1827 return s->errorhandler();
1829 _PyString_Resize(&buf, buflen);
1830 return buf;
1831 #endif /* __BEOS__ */
1834 PyDoc_STRVAR(getsockopt_doc,
1835 "getsockopt(level, option[, buffersize]) -> value\n\
1837 Get a socket option. See the Unix manual for level and option.\n\
1838 If a nonzero buffersize argument is given, the return value is a\n\
1839 string of that length; otherwise it is an integer.");
1842 /* s.bind(sockaddr) method */
1844 static PyObject *
1845 sock_bind(PySocketSockObject *s, PyObject *addro)
1847 sock_addr_t addrbuf;
1848 int addrlen;
1849 int res;
1851 if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
1852 return NULL;
1853 Py_BEGIN_ALLOW_THREADS
1854 res = bind(s->sock_fd, SAS2SA(&addrbuf), addrlen);
1855 Py_END_ALLOW_THREADS
1856 if (res < 0)
1857 return s->errorhandler();
1858 Py_INCREF(Py_None);
1859 return Py_None;
1862 PyDoc_STRVAR(bind_doc,
1863 "bind(address)\n\
1865 Bind the socket to a local address. For IP sockets, the address is a\n\
1866 pair (host, port); the host must refer to the local host. For raw packet\n\
1867 sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");
1870 /* s.close() method.
1871 Set the file descriptor to -1 so operations tried subsequently
1872 will surely fail. */
1874 static PyObject *
1875 sock_close(PySocketSockObject *s)
1877 SOCKET_T fd;
1879 if ((fd = s->sock_fd) != -1) {
1880 s->sock_fd = -1;
1881 Py_BEGIN_ALLOW_THREADS
1882 (void) SOCKETCLOSE(fd);
1883 Py_END_ALLOW_THREADS
1885 Py_INCREF(Py_None);
1886 return Py_None;
1889 PyDoc_STRVAR(close_doc,
1890 "close()\n\
1892 Close the socket. It cannot be used after this call.");
1894 static int
1895 internal_connect(PySocketSockObject *s, struct sockaddr *addr, int addrlen,
1896 int *timeoutp)
1898 int res, timeout;
1900 timeout = 0;
1901 res = connect(s->sock_fd, addr, addrlen);
1903 #ifdef MS_WINDOWS
1905 if (s->sock_timeout > 0.0) {
1906 if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK &&
1907 IS_SELECTABLE(s)) {
1908 /* This is a mess. Best solution: trust select */
1909 fd_set fds;
1910 fd_set fds_exc;
1911 struct timeval tv;
1912 tv.tv_sec = (int)s->sock_timeout;
1913 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1914 FD_ZERO(&fds);
1915 FD_SET(s->sock_fd, &fds);
1916 FD_ZERO(&fds_exc);
1917 FD_SET(s->sock_fd, &fds_exc);
1918 res = select(s->sock_fd+1, NULL, &fds, &fds_exc, &tv);
1919 if (res == 0) {
1920 res = WSAEWOULDBLOCK;
1921 timeout = 1;
1922 } else if (res > 0) {
1923 if (FD_ISSET(s->sock_fd, &fds))
1924 /* The socket is in the writeable set - this
1925 means connected */
1926 res = 0;
1927 else {
1928 /* As per MS docs, we need to call getsockopt()
1929 to get the underlying error */
1930 int res_size = sizeof res;
1931 /* It must be in the exception set */
1932 assert(FD_ISSET(s->sock_fd, &fds_exc));
1933 if (0 == getsockopt(s->sock_fd, SOL_SOCKET, SO_ERROR,
1934 (char *)&res, &res_size))
1935 /* getsockopt also clears WSAGetLastError,
1936 so reset it back. */
1937 WSASetLastError(res);
1938 else
1939 res = WSAGetLastError();
1942 /* else if (res < 0) an error occurred */
1946 if (res < 0)
1947 res = WSAGetLastError();
1949 #else
1951 if (s->sock_timeout > 0.0) {
1952 if (res < 0 && errno == EINPROGRESS && IS_SELECTABLE(s)) {
1953 timeout = internal_select(s, 1);
1954 if (timeout == 0) {
1955 res = connect(s->sock_fd, addr, addrlen);
1956 if (res < 0 && errno == EISCONN)
1957 res = 0;
1959 else if (timeout == -1)
1960 res = errno; /* had error */
1961 else
1962 res = EWOULDBLOCK; /* timed out */
1966 if (res < 0)
1967 res = errno;
1969 #endif
1970 *timeoutp = timeout;
1972 return res;
1975 /* s.connect(sockaddr) method */
1977 static PyObject *
1978 sock_connect(PySocketSockObject *s, PyObject *addro)
1980 sock_addr_t addrbuf;
1981 int addrlen;
1982 int res;
1983 int timeout;
1985 if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
1986 return NULL;
1988 Py_BEGIN_ALLOW_THREADS
1989 res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
1990 Py_END_ALLOW_THREADS
1992 if (timeout == 1) {
1993 PyErr_SetString(socket_timeout, "timed out");
1994 return NULL;
1996 if (res != 0)
1997 return s->errorhandler();
1998 Py_INCREF(Py_None);
1999 return Py_None;
2002 PyDoc_STRVAR(connect_doc,
2003 "connect(address)\n\
2005 Connect the socket to a remote address. For IP sockets, the address\n\
2006 is a pair (host, port).");
2009 /* s.connect_ex(sockaddr) method */
2011 static PyObject *
2012 sock_connect_ex(PySocketSockObject *s, PyObject *addro)
2014 sock_addr_t addrbuf;
2015 int addrlen;
2016 int res;
2017 int timeout;
2019 if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
2020 return NULL;
2022 Py_BEGIN_ALLOW_THREADS
2023 res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
2024 Py_END_ALLOW_THREADS
2026 /* Signals are not errors (though they may raise exceptions). Adapted
2027 from PyErr_SetFromErrnoWithFilenameObject(). */
2028 #ifdef EINTR
2029 if (res == EINTR && PyErr_CheckSignals())
2030 return NULL;
2031 #endif
2033 return PyInt_FromLong((long) res);
2036 PyDoc_STRVAR(connect_ex_doc,
2037 "connect_ex(address) -> errno\n\
2039 This is like connect(address), but returns an error code (the errno value)\n\
2040 instead of raising an exception when an error occurs.");
2043 /* s.fileno() method */
2045 static PyObject *
2046 sock_fileno(PySocketSockObject *s)
2048 #if SIZEOF_SOCKET_T <= SIZEOF_LONG
2049 return PyInt_FromLong((long) s->sock_fd);
2050 #else
2051 return PyLong_FromLongLong((PY_LONG_LONG)s->sock_fd);
2052 #endif
2055 PyDoc_STRVAR(fileno_doc,
2056 "fileno() -> integer\n\
2058 Return the integer file descriptor of the socket.");
2061 #ifndef NO_DUP
2062 /* s.dup() method */
2064 static PyObject *
2065 sock_dup(PySocketSockObject *s)
2067 SOCKET_T newfd;
2068 PyObject *sock;
2070 newfd = dup(s->sock_fd);
2071 if (newfd < 0)
2072 return s->errorhandler();
2073 sock = (PyObject *) new_sockobject(newfd,
2074 s->sock_family,
2075 s->sock_type,
2076 s->sock_proto);
2077 if (sock == NULL)
2078 SOCKETCLOSE(newfd);
2079 return sock;
2082 PyDoc_STRVAR(dup_doc,
2083 "dup() -> socket object\n\
2085 Return a new socket object connected to the same system resource.");
2087 #endif
2090 /* s.getsockname() method */
2092 static PyObject *
2093 sock_getsockname(PySocketSockObject *s)
2095 sock_addr_t addrbuf;
2096 int res;
2097 socklen_t addrlen;
2099 if (!getsockaddrlen(s, &addrlen))
2100 return NULL;
2101 memset(&addrbuf, 0, addrlen);
2102 Py_BEGIN_ALLOW_THREADS
2103 res = getsockname(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
2104 Py_END_ALLOW_THREADS
2105 if (res < 0)
2106 return s->errorhandler();
2107 return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
2108 s->sock_proto);
2111 PyDoc_STRVAR(getsockname_doc,
2112 "getsockname() -> address info\n\
2114 Return the address of the local endpoint. For IP sockets, the address\n\
2115 info is a pair (hostaddr, port).");
2118 #ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
2119 /* s.getpeername() method */
2121 static PyObject *
2122 sock_getpeername(PySocketSockObject *s)
2124 sock_addr_t addrbuf;
2125 int res;
2126 socklen_t addrlen;
2128 if (!getsockaddrlen(s, &addrlen))
2129 return NULL;
2130 memset(&addrbuf, 0, addrlen);
2131 Py_BEGIN_ALLOW_THREADS
2132 res = getpeername(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
2133 Py_END_ALLOW_THREADS
2134 if (res < 0)
2135 return s->errorhandler();
2136 return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
2137 s->sock_proto);
2140 PyDoc_STRVAR(getpeername_doc,
2141 "getpeername() -> address info\n\
2143 Return the address of the remote endpoint. For IP sockets, the address\n\
2144 info is a pair (hostaddr, port).");
2146 #endif /* HAVE_GETPEERNAME */
2149 /* s.listen(n) method */
2151 static PyObject *
2152 sock_listen(PySocketSockObject *s, PyObject *arg)
2154 int backlog;
2155 int res;
2157 backlog = PyInt_AsLong(arg);
2158 if (backlog == -1 && PyErr_Occurred())
2159 return NULL;
2160 Py_BEGIN_ALLOW_THREADS
2161 if (backlog < 1)
2162 backlog = 1;
2163 res = listen(s->sock_fd, backlog);
2164 Py_END_ALLOW_THREADS
2165 if (res < 0)
2166 return s->errorhandler();
2167 Py_INCREF(Py_None);
2168 return Py_None;
2171 PyDoc_STRVAR(listen_doc,
2172 "listen(backlog)\n\
2174 Enable a server to accept connections. The backlog argument must be at\n\
2175 least 1; it specifies the number of unaccepted connection that the system\n\
2176 will allow before refusing new connections.");
2179 #ifndef NO_DUP
2180 /* s.makefile(mode) method.
2181 Create a new open file object referring to a dupped version of
2182 the socket's file descriptor. (The dup() call is necessary so
2183 that the open file and socket objects may be closed independent
2184 of each other.)
2185 The mode argument specifies 'r' or 'w' passed to fdopen(). */
2187 static PyObject *
2188 sock_makefile(PySocketSockObject *s, PyObject *args)
2190 extern int fclose(FILE *);
2191 char *mode = "r";
2192 int bufsize = -1;
2193 #ifdef MS_WIN32
2194 Py_intptr_t fd;
2195 #else
2196 int fd;
2197 #endif
2198 FILE *fp;
2199 PyObject *f;
2200 #ifdef __VMS
2201 char *mode_r = "r";
2202 char *mode_w = "w";
2203 #endif
2205 if (!PyArg_ParseTuple(args, "|si:makefile", &mode, &bufsize))
2206 return NULL;
2207 #ifdef __VMS
2208 if (strcmp(mode,"rb") == 0) {
2209 mode = mode_r;
2211 else {
2212 if (strcmp(mode,"wb") == 0) {
2213 mode = mode_w;
2216 #endif
2217 #ifdef MS_WIN32
2218 if (((fd = _open_osfhandle(s->sock_fd, _O_BINARY)) < 0) ||
2219 ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL))
2220 #else
2221 if ((fd = dup(s->sock_fd)) < 0 || (fp = fdopen(fd, mode)) == NULL)
2222 #endif
2224 if (fd >= 0)
2225 SOCKETCLOSE(fd);
2226 return s->errorhandler();
2228 f = PyFile_FromFile(fp, "<socket>", mode, fclose);
2229 if (f != NULL)
2230 PyFile_SetBufSize(f, bufsize);
2231 return f;
2234 PyDoc_STRVAR(makefile_doc,
2235 "makefile([mode[, buffersize]]) -> file object\n\
2237 Return a regular file object corresponding to the socket.\n\
2238 The mode and buffersize arguments are as for the built-in open() function.");
2240 #endif /* NO_DUP */
2243 * This is the guts of the recv() and recv_into() methods, which reads into a
2244 * char buffer. If you have any inc/dec ref to do to the objects that contain
2245 * the buffer, do it in the caller. This function returns the number of bytes
2246 * succesfully read. If there was an error, it returns -1. Note that it is
2247 * also possible that we return a number of bytes smaller than the request
2248 * bytes.
2250 static ssize_t
2251 sock_recv_guts(PySocketSockObject *s, char* cbuf, int len, int flags)
2253 ssize_t outlen = -1;
2254 int timeout;
2255 #ifdef __VMS
2256 int remaining;
2257 char *read_buf;
2258 #endif
2260 if (!IS_SELECTABLE(s)) {
2261 select_error();
2262 return -1;
2265 #ifndef __VMS
2266 Py_BEGIN_ALLOW_THREADS
2267 timeout = internal_select(s, 0);
2268 if (!timeout)
2269 outlen = recv(s->sock_fd, cbuf, len, flags);
2270 Py_END_ALLOW_THREADS
2272 if (timeout == 1) {
2273 PyErr_SetString(socket_timeout, "timed out");
2274 return -1;
2276 if (outlen < 0) {
2277 /* Note: the call to errorhandler() ALWAYS indirectly returned
2278 NULL, so ignore its return value */
2279 s->errorhandler();
2280 return -1;
2282 #else
2283 read_buf = cbuf;
2284 remaining = len;
2285 while (remaining != 0) {
2286 unsigned int segment;
2287 int nread = -1;
2289 segment = remaining /SEGMENT_SIZE;
2290 if (segment != 0) {
2291 segment = SEGMENT_SIZE;
2293 else {
2294 segment = remaining;
2297 Py_BEGIN_ALLOW_THREADS
2298 timeout = internal_select(s, 0);
2299 if (!timeout)
2300 nread = recv(s->sock_fd, read_buf, segment, flags);
2301 Py_END_ALLOW_THREADS
2303 if (timeout == 1) {
2304 PyErr_SetString(socket_timeout, "timed out");
2305 return -1;
2307 if (nread < 0) {
2308 s->errorhandler();
2309 return -1;
2311 if (nread != remaining) {
2312 read_buf += nread;
2313 break;
2316 remaining -= segment;
2317 read_buf += segment;
2319 outlen = read_buf - cbuf;
2320 #endif /* !__VMS */
2322 return outlen;
2326 /* s.recv(nbytes [,flags]) method */
2328 static PyObject *
2329 sock_recv(PySocketSockObject *s, PyObject *args)
2331 int recvlen, flags = 0;
2332 ssize_t outlen;
2333 PyObject *buf;
2335 if (!PyArg_ParseTuple(args, "i|i:recv", &recvlen, &flags))
2336 return NULL;
2338 if (recvlen < 0) {
2339 PyErr_SetString(PyExc_ValueError,
2340 "negative buffersize in recv");
2341 return NULL;
2344 /* Allocate a new string. */
2345 buf = PyString_FromStringAndSize((char *) 0, recvlen);
2346 if (buf == NULL)
2347 return NULL;
2349 /* Call the guts */
2350 outlen = sock_recv_guts(s, PyString_AS_STRING(buf), recvlen, flags);
2351 if (outlen < 0) {
2352 /* An error occurred, release the string and return an
2353 error. */
2354 Py_DECREF(buf);
2355 return NULL;
2357 if (outlen != recvlen) {
2358 /* We did not read as many bytes as we anticipated, resize the
2359 string if possible and be succesful. */
2360 if (_PyString_Resize(&buf, outlen) < 0)
2361 /* Oopsy, not so succesful after all. */
2362 return NULL;
2365 return buf;
2368 PyDoc_STRVAR(recv_doc,
2369 "recv(buffersize[, flags]) -> data\n\
2371 Receive up to buffersize bytes from the socket. For the optional flags\n\
2372 argument, see the Unix manual. When no data is available, block until\n\
2373 at least one byte is available or until the remote end is closed. When\n\
2374 the remote end is closed and all data is read, return the empty string.");
2377 /* s.recv_into(buffer, [nbytes [,flags]]) method */
2379 static PyObject*
2380 sock_recv_into(PySocketSockObject *s, PyObject *args, PyObject *kwds)
2382 static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
2384 int recvlen = 0, flags = 0;
2385 ssize_t readlen;
2386 char *buf;
2387 int buflen;
2389 /* Get the buffer's memory */
2390 if (!PyArg_ParseTupleAndKeywords(args, kwds, "w#|ii:recv_into", kwlist,
2391 &buf, &buflen, &recvlen, &flags))
2392 return NULL;
2393 assert(buf != 0 && buflen > 0);
2395 if (recvlen < 0) {
2396 PyErr_SetString(PyExc_ValueError,
2397 "negative buffersize in recv_into");
2398 return NULL;
2400 if (recvlen == 0) {
2401 /* If nbytes was not specified, use the buffer's length */
2402 recvlen = buflen;
2405 /* Check if the buffer is large enough */
2406 if (buflen < recvlen) {
2407 PyErr_SetString(PyExc_ValueError,
2408 "buffer too small for requested bytes");
2409 return NULL;
2412 /* Call the guts */
2413 readlen = sock_recv_guts(s, buf, recvlen, flags);
2414 if (readlen < 0) {
2415 /* Return an error. */
2416 return NULL;
2419 /* Return the number of bytes read. Note that we do not do anything
2420 special here in the case that readlen < recvlen. */
2421 return PyInt_FromSsize_t(readlen);
2424 PyDoc_STRVAR(recv_into_doc,
2425 "recv_into(buffer, [nbytes[, flags]]) -> nbytes_read\n\
2427 A version of recv() that stores its data into a buffer rather than creating \n\
2428 a new string. Receive up to buffersize bytes from the socket. If buffersize \n\
2429 is not specified (or 0), receive up to the size available in the given buffer.\n\
2431 See recv() for documentation about the flags.");
2435 * This is the guts of the recv() and recv_into() methods, which reads into a
2436 * char buffer. If you have any inc/def ref to do to the objects that contain
2437 * the buffer, do it in the caller. This function returns the number of bytes
2438 * succesfully read. If there was an error, it returns -1. Note that it is
2439 * also possible that we return a number of bytes smaller than the request
2440 * bytes.
2442 * 'addr' is a return value for the address object. Note that you must decref
2443 * it yourself.
2445 static ssize_t
2446 sock_recvfrom_guts(PySocketSockObject *s, char* cbuf, int len, int flags,
2447 PyObject** addr)
2449 sock_addr_t addrbuf;
2450 int timeout;
2451 ssize_t n = -1;
2452 socklen_t addrlen;
2454 *addr = NULL;
2456 if (!getsockaddrlen(s, &addrlen))
2457 return -1;
2459 if (!IS_SELECTABLE(s)) {
2460 select_error();
2461 return -1;
2464 Py_BEGIN_ALLOW_THREADS
2465 memset(&addrbuf, 0, addrlen);
2466 timeout = internal_select(s, 0);
2467 if (!timeout) {
2468 #ifndef MS_WINDOWS
2469 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
2470 n = recvfrom(s->sock_fd, cbuf, len, flags,
2471 SAS2SA(&addrbuf), &addrlen);
2472 #else
2473 n = recvfrom(s->sock_fd, cbuf, len, flags,
2474 (void *) &addrbuf, &addrlen);
2475 #endif
2476 #else
2477 n = recvfrom(s->sock_fd, cbuf, len, flags,
2478 SAS2SA(&addrbuf), &addrlen);
2479 #endif
2481 Py_END_ALLOW_THREADS
2483 if (timeout == 1) {
2484 PyErr_SetString(socket_timeout, "timed out");
2485 return -1;
2487 if (n < 0) {
2488 s->errorhandler();
2489 return -1;
2492 if (!(*addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
2493 addrlen, s->sock_proto)))
2494 return -1;
2496 return n;
2499 /* s.recvfrom(nbytes [,flags]) method */
2501 static PyObject *
2502 sock_recvfrom(PySocketSockObject *s, PyObject *args)
2504 PyObject *buf = NULL;
2505 PyObject *addr = NULL;
2506 PyObject *ret = NULL;
2507 int recvlen, flags = 0;
2508 ssize_t outlen;
2510 if (!PyArg_ParseTuple(args, "i|i:recvfrom", &recvlen, &flags))
2511 return NULL;
2513 if (recvlen < 0) {
2514 PyErr_SetString(PyExc_ValueError,
2515 "negative buffersize in recvfrom");
2516 return NULL;
2519 buf = PyString_FromStringAndSize((char *) 0, recvlen);
2520 if (buf == NULL)
2521 return NULL;
2523 outlen = sock_recvfrom_guts(s, PyString_AS_STRING(buf),
2524 recvlen, flags, &addr);
2525 if (outlen < 0) {
2526 goto finally;
2529 if (outlen != recvlen) {
2530 /* We did not read as many bytes as we anticipated, resize the
2531 string if possible and be succesful. */
2532 if (_PyString_Resize(&buf, outlen) < 0)
2533 /* Oopsy, not so succesful after all. */
2534 goto finally;
2537 ret = PyTuple_Pack(2, buf, addr);
2539 finally:
2540 Py_XDECREF(buf);
2541 Py_XDECREF(addr);
2542 return ret;
2545 PyDoc_STRVAR(recvfrom_doc,
2546 "recvfrom(buffersize[, flags]) -> (data, address info)\n\
2548 Like recv(buffersize, flags) but also return the sender's address info.");
2551 /* s.recvfrom_into(buffer[, nbytes [,flags]]) method */
2553 static PyObject *
2554 sock_recvfrom_into(PySocketSockObject *s, PyObject *args, PyObject* kwds)
2556 static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
2558 int recvlen = 0, flags = 0;
2559 ssize_t readlen;
2560 char *buf;
2561 int buflen;
2563 PyObject *addr = NULL;
2565 if (!PyArg_ParseTupleAndKeywords(args, kwds, "w#|ii:recvfrom_into",
2566 kwlist, &buf, &buflen,
2567 &recvlen, &flags))
2568 return NULL;
2569 assert(buf != 0 && buflen > 0);
2571 if (recvlen < 0) {
2572 PyErr_SetString(PyExc_ValueError,
2573 "negative buffersize in recvfrom_into");
2574 return NULL;
2576 if (recvlen == 0) {
2577 /* If nbytes was not specified, use the buffer's length */
2578 recvlen = buflen;
2581 readlen = sock_recvfrom_guts(s, buf, recvlen, flags, &addr);
2582 if (readlen < 0) {
2583 /* Return an error */
2584 Py_XDECREF(addr);
2585 return NULL;
2588 /* Return the number of bytes read and the address. Note that we do
2589 not do anything special here in the case that readlen < recvlen. */
2590 return Py_BuildValue("lN", readlen, addr);
2593 PyDoc_STRVAR(recvfrom_into_doc,
2594 "recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)\n\
2596 Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.");
2599 /* s.send(data [,flags]) method */
2601 static PyObject *
2602 sock_send(PySocketSockObject *s, PyObject *args)
2604 char *buf;
2605 int len, n = -1, flags = 0, timeout;
2607 if (!PyArg_ParseTuple(args, "s#|i:send", &buf, &len, &flags))
2608 return NULL;
2610 if (!IS_SELECTABLE(s))
2611 return select_error();
2613 Py_BEGIN_ALLOW_THREADS
2614 timeout = internal_select(s, 1);
2615 if (!timeout)
2616 #ifdef __VMS
2617 n = sendsegmented(s->sock_fd, buf, len, flags);
2618 #else
2619 n = send(s->sock_fd, buf, len, flags);
2620 #endif
2621 Py_END_ALLOW_THREADS
2623 if (timeout == 1) {
2624 PyErr_SetString(socket_timeout, "timed out");
2625 return NULL;
2627 if (n < 0)
2628 return s->errorhandler();
2629 return PyInt_FromLong((long)n);
2632 PyDoc_STRVAR(send_doc,
2633 "send(data[, flags]) -> count\n\
2635 Send a data string to the socket. For the optional flags\n\
2636 argument, see the Unix manual. Return the number of bytes\n\
2637 sent; this may be less than len(data) if the network is busy.");
2640 /* s.sendall(data [,flags]) method */
2642 static PyObject *
2643 sock_sendall(PySocketSockObject *s, PyObject *args)
2645 char *buf;
2646 int len, n = -1, flags = 0, timeout;
2648 if (!PyArg_ParseTuple(args, "s#|i:sendall", &buf, &len, &flags))
2649 return NULL;
2651 if (!IS_SELECTABLE(s))
2652 return select_error();
2654 Py_BEGIN_ALLOW_THREADS
2655 do {
2656 timeout = internal_select(s, 1);
2657 n = -1;
2658 if (timeout)
2659 break;
2660 #ifdef __VMS
2661 n = sendsegmented(s->sock_fd, buf, len, flags);
2662 #else
2663 n = send(s->sock_fd, buf, len, flags);
2664 #endif
2665 if (n < 0)
2666 break;
2667 buf += n;
2668 len -= n;
2669 } while (len > 0);
2670 Py_END_ALLOW_THREADS
2672 if (timeout == 1) {
2673 PyErr_SetString(socket_timeout, "timed out");
2674 return NULL;
2676 if (n < 0)
2677 return s->errorhandler();
2679 Py_INCREF(Py_None);
2680 return Py_None;
2683 PyDoc_STRVAR(sendall_doc,
2684 "sendall(data[, flags])\n\
2686 Send a data string to the socket. For the optional flags\n\
2687 argument, see the Unix manual. This calls send() repeatedly\n\
2688 until all data is sent. If an error occurs, it's impossible\n\
2689 to tell how much data has been sent.");
2692 /* s.sendto(data, [flags,] sockaddr) method */
2694 static PyObject *
2695 sock_sendto(PySocketSockObject *s, PyObject *args)
2697 PyObject *addro;
2698 char *buf;
2699 sock_addr_t addrbuf;
2700 int addrlen, len, n = -1, flags, timeout;
2702 flags = 0;
2703 if (!PyArg_ParseTuple(args, "s#O:sendto", &buf, &len, &addro)) {
2704 PyErr_Clear();
2705 if (!PyArg_ParseTuple(args, "s#iO:sendto",
2706 &buf, &len, &flags, &addro))
2707 return NULL;
2710 if (!IS_SELECTABLE(s))
2711 return select_error();
2713 if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
2714 return NULL;
2716 Py_BEGIN_ALLOW_THREADS
2717 timeout = internal_select(s, 1);
2718 if (!timeout)
2719 n = sendto(s->sock_fd, buf, len, flags, SAS2SA(&addrbuf), addrlen);
2720 Py_END_ALLOW_THREADS
2722 if (timeout == 1) {
2723 PyErr_SetString(socket_timeout, "timed out");
2724 return NULL;
2726 if (n < 0)
2727 return s->errorhandler();
2728 return PyInt_FromLong((long)n);
2731 PyDoc_STRVAR(sendto_doc,
2732 "sendto(data[, flags], address) -> count\n\
2734 Like send(data, flags) but allows specifying the destination address.\n\
2735 For IP sockets, the address is a pair (hostaddr, port).");
2738 /* s.shutdown(how) method */
2740 static PyObject *
2741 sock_shutdown(PySocketSockObject *s, PyObject *arg)
2743 int how;
2744 int res;
2746 how = PyInt_AsLong(arg);
2747 if (how == -1 && PyErr_Occurred())
2748 return NULL;
2749 Py_BEGIN_ALLOW_THREADS
2750 res = shutdown(s->sock_fd, how);
2751 Py_END_ALLOW_THREADS
2752 if (res < 0)
2753 return s->errorhandler();
2754 Py_INCREF(Py_None);
2755 return Py_None;
2758 PyDoc_STRVAR(shutdown_doc,
2759 "shutdown(flag)\n\
2761 Shut down the reading side of the socket (flag == SHUT_RD), the writing side\n\
2762 of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).");
2765 /* List of methods for socket objects */
2767 static PyMethodDef sock_methods[] = {
2768 {"accept", (PyCFunction)sock_accept, METH_NOARGS,
2769 accept_doc},
2770 {"bind", (PyCFunction)sock_bind, METH_O,
2771 bind_doc},
2772 {"close", (PyCFunction)sock_close, METH_NOARGS,
2773 close_doc},
2774 {"connect", (PyCFunction)sock_connect, METH_O,
2775 connect_doc},
2776 {"connect_ex", (PyCFunction)sock_connect_ex, METH_O,
2777 connect_ex_doc},
2778 #ifndef NO_DUP
2779 {"dup", (PyCFunction)sock_dup, METH_NOARGS,
2780 dup_doc},
2781 #endif
2782 {"fileno", (PyCFunction)sock_fileno, METH_NOARGS,
2783 fileno_doc},
2784 #ifdef HAVE_GETPEERNAME
2785 {"getpeername", (PyCFunction)sock_getpeername,
2786 METH_NOARGS, getpeername_doc},
2787 #endif
2788 {"getsockname", (PyCFunction)sock_getsockname,
2789 METH_NOARGS, getsockname_doc},
2790 {"getsockopt", (PyCFunction)sock_getsockopt, METH_VARARGS,
2791 getsockopt_doc},
2792 {"listen", (PyCFunction)sock_listen, METH_O,
2793 listen_doc},
2794 #ifndef NO_DUP
2795 {"makefile", (PyCFunction)sock_makefile, METH_VARARGS,
2796 makefile_doc},
2797 #endif
2798 {"recv", (PyCFunction)sock_recv, METH_VARARGS,
2799 recv_doc},
2800 {"recv_into", (PyCFunction)sock_recv_into, METH_VARARGS | METH_KEYWORDS,
2801 recv_into_doc},
2802 {"recvfrom", (PyCFunction)sock_recvfrom, METH_VARARGS,
2803 recvfrom_doc},
2804 {"recvfrom_into", (PyCFunction)sock_recvfrom_into, METH_VARARGS | METH_KEYWORDS,
2805 recvfrom_into_doc},
2806 {"send", (PyCFunction)sock_send, METH_VARARGS,
2807 send_doc},
2808 {"sendall", (PyCFunction)sock_sendall, METH_VARARGS,
2809 sendall_doc},
2810 {"sendto", (PyCFunction)sock_sendto, METH_VARARGS,
2811 sendto_doc},
2812 {"setblocking", (PyCFunction)sock_setblocking, METH_O,
2813 setblocking_doc},
2814 {"settimeout", (PyCFunction)sock_settimeout, METH_O,
2815 settimeout_doc},
2816 {"gettimeout", (PyCFunction)sock_gettimeout, METH_NOARGS,
2817 gettimeout_doc},
2818 {"setsockopt", (PyCFunction)sock_setsockopt, METH_VARARGS,
2819 setsockopt_doc},
2820 {"shutdown", (PyCFunction)sock_shutdown, METH_O,
2821 shutdown_doc},
2822 #ifdef RISCOS
2823 {"sleeptaskw", (PyCFunction)sock_sleeptaskw, METH_O,
2824 sleeptaskw_doc},
2825 #endif
2826 {NULL, NULL} /* sentinel */
2829 /* SockObject members */
2830 static PyMemberDef sock_memberlist[] = {
2831 {"family", T_INT, offsetof(PySocketSockObject, sock_family), READONLY, "the socket family"},
2832 {"type", T_INT, offsetof(PySocketSockObject, sock_type), READONLY, "the socket type"},
2833 {"proto", T_INT, offsetof(PySocketSockObject, sock_proto), READONLY, "the socket protocol"},
2834 {"timeout", T_DOUBLE, offsetof(PySocketSockObject, sock_timeout), READONLY, "the socket timeout"},
2835 {0},
2838 /* Deallocate a socket object in response to the last Py_DECREF().
2839 First close the file description. */
2841 static void
2842 sock_dealloc(PySocketSockObject *s)
2844 if (s->sock_fd != -1)
2845 (void) SOCKETCLOSE(s->sock_fd);
2846 Py_Type(s)->tp_free((PyObject *)s);
2850 static PyObject *
2851 sock_repr(PySocketSockObject *s)
2853 char buf[512];
2854 #if SIZEOF_SOCKET_T > SIZEOF_LONG
2855 if (s->sock_fd > LONG_MAX) {
2856 /* this can occur on Win64, and actually there is a special
2857 ugly printf formatter for decimal pointer length integer
2858 printing, only bother if necessary*/
2859 PyErr_SetString(PyExc_OverflowError,
2860 "no printf formatter to display "
2861 "the socket descriptor in decimal");
2862 return NULL;
2864 #endif
2865 PyOS_snprintf(
2866 buf, sizeof(buf),
2867 "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
2868 (long)s->sock_fd, s->sock_family,
2869 s->sock_type,
2870 s->sock_proto);
2871 return PyString_FromString(buf);
2875 /* Create a new, uninitialized socket object. */
2877 static PyObject *
2878 sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2880 PyObject *new;
2882 new = type->tp_alloc(type, 0);
2883 if (new != NULL) {
2884 ((PySocketSockObject *)new)->sock_fd = -1;
2885 ((PySocketSockObject *)new)->sock_timeout = -1.0;
2886 ((PySocketSockObject *)new)->errorhandler = &set_error;
2888 return new;
2892 /* Initialize a new socket object. */
2894 /*ARGSUSED*/
2895 static int
2896 sock_initobj(PyObject *self, PyObject *args, PyObject *kwds)
2898 PySocketSockObject *s = (PySocketSockObject *)self;
2899 SOCKET_T fd;
2900 int family = AF_INET, type = SOCK_STREAM, proto = 0;
2901 static char *keywords[] = {"family", "type", "proto", 0};
2903 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2904 "|iii:socket", keywords,
2905 &family, &type, &proto))
2906 return -1;
2908 Py_BEGIN_ALLOW_THREADS
2909 fd = socket(family, type, proto);
2910 Py_END_ALLOW_THREADS
2912 #ifdef MS_WINDOWS
2913 if (fd == INVALID_SOCKET)
2914 #else
2915 if (fd < 0)
2916 #endif
2918 set_error();
2919 return -1;
2921 init_sockobject(s, fd, family, type, proto);
2923 return 0;
2928 /* Type object for socket objects. */
2930 static PyTypeObject sock_type = {
2931 PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */
2932 "_socket.socket", /* tp_name */
2933 sizeof(PySocketSockObject), /* tp_basicsize */
2934 0, /* tp_itemsize */
2935 (destructor)sock_dealloc, /* tp_dealloc */
2936 0, /* tp_print */
2937 0, /* tp_getattr */
2938 0, /* tp_setattr */
2939 0, /* tp_compare */
2940 (reprfunc)sock_repr, /* tp_repr */
2941 0, /* tp_as_number */
2942 0, /* tp_as_sequence */
2943 0, /* tp_as_mapping */
2944 0, /* tp_hash */
2945 0, /* tp_call */
2946 0, /* tp_str */
2947 PyObject_GenericGetAttr, /* tp_getattro */
2948 0, /* tp_setattro */
2949 0, /* tp_as_buffer */
2950 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2951 sock_doc, /* tp_doc */
2952 0, /* tp_traverse */
2953 0, /* tp_clear */
2954 0, /* tp_richcompare */
2955 0, /* tp_weaklistoffset */
2956 0, /* tp_iter */
2957 0, /* tp_iternext */
2958 sock_methods, /* tp_methods */
2959 sock_memberlist, /* tp_members */
2960 0, /* tp_getset */
2961 0, /* tp_base */
2962 0, /* tp_dict */
2963 0, /* tp_descr_get */
2964 0, /* tp_descr_set */
2965 0, /* tp_dictoffset */
2966 sock_initobj, /* tp_init */
2967 PyType_GenericAlloc, /* tp_alloc */
2968 sock_new, /* tp_new */
2969 PyObject_Del, /* tp_free */
2973 /* Python interface to gethostname(). */
2975 /*ARGSUSED*/
2976 static PyObject *
2977 socket_gethostname(PyObject *self, PyObject *unused)
2979 char buf[1024];
2980 int res;
2981 Py_BEGIN_ALLOW_THREADS
2982 res = gethostname(buf, (int) sizeof buf - 1);
2983 Py_END_ALLOW_THREADS
2984 if (res < 0)
2985 return set_error();
2986 buf[sizeof buf - 1] = '\0';
2987 return PyString_FromString(buf);
2990 PyDoc_STRVAR(gethostname_doc,
2991 "gethostname() -> string\n\
2993 Return the current host name.");
2996 /* Python interface to gethostbyname(name). */
2998 /*ARGSUSED*/
2999 static PyObject *
3000 socket_gethostbyname(PyObject *self, PyObject *args)
3002 char *name;
3003 sock_addr_t addrbuf;
3005 if (!PyArg_ParseTuple(args, "s:gethostbyname", &name))
3006 return NULL;
3007 if (setipaddr(name, SAS2SA(&addrbuf), sizeof(addrbuf), AF_INET) < 0)
3008 return NULL;
3009 return makeipaddr(SAS2SA(&addrbuf), sizeof(struct sockaddr_in));
3012 PyDoc_STRVAR(gethostbyname_doc,
3013 "gethostbyname(host) -> address\n\
3015 Return the IP address (a string of the form '255.255.255.255') for a host.");
3018 /* Convenience function common to gethostbyname_ex and gethostbyaddr */
3020 static PyObject *
3021 gethost_common(struct hostent *h, struct sockaddr *addr, int alen, int af)
3023 char **pch;
3024 PyObject *rtn_tuple = (PyObject *)NULL;
3025 PyObject *name_list = (PyObject *)NULL;
3026 PyObject *addr_list = (PyObject *)NULL;
3027 PyObject *tmp;
3029 if (h == NULL) {
3030 /* Let's get real error message to return */
3031 #ifndef RISCOS
3032 set_herror(h_errno);
3033 #else
3034 PyErr_SetString(socket_error, "host not found");
3035 #endif
3036 return NULL;
3039 if (h->h_addrtype != af) {
3040 #ifdef HAVE_STRERROR
3041 /* Let's get real error message to return */
3042 PyErr_SetString(socket_error,
3043 (char *)strerror(EAFNOSUPPORT));
3044 #else
3045 PyErr_SetString(
3046 socket_error,
3047 "Address family not supported by protocol family");
3048 #endif
3049 return NULL;
3052 switch (af) {
3054 case AF_INET:
3055 if (alen < sizeof(struct sockaddr_in))
3056 return NULL;
3057 break;
3059 #ifdef ENABLE_IPV6
3060 case AF_INET6:
3061 if (alen < sizeof(struct sockaddr_in6))
3062 return NULL;
3063 break;
3064 #endif
3068 if ((name_list = PyList_New(0)) == NULL)
3069 goto err;
3071 if ((addr_list = PyList_New(0)) == NULL)
3072 goto err;
3074 /* SF #1511317: h_aliases can be NULL */
3075 if (h->h_aliases) {
3076 for (pch = h->h_aliases; *pch != NULL; pch++) {
3077 int status;
3078 tmp = PyString_FromString(*pch);
3079 if (tmp == NULL)
3080 goto err;
3082 status = PyList_Append(name_list, tmp);
3083 Py_DECREF(tmp);
3085 if (status)
3086 goto err;
3090 for (pch = h->h_addr_list; *pch != NULL; pch++) {
3091 int status;
3093 switch (af) {
3095 case AF_INET:
3097 struct sockaddr_in sin;
3098 memset(&sin, 0, sizeof(sin));
3099 sin.sin_family = af;
3100 #ifdef HAVE_SOCKADDR_SA_LEN
3101 sin.sin_len = sizeof(sin);
3102 #endif
3103 memcpy(&sin.sin_addr, *pch, sizeof(sin.sin_addr));
3104 tmp = makeipaddr((struct sockaddr *)&sin, sizeof(sin));
3106 if (pch == h->h_addr_list && alen >= sizeof(sin))
3107 memcpy((char *) addr, &sin, sizeof(sin));
3108 break;
3111 #ifdef ENABLE_IPV6
3112 case AF_INET6:
3114 struct sockaddr_in6 sin6;
3115 memset(&sin6, 0, sizeof(sin6));
3116 sin6.sin6_family = af;
3117 #ifdef HAVE_SOCKADDR_SA_LEN
3118 sin6.sin6_len = sizeof(sin6);
3119 #endif
3120 memcpy(&sin6.sin6_addr, *pch, sizeof(sin6.sin6_addr));
3121 tmp = makeipaddr((struct sockaddr *)&sin6,
3122 sizeof(sin6));
3124 if (pch == h->h_addr_list && alen >= sizeof(sin6))
3125 memcpy((char *) addr, &sin6, sizeof(sin6));
3126 break;
3128 #endif
3130 default: /* can't happen */
3131 PyErr_SetString(socket_error,
3132 "unsupported address family");
3133 return NULL;
3136 if (tmp == NULL)
3137 goto err;
3139 status = PyList_Append(addr_list, tmp);
3140 Py_DECREF(tmp);
3142 if (status)
3143 goto err;
3146 rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list);
3148 err:
3149 Py_XDECREF(name_list);
3150 Py_XDECREF(addr_list);
3151 return rtn_tuple;
3155 /* Python interface to gethostbyname_ex(name). */
3157 /*ARGSUSED*/
3158 static PyObject *
3159 socket_gethostbyname_ex(PyObject *self, PyObject *args)
3161 char *name;
3162 struct hostent *h;
3163 #ifdef ENABLE_IPV6
3164 struct sockaddr_storage addr;
3165 #else
3166 struct sockaddr_in addr;
3167 #endif
3168 struct sockaddr *sa;
3169 PyObject *ret;
3170 #ifdef HAVE_GETHOSTBYNAME_R
3171 struct hostent hp_allocated;
3172 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
3173 struct hostent_data data;
3174 #else
3175 char buf[16384];
3176 int buf_len = (sizeof buf) - 1;
3177 int errnop;
3178 #endif
3179 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3180 int result;
3181 #endif
3182 #endif /* HAVE_GETHOSTBYNAME_R */
3184 if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name))
3185 return NULL;
3186 if (setipaddr(name, (struct sockaddr *)&addr, sizeof(addr), AF_INET) < 0)
3187 return NULL;
3188 Py_BEGIN_ALLOW_THREADS
3189 #ifdef HAVE_GETHOSTBYNAME_R
3190 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3191 result = gethostbyname_r(name, &hp_allocated, buf, buf_len,
3192 &h, &errnop);
3193 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
3194 h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
3195 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
3196 memset((void *) &data, '\0', sizeof(data));
3197 result = gethostbyname_r(name, &hp_allocated, &data);
3198 h = (result != 0) ? NULL : &hp_allocated;
3199 #endif
3200 #else /* not HAVE_GETHOSTBYNAME_R */
3201 #ifdef USE_GETHOSTBYNAME_LOCK
3202 PyThread_acquire_lock(netdb_lock, 1);
3203 #endif
3204 h = gethostbyname(name);
3205 #endif /* HAVE_GETHOSTBYNAME_R */
3206 Py_END_ALLOW_THREADS
3207 /* Some C libraries would require addr.__ss_family instead of
3208 addr.ss_family.
3209 Therefore, we cast the sockaddr_storage into sockaddr to
3210 access sa_family. */
3211 sa = (struct sockaddr*)&addr;
3212 ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr),
3213 sa->sa_family);
3214 #ifdef USE_GETHOSTBYNAME_LOCK
3215 PyThread_release_lock(netdb_lock);
3216 #endif
3217 return ret;
3220 PyDoc_STRVAR(ghbn_ex_doc,
3221 "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
3223 Return the true host name, a list of aliases, and a list of IP addresses,\n\
3224 for a host. The host argument is a string giving a host name or IP number.");
3227 /* Python interface to gethostbyaddr(IP). */
3229 /*ARGSUSED*/
3230 static PyObject *
3231 socket_gethostbyaddr(PyObject *self, PyObject *args)
3233 #ifdef ENABLE_IPV6
3234 struct sockaddr_storage addr;
3235 #else
3236 struct sockaddr_in addr;
3237 #endif
3238 struct sockaddr *sa = (struct sockaddr *)&addr;
3239 char *ip_num;
3240 struct hostent *h;
3241 PyObject *ret;
3242 #ifdef HAVE_GETHOSTBYNAME_R
3243 struct hostent hp_allocated;
3244 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
3245 struct hostent_data data;
3246 #else
3247 char buf[16384];
3248 int buf_len = (sizeof buf) - 1;
3249 int errnop;
3250 #endif
3251 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3252 int result;
3253 #endif
3254 #endif /* HAVE_GETHOSTBYNAME_R */
3255 char *ap;
3256 int al;
3257 int af;
3259 if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num))
3260 return NULL;
3261 af = AF_UNSPEC;
3262 if (setipaddr(ip_num, sa, sizeof(addr), af) < 0)
3263 return NULL;
3264 af = sa->sa_family;
3265 ap = NULL;
3266 al = 0;
3267 switch (af) {
3268 case AF_INET:
3269 ap = (char *)&((struct sockaddr_in *)sa)->sin_addr;
3270 al = sizeof(((struct sockaddr_in *)sa)->sin_addr);
3271 break;
3272 #ifdef ENABLE_IPV6
3273 case AF_INET6:
3274 ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr;
3275 al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr);
3276 break;
3277 #endif
3278 default:
3279 PyErr_SetString(socket_error, "unsupported address family");
3280 return NULL;
3282 Py_BEGIN_ALLOW_THREADS
3283 #ifdef HAVE_GETHOSTBYNAME_R
3284 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3285 result = gethostbyaddr_r(ap, al, af,
3286 &hp_allocated, buf, buf_len,
3287 &h, &errnop);
3288 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
3289 h = gethostbyaddr_r(ap, al, af,
3290 &hp_allocated, buf, buf_len, &errnop);
3291 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
3292 memset((void *) &data, '\0', sizeof(data));
3293 result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data);
3294 h = (result != 0) ? NULL : &hp_allocated;
3295 #endif
3296 #else /* not HAVE_GETHOSTBYNAME_R */
3297 #ifdef USE_GETHOSTBYNAME_LOCK
3298 PyThread_acquire_lock(netdb_lock, 1);
3299 #endif
3300 h = gethostbyaddr(ap, al, af);
3301 #endif /* HAVE_GETHOSTBYNAME_R */
3302 Py_END_ALLOW_THREADS
3303 ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), af);
3304 #ifdef USE_GETHOSTBYNAME_LOCK
3305 PyThread_release_lock(netdb_lock);
3306 #endif
3307 return ret;
3310 PyDoc_STRVAR(gethostbyaddr_doc,
3311 "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
3313 Return the true host name, a list of aliases, and a list of IP addresses,\n\
3314 for a host. The host argument is a string giving a host name or IP number.");
3317 /* Python interface to getservbyname(name).
3318 This only returns the port number, since the other info is already
3319 known or not useful (like the list of aliases). */
3321 /*ARGSUSED*/
3322 static PyObject *
3323 socket_getservbyname(PyObject *self, PyObject *args)
3325 char *name, *proto=NULL;
3326 struct servent *sp;
3327 if (!PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto))
3328 return NULL;
3329 Py_BEGIN_ALLOW_THREADS
3330 sp = getservbyname(name, proto);
3331 Py_END_ALLOW_THREADS
3332 if (sp == NULL) {
3333 PyErr_SetString(socket_error, "service/proto not found");
3334 return NULL;
3336 return PyInt_FromLong((long) ntohs(sp->s_port));
3339 PyDoc_STRVAR(getservbyname_doc,
3340 "getservbyname(servicename[, protocolname]) -> integer\n\
3342 Return a port number from a service name and protocol name.\n\
3343 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3344 otherwise any protocol will match.");
3347 /* Python interface to getservbyport(port).
3348 This only returns the service name, since the other info is already
3349 known or not useful (like the list of aliases). */
3351 /*ARGSUSED*/
3352 static PyObject *
3353 socket_getservbyport(PyObject *self, PyObject *args)
3355 unsigned short port;
3356 char *proto=NULL;
3357 struct servent *sp;
3358 if (!PyArg_ParseTuple(args, "H|s:getservbyport", &port, &proto))
3359 return NULL;
3360 Py_BEGIN_ALLOW_THREADS
3361 sp = getservbyport(htons(port), proto);
3362 Py_END_ALLOW_THREADS
3363 if (sp == NULL) {
3364 PyErr_SetString(socket_error, "port/proto not found");
3365 return NULL;
3367 return PyString_FromString(sp->s_name);
3370 PyDoc_STRVAR(getservbyport_doc,
3371 "getservbyport(port[, protocolname]) -> string\n\
3373 Return the service name from a port number and protocol name.\n\
3374 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3375 otherwise any protocol will match.");
3377 /* Python interface to getprotobyname(name).
3378 This only returns the protocol number, since the other info is
3379 already known or not useful (like the list of aliases). */
3381 /*ARGSUSED*/
3382 static PyObject *
3383 socket_getprotobyname(PyObject *self, PyObject *args)
3385 char *name;
3386 struct protoent *sp;
3387 #ifdef __BEOS__
3388 /* Not available in BeOS yet. - [cjh] */
3389 PyErr_SetString(socket_error, "getprotobyname not supported");
3390 return NULL;
3391 #else
3392 if (!PyArg_ParseTuple(args, "s:getprotobyname", &name))
3393 return NULL;
3394 Py_BEGIN_ALLOW_THREADS
3395 sp = getprotobyname(name);
3396 Py_END_ALLOW_THREADS
3397 if (sp == NULL) {
3398 PyErr_SetString(socket_error, "protocol not found");
3399 return NULL;
3401 return PyInt_FromLong((long) sp->p_proto);
3402 #endif
3405 PyDoc_STRVAR(getprotobyname_doc,
3406 "getprotobyname(name) -> integer\n\
3408 Return the protocol number for the named protocol. (Rarely used.)");
3411 #ifdef HAVE_SOCKETPAIR
3412 /* Create a pair of sockets using the socketpair() function.
3413 Arguments as for socket() except the default family is AF_UNIX if
3414 defined on the platform; otherwise, the default is AF_INET. */
3416 /*ARGSUSED*/
3417 static PyObject *
3418 socket_socketpair(PyObject *self, PyObject *args)
3420 PySocketSockObject *s0 = NULL, *s1 = NULL;
3421 SOCKET_T sv[2];
3422 int family, type = SOCK_STREAM, proto = 0;
3423 PyObject *res = NULL;
3425 #if defined(AF_UNIX)
3426 family = AF_UNIX;
3427 #else
3428 family = AF_INET;
3429 #endif
3430 if (!PyArg_ParseTuple(args, "|iii:socketpair",
3431 &family, &type, &proto))
3432 return NULL;
3433 /* Create a pair of socket fds */
3434 if (socketpair(family, type, proto, sv) < 0)
3435 return set_error();
3436 s0 = new_sockobject(sv[0], family, type, proto);
3437 if (s0 == NULL)
3438 goto finally;
3439 s1 = new_sockobject(sv[1], family, type, proto);
3440 if (s1 == NULL)
3441 goto finally;
3442 res = PyTuple_Pack(2, s0, s1);
3444 finally:
3445 if (res == NULL) {
3446 if (s0 == NULL)
3447 SOCKETCLOSE(sv[0]);
3448 if (s1 == NULL)
3449 SOCKETCLOSE(sv[1]);
3451 Py_XDECREF(s0);
3452 Py_XDECREF(s1);
3453 return res;
3456 PyDoc_STRVAR(socketpair_doc,
3457 "socketpair([family[, type[, proto]]]) -> (socket object, socket object)\n\
3459 Create a pair of socket objects from the sockets returned by the platform\n\
3460 socketpair() function.\n\
3461 The arguments are the same as for socket() except the default family is\n\
3462 AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");
3464 #endif /* HAVE_SOCKETPAIR */
3467 #ifndef NO_DUP
3468 /* Create a socket object from a numeric file description.
3469 Useful e.g. if stdin is a socket.
3470 Additional arguments as for socket(). */
3472 /*ARGSUSED*/
3473 static PyObject *
3474 socket_fromfd(PyObject *self, PyObject *args)
3476 PySocketSockObject *s;
3477 SOCKET_T fd;
3478 int family, type, proto = 0;
3479 if (!PyArg_ParseTuple(args, "iii|i:fromfd",
3480 &fd, &family, &type, &proto))
3481 return NULL;
3482 /* Dup the fd so it and the socket can be closed independently */
3483 fd = dup(fd);
3484 if (fd < 0)
3485 return set_error();
3486 s = new_sockobject(fd, family, type, proto);
3487 return (PyObject *) s;
3490 PyDoc_STRVAR(fromfd_doc,
3491 "fromfd(fd, family, type[, proto]) -> socket object\n\
3493 Create a socket object from a duplicate of the given\n\
3494 file descriptor.\n\
3495 The remaining arguments are the same as for socket().");
3497 #endif /* NO_DUP */
3500 static PyObject *
3501 socket_ntohs(PyObject *self, PyObject *args)
3503 int x1, x2;
3505 if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) {
3506 return NULL;
3508 if (x1 < 0) {
3509 PyErr_SetString(PyExc_OverflowError,
3510 "can't convert negative number to unsigned long");
3511 return NULL;
3513 x2 = (unsigned int)ntohs((unsigned short)x1);
3514 return PyInt_FromLong(x2);
3517 PyDoc_STRVAR(ntohs_doc,
3518 "ntohs(integer) -> integer\n\
3520 Convert a 16-bit integer from network to host byte order.");
3523 static PyObject *
3524 socket_ntohl(PyObject *self, PyObject *arg)
3526 unsigned long x;
3528 if (PyInt_Check(arg)) {
3529 x = PyInt_AS_LONG(arg);
3530 if (x == (unsigned long) -1 && PyErr_Occurred())
3531 return NULL;
3532 if ((long)x < 0) {
3533 PyErr_SetString(PyExc_OverflowError,
3534 "can't convert negative number to unsigned long");
3535 return NULL;
3538 else if (PyLong_Check(arg)) {
3539 x = PyLong_AsUnsignedLong(arg);
3540 if (x == (unsigned long) -1 && PyErr_Occurred())
3541 return NULL;
3542 #if SIZEOF_LONG > 4
3544 unsigned long y;
3545 /* only want the trailing 32 bits */
3546 y = x & 0xFFFFFFFFUL;
3547 if (y ^ x)
3548 return PyErr_Format(PyExc_OverflowError,
3549 "long int larger than 32 bits");
3550 x = y;
3552 #endif
3554 else
3555 return PyErr_Format(PyExc_TypeError,
3556 "expected int/long, %s found",
3557 Py_Type(arg)->tp_name);
3558 if (x == (unsigned long) -1 && PyErr_Occurred())
3559 return NULL;
3560 return PyLong_FromUnsignedLong(ntohl(x));
3563 PyDoc_STRVAR(ntohl_doc,
3564 "ntohl(integer) -> integer\n\
3566 Convert a 32-bit integer from network to host byte order.");
3569 static PyObject *
3570 socket_htons(PyObject *self, PyObject *args)
3572 int x1, x2;
3574 if (!PyArg_ParseTuple(args, "i:htons", &x1)) {
3575 return NULL;
3577 if (x1 < 0) {
3578 PyErr_SetString(PyExc_OverflowError,
3579 "can't convert negative number to unsigned long");
3580 return NULL;
3582 x2 = (unsigned int)htons((unsigned short)x1);
3583 return PyInt_FromLong(x2);
3586 PyDoc_STRVAR(htons_doc,
3587 "htons(integer) -> integer\n\
3589 Convert a 16-bit integer from host to network byte order.");
3592 static PyObject *
3593 socket_htonl(PyObject *self, PyObject *arg)
3595 unsigned long x;
3597 if (PyInt_Check(arg)) {
3598 x = PyInt_AS_LONG(arg);
3599 if (x == (unsigned long) -1 && PyErr_Occurred())
3600 return NULL;
3601 if ((long)x < 0) {
3602 PyErr_SetString(PyExc_OverflowError,
3603 "can't convert negative number to unsigned long");
3604 return NULL;
3607 else if (PyLong_Check(arg)) {
3608 x = PyLong_AsUnsignedLong(arg);
3609 if (x == (unsigned long) -1 && PyErr_Occurred())
3610 return NULL;
3611 #if SIZEOF_LONG > 4
3613 unsigned long y;
3614 /* only want the trailing 32 bits */
3615 y = x & 0xFFFFFFFFUL;
3616 if (y ^ x)
3617 return PyErr_Format(PyExc_OverflowError,
3618 "long int larger than 32 bits");
3619 x = y;
3621 #endif
3623 else
3624 return PyErr_Format(PyExc_TypeError,
3625 "expected int/long, %s found",
3626 Py_Type(arg)->tp_name);
3627 return PyLong_FromUnsignedLong(htonl((unsigned long)x));
3630 PyDoc_STRVAR(htonl_doc,
3631 "htonl(integer) -> integer\n\
3633 Convert a 32-bit integer from host to network byte order.");
3635 /* socket.inet_aton() and socket.inet_ntoa() functions. */
3637 PyDoc_STRVAR(inet_aton_doc,
3638 "inet_aton(string) -> packed 32-bit IP representation\n\
3640 Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
3641 binary format used in low-level network functions.");
3643 static PyObject*
3644 socket_inet_aton(PyObject *self, PyObject *args)
3646 #ifndef INADDR_NONE
3647 #define INADDR_NONE (-1)
3648 #endif
3649 #ifdef HAVE_INET_ATON
3650 struct in_addr buf;
3651 #endif
3653 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
3654 /* Have to use inet_addr() instead */
3655 unsigned long packed_addr;
3656 #endif
3657 char *ip_addr;
3659 if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr))
3660 return NULL;
3663 #ifdef HAVE_INET_ATON
3665 #ifdef USE_INET_ATON_WEAKLINK
3666 if (inet_aton != NULL) {
3667 #endif
3668 if (inet_aton(ip_addr, &buf))
3669 return PyString_FromStringAndSize((char *)(&buf),
3670 sizeof(buf));
3672 PyErr_SetString(socket_error,
3673 "illegal IP address string passed to inet_aton");
3674 return NULL;
3676 #ifdef USE_INET_ATON_WEAKLINK
3677 } else {
3678 #endif
3680 #endif
3682 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
3684 /* special-case this address as inet_addr might return INADDR_NONE
3685 * for this */
3686 if (strcmp(ip_addr, "255.255.255.255") == 0) {
3687 packed_addr = 0xFFFFFFFF;
3688 } else {
3690 packed_addr = inet_addr(ip_addr);
3692 if (packed_addr == INADDR_NONE) { /* invalid address */
3693 PyErr_SetString(socket_error,
3694 "illegal IP address string passed to inet_aton");
3695 return NULL;
3698 return PyString_FromStringAndSize((char *) &packed_addr,
3699 sizeof(packed_addr));
3701 #ifdef USE_INET_ATON_WEAKLINK
3703 #endif
3705 #endif
3708 PyDoc_STRVAR(inet_ntoa_doc,
3709 "inet_ntoa(packed_ip) -> ip_address_string\n\
3711 Convert an IP address from 32-bit packed binary format to string format");
3713 static PyObject*
3714 socket_inet_ntoa(PyObject *self, PyObject *args)
3716 char *packed_str;
3717 int addr_len;
3718 struct in_addr packed_addr;
3720 if (!PyArg_ParseTuple(args, "s#:inet_ntoa", &packed_str, &addr_len)) {
3721 return NULL;
3724 if (addr_len != sizeof(packed_addr)) {
3725 PyErr_SetString(socket_error,
3726 "packed IP wrong length for inet_ntoa");
3727 return NULL;
3730 memcpy(&packed_addr, packed_str, addr_len);
3732 return PyString_FromString(inet_ntoa(packed_addr));
3735 #ifdef HAVE_INET_PTON
3737 PyDoc_STRVAR(inet_pton_doc,
3738 "inet_pton(af, ip) -> packed IP address string\n\
3740 Convert an IP address from string format to a packed string suitable\n\
3741 for use with low-level network functions.");
3743 static PyObject *
3744 socket_inet_pton(PyObject *self, PyObject *args)
3746 int af;
3747 char* ip;
3748 int retval;
3749 #ifdef ENABLE_IPV6
3750 char packed[MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
3751 #else
3752 char packed[sizeof(struct in_addr)];
3753 #endif
3754 if (!PyArg_ParseTuple(args, "is:inet_pton", &af, &ip)) {
3755 return NULL;
3758 #if !defined(ENABLE_IPV6) && defined(AF_INET6)
3759 if(af == AF_INET6) {
3760 PyErr_SetString(socket_error,
3761 "can't use AF_INET6, IPv6 is disabled");
3762 return NULL;
3764 #endif
3766 retval = inet_pton(af, ip, packed);
3767 if (retval < 0) {
3768 PyErr_SetFromErrno(socket_error);
3769 return NULL;
3770 } else if (retval == 0) {
3771 PyErr_SetString(socket_error,
3772 "illegal IP address string passed to inet_pton");
3773 return NULL;
3774 } else if (af == AF_INET) {
3775 return PyString_FromStringAndSize(packed,
3776 sizeof(struct in_addr));
3777 #ifdef ENABLE_IPV6
3778 } else if (af == AF_INET6) {
3779 return PyString_FromStringAndSize(packed,
3780 sizeof(struct in6_addr));
3781 #endif
3782 } else {
3783 PyErr_SetString(socket_error, "unknown address family");
3784 return NULL;
3788 PyDoc_STRVAR(inet_ntop_doc,
3789 "inet_ntop(af, packed_ip) -> string formatted IP address\n\
3791 Convert a packed IP address of the given family to string format.");
3793 static PyObject *
3794 socket_inet_ntop(PyObject *self, PyObject *args)
3796 int af;
3797 char* packed;
3798 int len;
3799 const char* retval;
3800 #ifdef ENABLE_IPV6
3801 char ip[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) + 1];
3802 #else
3803 char ip[INET_ADDRSTRLEN + 1];
3804 #endif
3806 /* Guarantee NUL-termination for PyString_FromString() below */
3807 memset((void *) &ip[0], '\0', sizeof(ip));
3809 if (!PyArg_ParseTuple(args, "is#:inet_ntop", &af, &packed, &len)) {
3810 return NULL;
3813 if (af == AF_INET) {
3814 if (len != sizeof(struct in_addr)) {
3815 PyErr_SetString(PyExc_ValueError,
3816 "invalid length of packed IP address string");
3817 return NULL;
3819 #ifdef ENABLE_IPV6
3820 } else if (af == AF_INET6) {
3821 if (len != sizeof(struct in6_addr)) {
3822 PyErr_SetString(PyExc_ValueError,
3823 "invalid length of packed IP address string");
3824 return NULL;
3826 #endif
3827 } else {
3828 PyErr_Format(PyExc_ValueError,
3829 "unknown address family %d", af);
3830 return NULL;
3833 retval = inet_ntop(af, packed, ip, sizeof(ip));
3834 if (!retval) {
3835 PyErr_SetFromErrno(socket_error);
3836 return NULL;
3837 } else {
3838 return PyString_FromString(retval);
3841 /* NOTREACHED */
3842 PyErr_SetString(PyExc_RuntimeError, "invalid handling of inet_ntop");
3843 return NULL;
3846 #endif /* HAVE_INET_PTON */
3848 /* Python interface to getaddrinfo(host, port). */
3850 /*ARGSUSED*/
3851 static PyObject *
3852 socket_getaddrinfo(PyObject *self, PyObject *args)
3854 struct addrinfo hints, *res;
3855 struct addrinfo *res0 = NULL;
3856 PyObject *hobj = NULL;
3857 PyObject *pobj = (PyObject *)NULL;
3858 char pbuf[30];
3859 char *hptr, *pptr;
3860 int family, socktype, protocol, flags;
3861 int error;
3862 PyObject *all = (PyObject *)NULL;
3863 PyObject *single = (PyObject *)NULL;
3864 PyObject *idna = NULL;
3866 family = socktype = protocol = flags = 0;
3867 family = AF_UNSPEC;
3868 if (!PyArg_ParseTuple(args, "OO|iiii:getaddrinfo",
3869 &hobj, &pobj, &family, &socktype,
3870 &protocol, &flags)) {
3871 return NULL;
3873 if (hobj == Py_None) {
3874 hptr = NULL;
3875 } else if (PyUnicode_Check(hobj)) {
3876 idna = PyObject_CallMethod(hobj, "encode", "s", "idna");
3877 if (!idna)
3878 return NULL;
3879 hptr = PyString_AsString(idna);
3880 } else if (PyString_Check(hobj)) {
3881 hptr = PyString_AsString(hobj);
3882 } else {
3883 PyErr_SetString(PyExc_TypeError,
3884 "getaddrinfo() argument 1 must be string or None");
3885 return NULL;
3887 if (PyInt_Check(pobj)) {
3888 PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", PyInt_AsLong(pobj));
3889 pptr = pbuf;
3890 } else if (PyString_Check(pobj)) {
3891 pptr = PyString_AsString(pobj);
3892 } else if (pobj == Py_None) {
3893 pptr = (char *)NULL;
3894 } else {
3895 PyErr_SetString(socket_error, "Int or String expected");
3896 goto err;
3898 memset(&hints, 0, sizeof(hints));
3899 hints.ai_family = family;
3900 hints.ai_socktype = socktype;
3901 hints.ai_protocol = protocol;
3902 hints.ai_flags = flags;
3903 Py_BEGIN_ALLOW_THREADS
3904 ACQUIRE_GETADDRINFO_LOCK
3905 error = getaddrinfo(hptr, pptr, &hints, &res0);
3906 Py_END_ALLOW_THREADS
3907 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
3908 if (error) {
3909 set_gaierror(error);
3910 goto err;
3913 if ((all = PyList_New(0)) == NULL)
3914 goto err;
3915 for (res = res0; res; res = res->ai_next) {
3916 PyObject *addr =
3917 makesockaddr(-1, res->ai_addr, res->ai_addrlen, protocol);
3918 if (addr == NULL)
3919 goto err;
3920 single = Py_BuildValue("iiisO", res->ai_family,
3921 res->ai_socktype, res->ai_protocol,
3922 res->ai_canonname ? res->ai_canonname : "",
3923 addr);
3924 Py_DECREF(addr);
3925 if (single == NULL)
3926 goto err;
3928 if (PyList_Append(all, single))
3929 goto err;
3930 Py_XDECREF(single);
3932 Py_XDECREF(idna);
3933 if (res0)
3934 freeaddrinfo(res0);
3935 return all;
3936 err:
3937 Py_XDECREF(single);
3938 Py_XDECREF(all);
3939 Py_XDECREF(idna);
3940 if (res0)
3941 freeaddrinfo(res0);
3942 return (PyObject *)NULL;
3945 PyDoc_STRVAR(getaddrinfo_doc,
3946 "getaddrinfo(host, port [, family, socktype, proto, flags])\n\
3947 -> list of (family, socktype, proto, canonname, sockaddr)\n\
3949 Resolve host and port into addrinfo struct.");
3951 /* Python interface to getnameinfo(sa, flags). */
3953 /*ARGSUSED*/
3954 static PyObject *
3955 socket_getnameinfo(PyObject *self, PyObject *args)
3957 PyObject *sa = (PyObject *)NULL;
3958 int flags;
3959 char *hostp;
3960 int port, flowinfo, scope_id;
3961 char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
3962 struct addrinfo hints, *res = NULL;
3963 int error;
3964 PyObject *ret = (PyObject *)NULL;
3966 flags = flowinfo = scope_id = 0;
3967 if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags))
3968 return NULL;
3969 if (!PyArg_ParseTuple(sa, "si|ii",
3970 &hostp, &port, &flowinfo, &scope_id))
3971 return NULL;
3972 PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port);
3973 memset(&hints, 0, sizeof(hints));
3974 hints.ai_family = AF_UNSPEC;
3975 hints.ai_socktype = SOCK_DGRAM; /* make numeric port happy */
3976 Py_BEGIN_ALLOW_THREADS
3977 ACQUIRE_GETADDRINFO_LOCK
3978 error = getaddrinfo(hostp, pbuf, &hints, &res);
3979 Py_END_ALLOW_THREADS
3980 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
3981 if (error) {
3982 set_gaierror(error);
3983 goto fail;
3985 if (res->ai_next) {
3986 PyErr_SetString(socket_error,
3987 "sockaddr resolved to multiple addresses");
3988 goto fail;
3990 switch (res->ai_family) {
3991 case AF_INET:
3993 char *t1;
3994 int t2;
3995 if (PyArg_ParseTuple(sa, "si", &t1, &t2) == 0) {
3996 PyErr_SetString(socket_error,
3997 "IPv4 sockaddr must be 2 tuple");
3998 goto fail;
4000 break;
4002 #ifdef ENABLE_IPV6
4003 case AF_INET6:
4005 struct sockaddr_in6 *sin6;
4006 sin6 = (struct sockaddr_in6 *)res->ai_addr;
4007 sin6->sin6_flowinfo = flowinfo;
4008 sin6->sin6_scope_id = scope_id;
4009 break;
4011 #endif
4013 error = getnameinfo(res->ai_addr, res->ai_addrlen,
4014 hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags);
4015 if (error) {
4016 set_gaierror(error);
4017 goto fail;
4019 ret = Py_BuildValue("ss", hbuf, pbuf);
4021 fail:
4022 if (res)
4023 freeaddrinfo(res);
4024 return ret;
4027 PyDoc_STRVAR(getnameinfo_doc,
4028 "getnameinfo(sockaddr, flags) --> (host, port)\n\
4030 Get host and port for a sockaddr.");
4033 /* Python API to getting and setting the default timeout value. */
4035 static PyObject *
4036 socket_getdefaulttimeout(PyObject *self)
4038 if (defaulttimeout < 0.0) {
4039 Py_INCREF(Py_None);
4040 return Py_None;
4042 else
4043 return PyFloat_FromDouble(defaulttimeout);
4046 PyDoc_STRVAR(getdefaulttimeout_doc,
4047 "getdefaulttimeout() -> timeout\n\
4049 Returns the default timeout in floating seconds for new socket objects.\n\
4050 A value of None indicates that new socket objects have no timeout.\n\
4051 When the socket module is first imported, the default is None.");
4053 static PyObject *
4054 socket_setdefaulttimeout(PyObject *self, PyObject *arg)
4056 double timeout;
4058 if (arg == Py_None)
4059 timeout = -1.0;
4060 else {
4061 timeout = PyFloat_AsDouble(arg);
4062 if (timeout < 0.0) {
4063 if (!PyErr_Occurred())
4064 PyErr_SetString(PyExc_ValueError,
4065 "Timeout value out of range");
4066 return NULL;
4070 defaulttimeout = timeout;
4072 Py_INCREF(Py_None);
4073 return Py_None;
4076 PyDoc_STRVAR(setdefaulttimeout_doc,
4077 "setdefaulttimeout(timeout)\n\
4079 Set the default timeout in floating seconds for new socket objects.\n\
4080 A value of None indicates that new socket objects have no timeout.\n\
4081 When the socket module is first imported, the default is None.");
4084 /* List of functions exported by this module. */
4086 static PyMethodDef socket_methods[] = {
4087 {"gethostbyname", socket_gethostbyname,
4088 METH_VARARGS, gethostbyname_doc},
4089 {"gethostbyname_ex", socket_gethostbyname_ex,
4090 METH_VARARGS, ghbn_ex_doc},
4091 {"gethostbyaddr", socket_gethostbyaddr,
4092 METH_VARARGS, gethostbyaddr_doc},
4093 {"gethostname", socket_gethostname,
4094 METH_NOARGS, gethostname_doc},
4095 {"getservbyname", socket_getservbyname,
4096 METH_VARARGS, getservbyname_doc},
4097 {"getservbyport", socket_getservbyport,
4098 METH_VARARGS, getservbyport_doc},
4099 {"getprotobyname", socket_getprotobyname,
4100 METH_VARARGS, getprotobyname_doc},
4101 #ifndef NO_DUP
4102 {"fromfd", socket_fromfd,
4103 METH_VARARGS, fromfd_doc},
4104 #endif
4105 #ifdef HAVE_SOCKETPAIR
4106 {"socketpair", socket_socketpair,
4107 METH_VARARGS, socketpair_doc},
4108 #endif
4109 {"ntohs", socket_ntohs,
4110 METH_VARARGS, ntohs_doc},
4111 {"ntohl", socket_ntohl,
4112 METH_O, ntohl_doc},
4113 {"htons", socket_htons,
4114 METH_VARARGS, htons_doc},
4115 {"htonl", socket_htonl,
4116 METH_O, htonl_doc},
4117 {"inet_aton", socket_inet_aton,
4118 METH_VARARGS, inet_aton_doc},
4119 {"inet_ntoa", socket_inet_ntoa,
4120 METH_VARARGS, inet_ntoa_doc},
4121 #ifdef HAVE_INET_PTON
4122 {"inet_pton", socket_inet_pton,
4123 METH_VARARGS, inet_pton_doc},
4124 {"inet_ntop", socket_inet_ntop,
4125 METH_VARARGS, inet_ntop_doc},
4126 #endif
4127 {"getaddrinfo", socket_getaddrinfo,
4128 METH_VARARGS, getaddrinfo_doc},
4129 {"getnameinfo", socket_getnameinfo,
4130 METH_VARARGS, getnameinfo_doc},
4131 {"getdefaulttimeout", (PyCFunction)socket_getdefaulttimeout,
4132 METH_NOARGS, getdefaulttimeout_doc},
4133 {"setdefaulttimeout", socket_setdefaulttimeout,
4134 METH_O, setdefaulttimeout_doc},
4135 {NULL, NULL} /* Sentinel */
4139 #ifdef RISCOS
4140 #define OS_INIT_DEFINED
4142 static int
4143 os_init(void)
4145 _kernel_swi_regs r;
4147 r.r[0] = 0;
4148 _kernel_swi(0x43380, &r, &r);
4149 taskwindow = r.r[0];
4151 return 1;
4154 #endif /* RISCOS */
4157 #ifdef MS_WINDOWS
4158 #define OS_INIT_DEFINED
4160 /* Additional initialization and cleanup for Windows */
4162 static void
4163 os_cleanup(void)
4165 WSACleanup();
4168 static int
4169 os_init(void)
4171 WSADATA WSAData;
4172 int ret;
4173 char buf[100];
4174 ret = WSAStartup(0x0101, &WSAData);
4175 switch (ret) {
4176 case 0: /* No error */
4177 Py_AtExit(os_cleanup);
4178 return 1; /* Success */
4179 case WSASYSNOTREADY:
4180 PyErr_SetString(PyExc_ImportError,
4181 "WSAStartup failed: network not ready");
4182 break;
4183 case WSAVERNOTSUPPORTED:
4184 case WSAEINVAL:
4185 PyErr_SetString(
4186 PyExc_ImportError,
4187 "WSAStartup failed: requested version not supported");
4188 break;
4189 default:
4190 PyOS_snprintf(buf, sizeof(buf),
4191 "WSAStartup failed: error code %d", ret);
4192 PyErr_SetString(PyExc_ImportError, buf);
4193 break;
4195 return 0; /* Failure */
4198 #endif /* MS_WINDOWS */
4201 #ifdef PYOS_OS2
4202 #define OS_INIT_DEFINED
4204 /* Additional initialization for OS/2 */
4206 static int
4207 os_init(void)
4209 #ifndef PYCC_GCC
4210 char reason[64];
4211 int rc = sock_init();
4213 if (rc == 0) {
4214 return 1; /* Success */
4217 PyOS_snprintf(reason, sizeof(reason),
4218 "OS/2 TCP/IP Error# %d", sock_errno());
4219 PyErr_SetString(PyExc_ImportError, reason);
4221 return 0; /* Failure */
4222 #else
4223 /* No need to initialise sockets with GCC/EMX */
4224 return 1; /* Success */
4225 #endif
4228 #endif /* PYOS_OS2 */
4231 #ifndef OS_INIT_DEFINED
4232 static int
4233 os_init(void)
4235 return 1; /* Success */
4237 #endif
4240 /* C API table - always add new things to the end for binary
4241 compatibility. */
4242 static
4243 PySocketModule_APIObject PySocketModuleAPI =
4245 &sock_type,
4246 NULL
4250 /* Initialize the _socket module.
4252 This module is actually called "_socket", and there's a wrapper
4253 "socket.py" which implements some additional functionality. On some
4254 platforms (e.g. Windows and OS/2), socket.py also implements a
4255 wrapper for the socket type that provides missing functionality such
4256 as makefile(), dup() and fromfd(). The import of "_socket" may fail
4257 with an ImportError exception if os-specific initialization fails.
4258 On Windows, this does WINSOCK initialization. When WINSOCK is
4259 initialized succesfully, a call to WSACleanup() is scheduled to be
4260 made at exit time.
4263 PyDoc_STRVAR(socket_doc,
4264 "Implementation module for socket operations.\n\
4266 See the socket module for documentation.");
4268 PyMODINIT_FUNC
4269 init_socket(void)
4271 PyObject *m, *has_ipv6;
4273 if (!os_init())
4274 return;
4276 Py_Type(&sock_type) = &PyType_Type;
4277 m = Py_InitModule3(PySocket_MODULE_NAME,
4278 socket_methods,
4279 socket_doc);
4280 if (m == NULL)
4281 return;
4283 socket_error = PyErr_NewException("socket.error", NULL, NULL);
4284 if (socket_error == NULL)
4285 return;
4286 PySocketModuleAPI.error = socket_error;
4287 Py_INCREF(socket_error);
4288 PyModule_AddObject(m, "error", socket_error);
4289 socket_herror = PyErr_NewException("socket.herror",
4290 socket_error, NULL);
4291 if (socket_herror == NULL)
4292 return;
4293 Py_INCREF(socket_herror);
4294 PyModule_AddObject(m, "herror", socket_herror);
4295 socket_gaierror = PyErr_NewException("socket.gaierror", socket_error,
4296 NULL);
4297 if (socket_gaierror == NULL)
4298 return;
4299 Py_INCREF(socket_gaierror);
4300 PyModule_AddObject(m, "gaierror", socket_gaierror);
4301 socket_timeout = PyErr_NewException("socket.timeout",
4302 socket_error, NULL);
4303 if (socket_timeout == NULL)
4304 return;
4305 Py_INCREF(socket_timeout);
4306 PyModule_AddObject(m, "timeout", socket_timeout);
4307 Py_INCREF((PyObject *)&sock_type);
4308 if (PyModule_AddObject(m, "SocketType",
4309 (PyObject *)&sock_type) != 0)
4310 return;
4311 Py_INCREF((PyObject *)&sock_type);
4312 if (PyModule_AddObject(m, "socket",
4313 (PyObject *)&sock_type) != 0)
4314 return;
4316 #ifdef ENABLE_IPV6
4317 has_ipv6 = Py_True;
4318 #else
4319 has_ipv6 = Py_False;
4320 #endif
4321 Py_INCREF(has_ipv6);
4322 PyModule_AddObject(m, "has_ipv6", has_ipv6);
4324 /* Export C API */
4325 if (PyModule_AddObject(m, PySocket_CAPI_NAME,
4326 PyCObject_FromVoidPtr((void *)&PySocketModuleAPI, NULL)
4327 ) != 0)
4328 return;
4330 /* Address families (we only support AF_INET and AF_UNIX) */
4331 #ifdef AF_UNSPEC
4332 PyModule_AddIntConstant(m, "AF_UNSPEC", AF_UNSPEC);
4333 #endif
4334 PyModule_AddIntConstant(m, "AF_INET", AF_INET);
4335 #ifdef AF_INET6
4336 PyModule_AddIntConstant(m, "AF_INET6", AF_INET6);
4337 #endif /* AF_INET6 */
4338 #if defined(AF_UNIX)
4339 PyModule_AddIntConstant(m, "AF_UNIX", AF_UNIX);
4340 #endif /* AF_UNIX */
4341 #ifdef AF_AX25
4342 /* Amateur Radio AX.25 */
4343 PyModule_AddIntConstant(m, "AF_AX25", AF_AX25);
4344 #endif
4345 #ifdef AF_IPX
4346 PyModule_AddIntConstant(m, "AF_IPX", AF_IPX); /* Novell IPX */
4347 #endif
4348 #ifdef AF_APPLETALK
4349 /* Appletalk DDP */
4350 PyModule_AddIntConstant(m, "AF_APPLETALK", AF_APPLETALK);
4351 #endif
4352 #ifdef AF_NETROM
4353 /* Amateur radio NetROM */
4354 PyModule_AddIntConstant(m, "AF_NETROM", AF_NETROM);
4355 #endif
4356 #ifdef AF_BRIDGE
4357 /* Multiprotocol bridge */
4358 PyModule_AddIntConstant(m, "AF_BRIDGE", AF_BRIDGE);
4359 #endif
4360 #ifdef AF_ATMPVC
4361 /* ATM PVCs */
4362 PyModule_AddIntConstant(m, "AF_ATMPVC", AF_ATMPVC);
4363 #endif
4364 #ifdef AF_AAL5
4365 /* Reserved for Werner's ATM */
4366 PyModule_AddIntConstant(m, "AF_AAL5", AF_AAL5);
4367 #endif
4368 #ifdef AF_X25
4369 /* Reserved for X.25 project */
4370 PyModule_AddIntConstant(m, "AF_X25", AF_X25);
4371 #endif
4372 #ifdef AF_INET6
4373 PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); /* IP version 6 */
4374 #endif
4375 #ifdef AF_ROSE
4376 /* Amateur Radio X.25 PLP */
4377 PyModule_AddIntConstant(m, "AF_ROSE", AF_ROSE);
4378 #endif
4379 #ifdef AF_DECnet
4380 /* Reserved for DECnet project */
4381 PyModule_AddIntConstant(m, "AF_DECnet", AF_DECnet);
4382 #endif
4383 #ifdef AF_NETBEUI
4384 /* Reserved for 802.2LLC project */
4385 PyModule_AddIntConstant(m, "AF_NETBEUI", AF_NETBEUI);
4386 #endif
4387 #ifdef AF_SECURITY
4388 /* Security callback pseudo AF */
4389 PyModule_AddIntConstant(m, "AF_SECURITY", AF_SECURITY);
4390 #endif
4391 #ifdef AF_KEY
4392 /* PF_KEY key management API */
4393 PyModule_AddIntConstant(m, "AF_KEY", AF_KEY);
4394 #endif
4395 #ifdef AF_NETLINK
4396 /* */
4397 PyModule_AddIntConstant(m, "AF_NETLINK", AF_NETLINK);
4398 PyModule_AddIntConstant(m, "NETLINK_ROUTE", NETLINK_ROUTE);
4399 #ifdef NETLINK_SKIP
4400 PyModule_AddIntConstant(m, "NETLINK_SKIP", NETLINK_SKIP);
4401 #endif
4402 #ifdef NETLINK_W1
4403 PyModule_AddIntConstant(m, "NETLINK_W1", NETLINK_W1);
4404 #endif
4405 PyModule_AddIntConstant(m, "NETLINK_USERSOCK", NETLINK_USERSOCK);
4406 PyModule_AddIntConstant(m, "NETLINK_FIREWALL", NETLINK_FIREWALL);
4407 #ifdef NETLINK_TCPDIAG
4408 PyModule_AddIntConstant(m, "NETLINK_TCPDIAG", NETLINK_TCPDIAG);
4409 #endif
4410 #ifdef NETLINK_NFLOG
4411 PyModule_AddIntConstant(m, "NETLINK_NFLOG", NETLINK_NFLOG);
4412 #endif
4413 #ifdef NETLINK_XFRM
4414 PyModule_AddIntConstant(m, "NETLINK_XFRM", NETLINK_XFRM);
4415 #endif
4416 #ifdef NETLINK_ARPD
4417 PyModule_AddIntConstant(m, "NETLINK_ARPD", NETLINK_ARPD);
4418 #endif
4419 #ifdef NETLINK_ROUTE6
4420 PyModule_AddIntConstant(m, "NETLINK_ROUTE6", NETLINK_ROUTE6);
4421 #endif
4422 PyModule_AddIntConstant(m, "NETLINK_IP6_FW", NETLINK_IP6_FW);
4423 #ifdef NETLINK_DNRTMSG
4424 PyModule_AddIntConstant(m, "NETLINK_DNRTMSG", NETLINK_DNRTMSG);
4425 #endif
4426 #ifdef NETLINK_TAPBASE
4427 PyModule_AddIntConstant(m, "NETLINK_TAPBASE", NETLINK_TAPBASE);
4428 #endif
4429 #endif /* AF_NETLINK */
4430 #ifdef AF_ROUTE
4431 /* Alias to emulate 4.4BSD */
4432 PyModule_AddIntConstant(m, "AF_ROUTE", AF_ROUTE);
4433 #endif
4434 #ifdef AF_ASH
4435 /* Ash */
4436 PyModule_AddIntConstant(m, "AF_ASH", AF_ASH);
4437 #endif
4438 #ifdef AF_ECONET
4439 /* Acorn Econet */
4440 PyModule_AddIntConstant(m, "AF_ECONET", AF_ECONET);
4441 #endif
4442 #ifdef AF_ATMSVC
4443 /* ATM SVCs */
4444 PyModule_AddIntConstant(m, "AF_ATMSVC", AF_ATMSVC);
4445 #endif
4446 #ifdef AF_SNA
4447 /* Linux SNA Project (nutters!) */
4448 PyModule_AddIntConstant(m, "AF_SNA", AF_SNA);
4449 #endif
4450 #ifdef AF_IRDA
4451 /* IRDA sockets */
4452 PyModule_AddIntConstant(m, "AF_IRDA", AF_IRDA);
4453 #endif
4454 #ifdef AF_PPPOX
4455 /* PPPoX sockets */
4456 PyModule_AddIntConstant(m, "AF_PPPOX", AF_PPPOX);
4457 #endif
4458 #ifdef AF_WANPIPE
4459 /* Wanpipe API Sockets */
4460 PyModule_AddIntConstant(m, "AF_WANPIPE", AF_WANPIPE);
4461 #endif
4462 #ifdef AF_LLC
4463 /* Linux LLC */
4464 PyModule_AddIntConstant(m, "AF_LLC", AF_LLC);
4465 #endif
4467 #ifdef USE_BLUETOOTH
4468 PyModule_AddIntConstant(m, "AF_BLUETOOTH", AF_BLUETOOTH);
4469 PyModule_AddIntConstant(m, "BTPROTO_L2CAP", BTPROTO_L2CAP);
4470 PyModule_AddIntConstant(m, "BTPROTO_HCI", BTPROTO_HCI);
4471 PyModule_AddIntConstant(m, "SOL_HCI", SOL_HCI);
4472 PyModule_AddIntConstant(m, "HCI_FILTER", HCI_FILTER);
4473 #if !defined(__FreeBSD__)
4474 PyModule_AddIntConstant(m, "HCI_TIME_STAMP", HCI_TIME_STAMP);
4475 PyModule_AddIntConstant(m, "HCI_DATA_DIR", HCI_DATA_DIR);
4476 PyModule_AddIntConstant(m, "BTPROTO_SCO", BTPROTO_SCO);
4477 #endif
4478 PyModule_AddIntConstant(m, "BTPROTO_RFCOMM", BTPROTO_RFCOMM);
4479 PyModule_AddStringConstant(m, "BDADDR_ANY", "00:00:00:00:00:00");
4480 PyModule_AddStringConstant(m, "BDADDR_LOCAL", "00:00:00:FF:FF:FF");
4481 #endif
4483 #ifdef HAVE_NETPACKET_PACKET_H
4484 PyModule_AddIntConstant(m, "AF_PACKET", AF_PACKET);
4485 PyModule_AddIntConstant(m, "PF_PACKET", PF_PACKET);
4486 PyModule_AddIntConstant(m, "PACKET_HOST", PACKET_HOST);
4487 PyModule_AddIntConstant(m, "PACKET_BROADCAST", PACKET_BROADCAST);
4488 PyModule_AddIntConstant(m, "PACKET_MULTICAST", PACKET_MULTICAST);
4489 PyModule_AddIntConstant(m, "PACKET_OTHERHOST", PACKET_OTHERHOST);
4490 PyModule_AddIntConstant(m, "PACKET_OUTGOING", PACKET_OUTGOING);
4491 PyModule_AddIntConstant(m, "PACKET_LOOPBACK", PACKET_LOOPBACK);
4492 PyModule_AddIntConstant(m, "PACKET_FASTROUTE", PACKET_FASTROUTE);
4493 #endif
4495 /* Socket types */
4496 PyModule_AddIntConstant(m, "SOCK_STREAM", SOCK_STREAM);
4497 PyModule_AddIntConstant(m, "SOCK_DGRAM", SOCK_DGRAM);
4498 #ifndef __BEOS__
4499 /* We have incomplete socket support. */
4500 PyModule_AddIntConstant(m, "SOCK_RAW", SOCK_RAW);
4501 PyModule_AddIntConstant(m, "SOCK_SEQPACKET", SOCK_SEQPACKET);
4502 #if defined(SOCK_RDM)
4503 PyModule_AddIntConstant(m, "SOCK_RDM", SOCK_RDM);
4504 #endif
4505 #endif
4507 #ifdef SO_DEBUG
4508 PyModule_AddIntConstant(m, "SO_DEBUG", SO_DEBUG);
4509 #endif
4510 #ifdef SO_ACCEPTCONN
4511 PyModule_AddIntConstant(m, "SO_ACCEPTCONN", SO_ACCEPTCONN);
4512 #endif
4513 #ifdef SO_REUSEADDR
4514 PyModule_AddIntConstant(m, "SO_REUSEADDR", SO_REUSEADDR);
4515 #endif
4516 #ifdef SO_EXCLUSIVEADDRUSE
4517 PyModule_AddIntConstant(m, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE);
4518 #endif
4520 #ifdef SO_KEEPALIVE
4521 PyModule_AddIntConstant(m, "SO_KEEPALIVE", SO_KEEPALIVE);
4522 #endif
4523 #ifdef SO_DONTROUTE
4524 PyModule_AddIntConstant(m, "SO_DONTROUTE", SO_DONTROUTE);
4525 #endif
4526 #ifdef SO_BROADCAST
4527 PyModule_AddIntConstant(m, "SO_BROADCAST", SO_BROADCAST);
4528 #endif
4529 #ifdef SO_USELOOPBACK
4530 PyModule_AddIntConstant(m, "SO_USELOOPBACK", SO_USELOOPBACK);
4531 #endif
4532 #ifdef SO_LINGER
4533 PyModule_AddIntConstant(m, "SO_LINGER", SO_LINGER);
4534 #endif
4535 #ifdef SO_OOBINLINE
4536 PyModule_AddIntConstant(m, "SO_OOBINLINE", SO_OOBINLINE);
4537 #endif
4538 #ifdef SO_REUSEPORT
4539 PyModule_AddIntConstant(m, "SO_REUSEPORT", SO_REUSEPORT);
4540 #endif
4541 #ifdef SO_SNDBUF
4542 PyModule_AddIntConstant(m, "SO_SNDBUF", SO_SNDBUF);
4543 #endif
4544 #ifdef SO_RCVBUF
4545 PyModule_AddIntConstant(m, "SO_RCVBUF", SO_RCVBUF);
4546 #endif
4547 #ifdef SO_SNDLOWAT
4548 PyModule_AddIntConstant(m, "SO_SNDLOWAT", SO_SNDLOWAT);
4549 #endif
4550 #ifdef SO_RCVLOWAT
4551 PyModule_AddIntConstant(m, "SO_RCVLOWAT", SO_RCVLOWAT);
4552 #endif
4553 #ifdef SO_SNDTIMEO
4554 PyModule_AddIntConstant(m, "SO_SNDTIMEO", SO_SNDTIMEO);
4555 #endif
4556 #ifdef SO_RCVTIMEO
4557 PyModule_AddIntConstant(m, "SO_RCVTIMEO", SO_RCVTIMEO);
4558 #endif
4559 #ifdef SO_ERROR
4560 PyModule_AddIntConstant(m, "SO_ERROR", SO_ERROR);
4561 #endif
4562 #ifdef SO_TYPE
4563 PyModule_AddIntConstant(m, "SO_TYPE", SO_TYPE);
4564 #endif
4566 /* Maximum number of connections for "listen" */
4567 #ifdef SOMAXCONN
4568 PyModule_AddIntConstant(m, "SOMAXCONN", SOMAXCONN);
4569 #else
4570 PyModule_AddIntConstant(m, "SOMAXCONN", 5); /* Common value */
4571 #endif
4573 /* Flags for send, recv */
4574 #ifdef MSG_OOB
4575 PyModule_AddIntConstant(m, "MSG_OOB", MSG_OOB);
4576 #endif
4577 #ifdef MSG_PEEK
4578 PyModule_AddIntConstant(m, "MSG_PEEK", MSG_PEEK);
4579 #endif
4580 #ifdef MSG_DONTROUTE
4581 PyModule_AddIntConstant(m, "MSG_DONTROUTE", MSG_DONTROUTE);
4582 #endif
4583 #ifdef MSG_DONTWAIT
4584 PyModule_AddIntConstant(m, "MSG_DONTWAIT", MSG_DONTWAIT);
4585 #endif
4586 #ifdef MSG_EOR
4587 PyModule_AddIntConstant(m, "MSG_EOR", MSG_EOR);
4588 #endif
4589 #ifdef MSG_TRUNC
4590 PyModule_AddIntConstant(m, "MSG_TRUNC", MSG_TRUNC);
4591 #endif
4592 #ifdef MSG_CTRUNC
4593 PyModule_AddIntConstant(m, "MSG_CTRUNC", MSG_CTRUNC);
4594 #endif
4595 #ifdef MSG_WAITALL
4596 PyModule_AddIntConstant(m, "MSG_WAITALL", MSG_WAITALL);
4597 #endif
4598 #ifdef MSG_BTAG
4599 PyModule_AddIntConstant(m, "MSG_BTAG", MSG_BTAG);
4600 #endif
4601 #ifdef MSG_ETAG
4602 PyModule_AddIntConstant(m, "MSG_ETAG", MSG_ETAG);
4603 #endif
4605 /* Protocol level and numbers, usable for [gs]etsockopt */
4606 #ifdef SOL_SOCKET
4607 PyModule_AddIntConstant(m, "SOL_SOCKET", SOL_SOCKET);
4608 #endif
4609 #ifdef SOL_IP
4610 PyModule_AddIntConstant(m, "SOL_IP", SOL_IP);
4611 #else
4612 PyModule_AddIntConstant(m, "SOL_IP", 0);
4613 #endif
4614 #ifdef SOL_IPX
4615 PyModule_AddIntConstant(m, "SOL_IPX", SOL_IPX);
4616 #endif
4617 #ifdef SOL_AX25
4618 PyModule_AddIntConstant(m, "SOL_AX25", SOL_AX25);
4619 #endif
4620 #ifdef SOL_ATALK
4621 PyModule_AddIntConstant(m, "SOL_ATALK", SOL_ATALK);
4622 #endif
4623 #ifdef SOL_NETROM
4624 PyModule_AddIntConstant(m, "SOL_NETROM", SOL_NETROM);
4625 #endif
4626 #ifdef SOL_ROSE
4627 PyModule_AddIntConstant(m, "SOL_ROSE", SOL_ROSE);
4628 #endif
4629 #ifdef SOL_TCP
4630 PyModule_AddIntConstant(m, "SOL_TCP", SOL_TCP);
4631 #else
4632 PyModule_AddIntConstant(m, "SOL_TCP", 6);
4633 #endif
4634 #ifdef SOL_UDP
4635 PyModule_AddIntConstant(m, "SOL_UDP", SOL_UDP);
4636 #else
4637 PyModule_AddIntConstant(m, "SOL_UDP", 17);
4638 #endif
4639 #ifdef IPPROTO_IP
4640 PyModule_AddIntConstant(m, "IPPROTO_IP", IPPROTO_IP);
4641 #else
4642 PyModule_AddIntConstant(m, "IPPROTO_IP", 0);
4643 #endif
4644 #ifdef IPPROTO_HOPOPTS
4645 PyModule_AddIntConstant(m, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS);
4646 #endif
4647 #ifdef IPPROTO_ICMP
4648 PyModule_AddIntConstant(m, "IPPROTO_ICMP", IPPROTO_ICMP);
4649 #else
4650 PyModule_AddIntConstant(m, "IPPROTO_ICMP", 1);
4651 #endif
4652 #ifdef IPPROTO_IGMP
4653 PyModule_AddIntConstant(m, "IPPROTO_IGMP", IPPROTO_IGMP);
4654 #endif
4655 #ifdef IPPROTO_GGP
4656 PyModule_AddIntConstant(m, "IPPROTO_GGP", IPPROTO_GGP);
4657 #endif
4658 #ifdef IPPROTO_IPV4
4659 PyModule_AddIntConstant(m, "IPPROTO_IPV4", IPPROTO_IPV4);
4660 #endif
4661 #ifdef IPPROTO_IPV6
4662 PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
4663 #endif
4664 #ifdef IPPROTO_IPIP
4665 PyModule_AddIntConstant(m, "IPPROTO_IPIP", IPPROTO_IPIP);
4666 #endif
4667 #ifdef IPPROTO_TCP
4668 PyModule_AddIntConstant(m, "IPPROTO_TCP", IPPROTO_TCP);
4669 #else
4670 PyModule_AddIntConstant(m, "IPPROTO_TCP", 6);
4671 #endif
4672 #ifdef IPPROTO_EGP
4673 PyModule_AddIntConstant(m, "IPPROTO_EGP", IPPROTO_EGP);
4674 #endif
4675 #ifdef IPPROTO_PUP
4676 PyModule_AddIntConstant(m, "IPPROTO_PUP", IPPROTO_PUP);
4677 #endif
4678 #ifdef IPPROTO_UDP
4679 PyModule_AddIntConstant(m, "IPPROTO_UDP", IPPROTO_UDP);
4680 #else
4681 PyModule_AddIntConstant(m, "IPPROTO_UDP", 17);
4682 #endif
4683 #ifdef IPPROTO_IDP
4684 PyModule_AddIntConstant(m, "IPPROTO_IDP", IPPROTO_IDP);
4685 #endif
4686 #ifdef IPPROTO_HELLO
4687 PyModule_AddIntConstant(m, "IPPROTO_HELLO", IPPROTO_HELLO);
4688 #endif
4689 #ifdef IPPROTO_ND
4690 PyModule_AddIntConstant(m, "IPPROTO_ND", IPPROTO_ND);
4691 #endif
4692 #ifdef IPPROTO_TP
4693 PyModule_AddIntConstant(m, "IPPROTO_TP", IPPROTO_TP);
4694 #endif
4695 #ifdef IPPROTO_IPV6
4696 PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
4697 #endif
4698 #ifdef IPPROTO_ROUTING
4699 PyModule_AddIntConstant(m, "IPPROTO_ROUTING", IPPROTO_ROUTING);
4700 #endif
4701 #ifdef IPPROTO_FRAGMENT
4702 PyModule_AddIntConstant(m, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT);
4703 #endif
4704 #ifdef IPPROTO_RSVP
4705 PyModule_AddIntConstant(m, "IPPROTO_RSVP", IPPROTO_RSVP);
4706 #endif
4707 #ifdef IPPROTO_GRE
4708 PyModule_AddIntConstant(m, "IPPROTO_GRE", IPPROTO_GRE);
4709 #endif
4710 #ifdef IPPROTO_ESP
4711 PyModule_AddIntConstant(m, "IPPROTO_ESP", IPPROTO_ESP);
4712 #endif
4713 #ifdef IPPROTO_AH
4714 PyModule_AddIntConstant(m, "IPPROTO_AH", IPPROTO_AH);
4715 #endif
4716 #ifdef IPPROTO_MOBILE
4717 PyModule_AddIntConstant(m, "IPPROTO_MOBILE", IPPROTO_MOBILE);
4718 #endif
4719 #ifdef IPPROTO_ICMPV6
4720 PyModule_AddIntConstant(m, "IPPROTO_ICMPV6", IPPROTO_ICMPV6);
4721 #endif
4722 #ifdef IPPROTO_NONE
4723 PyModule_AddIntConstant(m, "IPPROTO_NONE", IPPROTO_NONE);
4724 #endif
4725 #ifdef IPPROTO_DSTOPTS
4726 PyModule_AddIntConstant(m, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS);
4727 #endif
4728 #ifdef IPPROTO_XTP
4729 PyModule_AddIntConstant(m, "IPPROTO_XTP", IPPROTO_XTP);
4730 #endif
4731 #ifdef IPPROTO_EON
4732 PyModule_AddIntConstant(m, "IPPROTO_EON", IPPROTO_EON);
4733 #endif
4734 #ifdef IPPROTO_PIM
4735 PyModule_AddIntConstant(m, "IPPROTO_PIM", IPPROTO_PIM);
4736 #endif
4737 #ifdef IPPROTO_IPCOMP
4738 PyModule_AddIntConstant(m, "IPPROTO_IPCOMP", IPPROTO_IPCOMP);
4739 #endif
4740 #ifdef IPPROTO_VRRP
4741 PyModule_AddIntConstant(m, "IPPROTO_VRRP", IPPROTO_VRRP);
4742 #endif
4743 #ifdef IPPROTO_BIP
4744 PyModule_AddIntConstant(m, "IPPROTO_BIP", IPPROTO_BIP);
4745 #endif
4746 /**/
4747 #ifdef IPPROTO_RAW
4748 PyModule_AddIntConstant(m, "IPPROTO_RAW", IPPROTO_RAW);
4749 #else
4750 PyModule_AddIntConstant(m, "IPPROTO_RAW", 255);
4751 #endif
4752 #ifdef IPPROTO_MAX
4753 PyModule_AddIntConstant(m, "IPPROTO_MAX", IPPROTO_MAX);
4754 #endif
4756 /* Some port configuration */
4757 #ifdef IPPORT_RESERVED
4758 PyModule_AddIntConstant(m, "IPPORT_RESERVED", IPPORT_RESERVED);
4759 #else
4760 PyModule_AddIntConstant(m, "IPPORT_RESERVED", 1024);
4761 #endif
4762 #ifdef IPPORT_USERRESERVED
4763 PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", IPPORT_USERRESERVED);
4764 #else
4765 PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", 5000);
4766 #endif
4768 /* Some reserved IP v.4 addresses */
4769 #ifdef INADDR_ANY
4770 PyModule_AddIntConstant(m, "INADDR_ANY", INADDR_ANY);
4771 #else
4772 PyModule_AddIntConstant(m, "INADDR_ANY", 0x00000000);
4773 #endif
4774 #ifdef INADDR_BROADCAST
4775 PyModule_AddIntConstant(m, "INADDR_BROADCAST", INADDR_BROADCAST);
4776 #else
4777 PyModule_AddIntConstant(m, "INADDR_BROADCAST", 0xffffffff);
4778 #endif
4779 #ifdef INADDR_LOOPBACK
4780 PyModule_AddIntConstant(m, "INADDR_LOOPBACK", INADDR_LOOPBACK);
4781 #else
4782 PyModule_AddIntConstant(m, "INADDR_LOOPBACK", 0x7F000001);
4783 #endif
4784 #ifdef INADDR_UNSPEC_GROUP
4785 PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
4786 #else
4787 PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", 0xe0000000);
4788 #endif
4789 #ifdef INADDR_ALLHOSTS_GROUP
4790 PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP",
4791 INADDR_ALLHOSTS_GROUP);
4792 #else
4793 PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
4794 #endif
4795 #ifdef INADDR_MAX_LOCAL_GROUP
4796 PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP",
4797 INADDR_MAX_LOCAL_GROUP);
4798 #else
4799 PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
4800 #endif
4801 #ifdef INADDR_NONE
4802 PyModule_AddIntConstant(m, "INADDR_NONE", INADDR_NONE);
4803 #else
4804 PyModule_AddIntConstant(m, "INADDR_NONE", 0xffffffff);
4805 #endif
4807 /* IPv4 [gs]etsockopt options */
4808 #ifdef IP_OPTIONS
4809 PyModule_AddIntConstant(m, "IP_OPTIONS", IP_OPTIONS);
4810 #endif
4811 #ifdef IP_HDRINCL
4812 PyModule_AddIntConstant(m, "IP_HDRINCL", IP_HDRINCL);
4813 #endif
4814 #ifdef IP_TOS
4815 PyModule_AddIntConstant(m, "IP_TOS", IP_TOS);
4816 #endif
4817 #ifdef IP_TTL
4818 PyModule_AddIntConstant(m, "IP_TTL", IP_TTL);
4819 #endif
4820 #ifdef IP_RECVOPTS
4821 PyModule_AddIntConstant(m, "IP_RECVOPTS", IP_RECVOPTS);
4822 #endif
4823 #ifdef IP_RECVRETOPTS
4824 PyModule_AddIntConstant(m, "IP_RECVRETOPTS", IP_RECVRETOPTS);
4825 #endif
4826 #ifdef IP_RECVDSTADDR
4827 PyModule_AddIntConstant(m, "IP_RECVDSTADDR", IP_RECVDSTADDR);
4828 #endif
4829 #ifdef IP_RETOPTS
4830 PyModule_AddIntConstant(m, "IP_RETOPTS", IP_RETOPTS);
4831 #endif
4832 #ifdef IP_MULTICAST_IF
4833 PyModule_AddIntConstant(m, "IP_MULTICAST_IF", IP_MULTICAST_IF);
4834 #endif
4835 #ifdef IP_MULTICAST_TTL
4836 PyModule_AddIntConstant(m, "IP_MULTICAST_TTL", IP_MULTICAST_TTL);
4837 #endif
4838 #ifdef IP_MULTICAST_LOOP
4839 PyModule_AddIntConstant(m, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
4840 #endif
4841 #ifdef IP_ADD_MEMBERSHIP
4842 PyModule_AddIntConstant(m, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
4843 #endif
4844 #ifdef IP_DROP_MEMBERSHIP
4845 PyModule_AddIntConstant(m, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
4846 #endif
4847 #ifdef IP_DEFAULT_MULTICAST_TTL
4848 PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_TTL",
4849 IP_DEFAULT_MULTICAST_TTL);
4850 #endif
4851 #ifdef IP_DEFAULT_MULTICAST_LOOP
4852 PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_LOOP",
4853 IP_DEFAULT_MULTICAST_LOOP);
4854 #endif
4855 #ifdef IP_MAX_MEMBERSHIPS
4856 PyModule_AddIntConstant(m, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS);
4857 #endif
4859 /* IPv6 [gs]etsockopt options, defined in RFC2553 */
4860 #ifdef IPV6_JOIN_GROUP
4861 PyModule_AddIntConstant(m, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP);
4862 #endif
4863 #ifdef IPV6_LEAVE_GROUP
4864 PyModule_AddIntConstant(m, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP);
4865 #endif
4866 #ifdef IPV6_MULTICAST_HOPS
4867 PyModule_AddIntConstant(m, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS);
4868 #endif
4869 #ifdef IPV6_MULTICAST_IF
4870 PyModule_AddIntConstant(m, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF);
4871 #endif
4872 #ifdef IPV6_MULTICAST_LOOP
4873 PyModule_AddIntConstant(m, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP);
4874 #endif
4875 #ifdef IPV6_UNICAST_HOPS
4876 PyModule_AddIntConstant(m, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS);
4877 #endif
4878 /* Additional IPV6 socket options, defined in RFC 3493 */
4879 #ifdef IPV6_V6ONLY
4880 PyModule_AddIntConstant(m, "IPV6_V6ONLY", IPV6_V6ONLY);
4881 #endif
4882 /* Advanced IPV6 socket options, from RFC 3542 */
4883 #ifdef IPV6_CHECKSUM
4884 PyModule_AddIntConstant(m, "IPV6_CHECKSUM", IPV6_CHECKSUM);
4885 #endif
4886 #ifdef IPV6_DONTFRAG
4887 PyModule_AddIntConstant(m, "IPV6_DONTFRAG", IPV6_DONTFRAG);
4888 #endif
4889 #ifdef IPV6_DSTOPTS
4890 PyModule_AddIntConstant(m, "IPV6_DSTOPTS", IPV6_DSTOPTS);
4891 #endif
4892 #ifdef IPV6_HOPLIMIT
4893 PyModule_AddIntConstant(m, "IPV6_HOPLIMIT", IPV6_HOPLIMIT);
4894 #endif
4895 #ifdef IPV6_HOPOPTS
4896 PyModule_AddIntConstant(m, "IPV6_HOPOPTS", IPV6_HOPOPTS);
4897 #endif
4898 #ifdef IPV6_NEXTHOP
4899 PyModule_AddIntConstant(m, "IPV6_NEXTHOP", IPV6_NEXTHOP);
4900 #endif
4901 #ifdef IPV6_PATHMTU
4902 PyModule_AddIntConstant(m, "IPV6_PATHMTU", IPV6_PATHMTU);
4903 #endif
4904 #ifdef IPV6_PKTINFO
4905 PyModule_AddIntConstant(m, "IPV6_PKTINFO", IPV6_PKTINFO);
4906 #endif
4907 #ifdef IPV6_RECVDSTOPTS
4908 PyModule_AddIntConstant(m, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS);
4909 #endif
4910 #ifdef IPV6_RECVHOPLIMIT
4911 PyModule_AddIntConstant(m, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT);
4912 #endif
4913 #ifdef IPV6_RECVHOPOPTS
4914 PyModule_AddIntConstant(m, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS);
4915 #endif
4916 #ifdef IPV6_RECVPKTINFO
4917 PyModule_AddIntConstant(m, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO);
4918 #endif
4919 #ifdef IPV6_RECVRTHDR
4920 PyModule_AddIntConstant(m, "IPV6_RECVRTHDR", IPV6_RECVRTHDR);
4921 #endif
4922 #ifdef IPV6_RECVTCLASS
4923 PyModule_AddIntConstant(m, "IPV6_RECVTCLASS", IPV6_RECVTCLASS);
4924 #endif
4925 #ifdef IPV6_RTHDR
4926 PyModule_AddIntConstant(m, "IPV6_RTHDR", IPV6_RTHDR);
4927 #endif
4928 #ifdef IPV6_RTHDRDSTOPTS
4929 PyModule_AddIntConstant(m, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS);
4930 #endif
4931 #ifdef IPV6_RTHDR_TYPE_0
4932 PyModule_AddIntConstant(m, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0);
4933 #endif
4934 #ifdef IPV6_RECVPATHMTU
4935 PyModule_AddIntConstant(m, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU);
4936 #endif
4937 #ifdef IPV6_TCLASS
4938 PyModule_AddIntConstant(m, "IPV6_TCLASS", IPV6_TCLASS);
4939 #endif
4940 #ifdef IPV6_USE_MIN_MTU
4941 PyModule_AddIntConstant(m, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU);
4942 #endif
4944 /* TCP options */
4945 #ifdef TCP_NODELAY
4946 PyModule_AddIntConstant(m, "TCP_NODELAY", TCP_NODELAY);
4947 #endif
4948 #ifdef TCP_MAXSEG
4949 PyModule_AddIntConstant(m, "TCP_MAXSEG", TCP_MAXSEG);
4950 #endif
4951 #ifdef TCP_CORK
4952 PyModule_AddIntConstant(m, "TCP_CORK", TCP_CORK);
4953 #endif
4954 #ifdef TCP_KEEPIDLE
4955 PyModule_AddIntConstant(m, "TCP_KEEPIDLE", TCP_KEEPIDLE);
4956 #endif
4957 #ifdef TCP_KEEPINTVL
4958 PyModule_AddIntConstant(m, "TCP_KEEPINTVL", TCP_KEEPINTVL);
4959 #endif
4960 #ifdef TCP_KEEPCNT
4961 PyModule_AddIntConstant(m, "TCP_KEEPCNT", TCP_KEEPCNT);
4962 #endif
4963 #ifdef TCP_SYNCNT
4964 PyModule_AddIntConstant(m, "TCP_SYNCNT", TCP_SYNCNT);
4965 #endif
4966 #ifdef TCP_LINGER2
4967 PyModule_AddIntConstant(m, "TCP_LINGER2", TCP_LINGER2);
4968 #endif
4969 #ifdef TCP_DEFER_ACCEPT
4970 PyModule_AddIntConstant(m, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT);
4971 #endif
4972 #ifdef TCP_WINDOW_CLAMP
4973 PyModule_AddIntConstant(m, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP);
4974 #endif
4975 #ifdef TCP_INFO
4976 PyModule_AddIntConstant(m, "TCP_INFO", TCP_INFO);
4977 #endif
4978 #ifdef TCP_QUICKACK
4979 PyModule_AddIntConstant(m, "TCP_QUICKACK", TCP_QUICKACK);
4980 #endif
4983 /* IPX options */
4984 #ifdef IPX_TYPE
4985 PyModule_AddIntConstant(m, "IPX_TYPE", IPX_TYPE);
4986 #endif
4988 /* get{addr,name}info parameters */
4989 #ifdef EAI_ADDRFAMILY
4990 PyModule_AddIntConstant(m, "EAI_ADDRFAMILY", EAI_ADDRFAMILY);
4991 #endif
4992 #ifdef EAI_AGAIN
4993 PyModule_AddIntConstant(m, "EAI_AGAIN", EAI_AGAIN);
4994 #endif
4995 #ifdef EAI_BADFLAGS
4996 PyModule_AddIntConstant(m, "EAI_BADFLAGS", EAI_BADFLAGS);
4997 #endif
4998 #ifdef EAI_FAIL
4999 PyModule_AddIntConstant(m, "EAI_FAIL", EAI_FAIL);
5000 #endif
5001 #ifdef EAI_FAMILY
5002 PyModule_AddIntConstant(m, "EAI_FAMILY", EAI_FAMILY);
5003 #endif
5004 #ifdef EAI_MEMORY
5005 PyModule_AddIntConstant(m, "EAI_MEMORY", EAI_MEMORY);
5006 #endif
5007 #ifdef EAI_NODATA
5008 PyModule_AddIntConstant(m, "EAI_NODATA", EAI_NODATA);
5009 #endif
5010 #ifdef EAI_NONAME
5011 PyModule_AddIntConstant(m, "EAI_NONAME", EAI_NONAME);
5012 #endif
5013 #ifdef EAI_OVERFLOW
5014 PyModule_AddIntConstant(m, "EAI_OVERFLOW", EAI_OVERFLOW);
5015 #endif
5016 #ifdef EAI_SERVICE
5017 PyModule_AddIntConstant(m, "EAI_SERVICE", EAI_SERVICE);
5018 #endif
5019 #ifdef EAI_SOCKTYPE
5020 PyModule_AddIntConstant(m, "EAI_SOCKTYPE", EAI_SOCKTYPE);
5021 #endif
5022 #ifdef EAI_SYSTEM
5023 PyModule_AddIntConstant(m, "EAI_SYSTEM", EAI_SYSTEM);
5024 #endif
5025 #ifdef EAI_BADHINTS
5026 PyModule_AddIntConstant(m, "EAI_BADHINTS", EAI_BADHINTS);
5027 #endif
5028 #ifdef EAI_PROTOCOL
5029 PyModule_AddIntConstant(m, "EAI_PROTOCOL", EAI_PROTOCOL);
5030 #endif
5031 #ifdef EAI_MAX
5032 PyModule_AddIntConstant(m, "EAI_MAX", EAI_MAX);
5033 #endif
5034 #ifdef AI_PASSIVE
5035 PyModule_AddIntConstant(m, "AI_PASSIVE", AI_PASSIVE);
5036 #endif
5037 #ifdef AI_CANONNAME
5038 PyModule_AddIntConstant(m, "AI_CANONNAME", AI_CANONNAME);
5039 #endif
5040 #ifdef AI_NUMERICHOST
5041 PyModule_AddIntConstant(m, "AI_NUMERICHOST", AI_NUMERICHOST);
5042 #endif
5043 #ifdef AI_NUMERICSERV
5044 PyModule_AddIntConstant(m, "AI_NUMERICSERV", AI_NUMERICSERV);
5045 #endif
5046 #ifdef AI_MASK
5047 PyModule_AddIntConstant(m, "AI_MASK", AI_MASK);
5048 #endif
5049 #ifdef AI_ALL
5050 PyModule_AddIntConstant(m, "AI_ALL", AI_ALL);
5051 #endif
5052 #ifdef AI_V4MAPPED_CFG
5053 PyModule_AddIntConstant(m, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG);
5054 #endif
5055 #ifdef AI_ADDRCONFIG
5056 PyModule_AddIntConstant(m, "AI_ADDRCONFIG", AI_ADDRCONFIG);
5057 #endif
5058 #ifdef AI_V4MAPPED
5059 PyModule_AddIntConstant(m, "AI_V4MAPPED", AI_V4MAPPED);
5060 #endif
5061 #ifdef AI_DEFAULT
5062 PyModule_AddIntConstant(m, "AI_DEFAULT", AI_DEFAULT);
5063 #endif
5064 #ifdef NI_MAXHOST
5065 PyModule_AddIntConstant(m, "NI_MAXHOST", NI_MAXHOST);
5066 #endif
5067 #ifdef NI_MAXSERV
5068 PyModule_AddIntConstant(m, "NI_MAXSERV", NI_MAXSERV);
5069 #endif
5070 #ifdef NI_NOFQDN
5071 PyModule_AddIntConstant(m, "NI_NOFQDN", NI_NOFQDN);
5072 #endif
5073 #ifdef NI_NUMERICHOST
5074 PyModule_AddIntConstant(m, "NI_NUMERICHOST", NI_NUMERICHOST);
5075 #endif
5076 #ifdef NI_NAMEREQD
5077 PyModule_AddIntConstant(m, "NI_NAMEREQD", NI_NAMEREQD);
5078 #endif
5079 #ifdef NI_NUMERICSERV
5080 PyModule_AddIntConstant(m, "NI_NUMERICSERV", NI_NUMERICSERV);
5081 #endif
5082 #ifdef NI_DGRAM
5083 PyModule_AddIntConstant(m, "NI_DGRAM", NI_DGRAM);
5084 #endif
5086 /* shutdown() parameters */
5087 #ifdef SHUT_RD
5088 PyModule_AddIntConstant(m, "SHUT_RD", SHUT_RD);
5089 #elif defined(SD_RECEIVE)
5090 PyModule_AddIntConstant(m, "SHUT_RD", SD_RECEIVE);
5091 #else
5092 PyModule_AddIntConstant(m, "SHUT_RD", 0);
5093 #endif
5094 #ifdef SHUT_WR
5095 PyModule_AddIntConstant(m, "SHUT_WR", SHUT_WR);
5096 #elif defined(SD_SEND)
5097 PyModule_AddIntConstant(m, "SHUT_WR", SD_SEND);
5098 #else
5099 PyModule_AddIntConstant(m, "SHUT_WR", 1);
5100 #endif
5101 #ifdef SHUT_RDWR
5102 PyModule_AddIntConstant(m, "SHUT_RDWR", SHUT_RDWR);
5103 #elif defined(SD_BOTH)
5104 PyModule_AddIntConstant(m, "SHUT_RDWR", SD_BOTH);
5105 #else
5106 PyModule_AddIntConstant(m, "SHUT_RDWR", 2);
5107 #endif
5109 /* Initialize gethostbyname lock */
5110 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
5111 netdb_lock = PyThread_allocate_lock();
5112 #endif
5116 #ifndef HAVE_INET_PTON
5118 /* Simplistic emulation code for inet_pton that only works for IPv4 */
5119 /* These are not exposed because they do not set errno properly */
5122 inet_pton(int af, const char *src, void *dst)
5124 if (af == AF_INET) {
5125 long packed_addr;
5126 packed_addr = inet_addr(src);
5127 if (packed_addr == INADDR_NONE)
5128 return 0;
5129 memcpy(dst, &packed_addr, 4);
5130 return 1;
5132 /* Should set errno to EAFNOSUPPORT */
5133 return -1;
5136 const char *
5137 inet_ntop(int af, const void *src, char *dst, socklen_t size)
5139 if (af == AF_INET) {
5140 struct in_addr packed_addr;
5141 if (size < 16)
5142 /* Should set errno to ENOSPC. */
5143 return NULL;
5144 memcpy(&packed_addr, src, sizeof(packed_addr));
5145 return strncpy(dst, inet_ntoa(packed_addr), size);
5147 /* Should set errno to EAFNOSUPPORT */
5148 return NULL;
5151 #endif