Fixed bug in time-to-midnight calculation.
[python.git] / Modules / socketmodule.c
blobb88703c7dadd8a938819e5f9bc8f0893d34c8259
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 #include "Python.h"
66 #undef MAX
67 #define MAX(x, y) ((x) < (y) ? (y) : (x))
69 /* Socket object documentation */
70 PyDoc_STRVAR(sock_doc,
71 "socket([family[, type[, proto]]]) -> socket object\n\
72 \n\
73 Open a socket of the given type. The family argument specifies the\n\
74 address family; it defaults to AF_INET. The type argument specifies\n\
75 whether this is a stream (SOCK_STREAM, this is the default)\n\
76 or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0,\n\
77 specifying the default protocol. Keyword arguments are accepted.\n\
78 \n\
79 A socket object represents one endpoint of a network connection.\n\
80 \n\
81 Methods of socket objects (keyword arguments not allowed):\n\
82 \n\
83 accept() -- accept a connection, returning new socket and client address\n\
84 bind(addr) -- bind the socket to a local address\n\
85 close() -- close the socket\n\
86 connect(addr) -- connect the socket to a remote address\n\
87 connect_ex(addr) -- connect, return an error code instead of an exception\n\
88 dup() -- return a new socket object identical to the current one [*]\n\
89 fileno() -- return underlying file descriptor\n\
90 getpeername() -- return remote address [*]\n\
91 getsockname() -- return local address\n\
92 getsockopt(level, optname[, buflen]) -- get socket options\n\
93 gettimeout() -- return timeout or None\n\
94 listen(n) -- start listening for incoming connections\n\
95 makefile([mode, [bufsize]]) -- return a file object for the socket [*]\n\
96 recv(buflen[, flags]) -- receive data\n\
97 recvfrom(buflen[, flags]) -- receive data and sender's address\n\
98 sendall(data[, flags]) -- send all data\n\
99 send(data[, flags]) -- send data, may not send all of it\n\
100 sendto(data[, flags], addr) -- send data to a given address\n\
101 setblocking(0 | 1) -- set or clear the blocking I/O flag\n\
102 setsockopt(level, optname, value) -- set socket options\n\
103 settimeout(None | float) -- set or clear the timeout\n\
104 shutdown(how) -- shut down traffic in one or both directions\n\
106 [*] not available on all platforms!");
108 /* XXX This is a terrible mess of platform-dependent preprocessor hacks.
109 I hope some day someone can clean this up please... */
111 /* Hacks for gethostbyname_r(). On some non-Linux platforms, the configure
112 script doesn't get this right, so we hardcode some platform checks below.
113 On the other hand, not all Linux versions agree, so there the settings
114 computed by the configure script are needed! */
116 #ifndef linux
117 # undef HAVE_GETHOSTBYNAME_R_3_ARG
118 # undef HAVE_GETHOSTBYNAME_R_5_ARG
119 # undef HAVE_GETHOSTBYNAME_R_6_ARG
120 #endif
122 #ifndef WITH_THREAD
123 # undef HAVE_GETHOSTBYNAME_R
124 #endif
126 #ifdef HAVE_GETHOSTBYNAME_R
127 # if defined(_AIX) || defined(__osf__)
128 # define HAVE_GETHOSTBYNAME_R_3_ARG
129 # elif defined(__sun) || defined(__sgi)
130 # define HAVE_GETHOSTBYNAME_R_5_ARG
131 # elif defined(linux)
132 /* Rely on the configure script */
133 # else
134 # undef HAVE_GETHOSTBYNAME_R
135 # endif
136 #endif
138 #if !defined(HAVE_GETHOSTBYNAME_R) && defined(WITH_THREAD) && \
139 !defined(MS_WINDOWS)
140 # define USE_GETHOSTBYNAME_LOCK
141 #endif
143 /* To use __FreeBSD_version */
144 #ifdef HAVE_SYS_PARAM_H
145 #include <sys/param.h>
146 #endif
147 /* On systems on which getaddrinfo() is believed to not be thread-safe,
148 (this includes the getaddrinfo emulation) protect access with a lock. */
149 #if defined(WITH_THREAD) && (defined(__APPLE__) || \
150 (defined(__FreeBSD__) && __FreeBSD_version+0 < 503000) || \
151 defined(__OpenBSD__) || defined(__NetBSD__) || !defined(HAVE_GETADDRINFO))
152 #define USE_GETADDRINFO_LOCK
153 #endif
155 #ifdef USE_GETADDRINFO_LOCK
156 #define ACQUIRE_GETADDRINFO_LOCK PyThread_acquire_lock(netdb_lock, 1);
157 #define RELEASE_GETADDRINFO_LOCK PyThread_release_lock(netdb_lock);
158 #else
159 #define ACQUIRE_GETADDRINFO_LOCK
160 #define RELEASE_GETADDRINFO_LOCK
161 #endif
163 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
164 # include "pythread.h"
165 #endif
167 #if defined(PYCC_VACPP)
168 # include <types.h>
169 # include <io.h>
170 # include <sys/ioctl.h>
171 # include <utils.h>
172 # include <ctype.h>
173 #endif
175 #if defined(__VMS)
176 #if ! defined(_SOCKADDR_LEN)
177 # ifdef getaddrinfo
178 # undef getaddrinfo
179 # endif
180 # include "TCPIP_IOCTL_ROUTINE"
181 #else
182 # include <ioctl.h>
183 #endif
184 #endif
186 #if defined(PYOS_OS2)
187 # define INCL_DOS
188 # define INCL_DOSERRORS
189 # define INCL_NOPMAPI
190 # include <os2.h>
191 #endif
193 #if defined(__sgi) && _COMPILER_VERSION>700 && !_SGIAPI
194 /* make sure that the reentrant (gethostbyaddr_r etc)
195 functions are declared correctly if compiling with
196 MIPSPro 7.x in ANSI C mode (default) */
198 /* XXX Using _SGIAPI is the wrong thing,
199 but I don't know what the right thing is. */
200 #undef _SGIAPI /* to avoid warning */
201 #define _SGIAPI 1
203 #undef _XOPEN_SOURCE
204 #include <sys/socket.h>
205 #include <sys/types.h>
206 #include <netinet/in.h>
207 #ifdef _SS_ALIGNSIZE
208 #define HAVE_GETADDRINFO 1
209 #define HAVE_GETNAMEINFO 1
210 #endif
212 #define HAVE_INET_PTON
213 #include <netdb.h>
214 #endif
216 /* Irix 6.5 fails to define this variable at all. This is needed
217 for both GCC and SGI's compiler. I'd say that the SGI headers
218 are just busted. */
219 #if defined(__sgi) && !defined(INET_ADDRSTRLEN)
220 #define INET_ADDRSTRLEN 16
221 #endif
223 /* Generic includes */
224 #include <sys/types.h>
226 /* Generic socket object definitions and includes */
227 #define PySocket_BUILDING_SOCKET
228 #include "socketmodule.h"
230 /* Addressing includes */
232 #ifndef MS_WINDOWS
234 /* Non-MS WINDOWS includes */
235 # include <netdb.h>
237 /* Headers needed for inet_ntoa() and inet_addr() */
238 # ifdef __BEOS__
239 # include <net/netdb.h>
240 # elif defined(PYOS_OS2) && defined(PYCC_VACPP)
241 # include <netdb.h>
242 typedef size_t socklen_t;
243 # else
244 # include <arpa/inet.h>
245 # endif
247 # ifndef RISCOS
248 # include <fcntl.h>
249 # else
250 # include <sys/ioctl.h>
251 # include <socklib.h>
252 # define NO_DUP
253 int h_errno; /* not used */
254 # define INET_ADDRSTRLEN 16
255 # endif
257 #else
259 /* MS_WINDOWS includes */
260 # include <fcntl.h>
262 #endif
264 #include <stddef.h>
266 #ifndef offsetof
267 # define offsetof(type, member) ((size_t)(&((type *)0)->member))
268 #endif
270 #ifndef O_NONBLOCK
271 # define O_NONBLOCK O_NDELAY
272 #endif
274 /* include Python's addrinfo.h unless it causes trouble */
275 #if defined(__sgi) && _COMPILER_VERSION>700 && defined(_SS_ALIGNSIZE)
276 /* Do not include addinfo.h on some newer IRIX versions.
277 * _SS_ALIGNSIZE is defined in sys/socket.h by 6.5.21,
278 * for example, but not by 6.5.10.
280 #elif defined(_MSC_VER) && _MSC_VER>1200
281 /* Do not include addrinfo.h for MSVC7 or greater. 'addrinfo' and
282 * EAI_* constants are defined in (the already included) ws2tcpip.h.
284 #else
285 # include "addrinfo.h"
286 #endif
288 #ifndef HAVE_INET_PTON
289 int inet_pton(int af, const char *src, void *dst);
290 const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
291 #endif
293 #ifdef __APPLE__
294 /* On OS X, getaddrinfo returns no error indication of lookup
295 failure, so we must use the emulation instead of the libinfo
296 implementation. Unfortunately, performing an autoconf test
297 for this bug would require DNS access for the machine performing
298 the configuration, which is not acceptable. Therefore, we
299 determine the bug just by checking for __APPLE__. If this bug
300 gets ever fixed, perhaps checking for sys/version.h would be
301 appropriate, which is 10/0 on the system with the bug. */
302 #ifndef HAVE_GETNAMEINFO
303 /* This bug seems to be fixed in Jaguar. Ths easiest way I could
304 Find to check for Jaguar is that it has getnameinfo(), which
305 older releases don't have */
306 #undef HAVE_GETADDRINFO
307 #endif
308 #endif
310 /* I know this is a bad practice, but it is the easiest... */
311 #if !defined(HAVE_GETADDRINFO)
312 /* avoid clashes with the C library definition of the symbol. */
313 #define getaddrinfo fake_getaddrinfo
314 #define gai_strerror fake_gai_strerror
315 #define freeaddrinfo fake_freeaddrinfo
316 #include "getaddrinfo.c"
317 #endif
318 #if !defined(HAVE_GETNAMEINFO)
319 #define getnameinfo fake_getnameinfo
320 #include "getnameinfo.c"
321 #endif
323 #if defined(MS_WINDOWS) || defined(__BEOS__)
324 /* BeOS suffers from the same socket dichotomy as Win32... - [cjh] */
325 /* seem to be a few differences in the API */
326 #define SOCKETCLOSE closesocket
327 #define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */
328 #endif
330 #ifdef MS_WIN32
331 #define EAFNOSUPPORT WSAEAFNOSUPPORT
332 #define snprintf _snprintf
333 #endif
335 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
336 #define SOCKETCLOSE soclose
337 #define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
338 #endif
340 #ifndef SOCKETCLOSE
341 #define SOCKETCLOSE close
342 #endif
344 #ifdef __VMS
345 /* TCP/IP Services for VMS uses a maximum send/revc buffer length of 65535 */
346 #define SEGMENT_SIZE 65535
347 #endif
349 #if defined(HAVE_BLUETOOTH_H) || defined(HAVE_BLUETOOTH_BLUETOOTH_H)
350 #define USE_BLUETOOTH 1
351 #if defined(__FreeBSD__)
352 #define BTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP
353 #define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM
354 #define sockaddr_l2 sockaddr_l2cap
355 #define sockaddr_rc sockaddr_rfcomm
356 #define _BT_SOCKADDR_MEMB(s, proto) &((s)->sock_addr)
357 #define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb)
358 #define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)
359 #else
360 #define _BT_SOCKADDR_MEMB(s, proto) (&((s)->sock_addr).bt_##proto)
361 #define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb)
362 #define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb)
363 #define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)
364 #endif
365 #endif
368 * Constants for getnameinfo()
370 #if !defined(NI_MAXHOST)
371 #define NI_MAXHOST 1025
372 #endif
373 #if !defined(NI_MAXSERV)
374 #define NI_MAXSERV 32
375 #endif
377 /* XXX There's a problem here: *static* functions are not supposed to have
378 a Py prefix (or use CapitalizedWords). Later... */
380 /* Global variable holding the exception type for errors detected
381 by this module (but not argument type or memory errors, etc.). */
382 static PyObject *socket_error;
383 static PyObject *socket_herror;
384 static PyObject *socket_gaierror;
385 static PyObject *socket_timeout;
387 #ifdef RISCOS
388 /* Global variable which is !=0 if Python is running in a RISC OS taskwindow */
389 static int taskwindow;
390 #endif
392 /* A forward reference to the socket type object.
393 The sock_type variable contains pointers to various functions,
394 some of which call new_sockobject(), which uses sock_type, so
395 there has to be a circular reference. */
396 static PyTypeObject sock_type;
398 /* Convenience function to raise an error according to errno
399 and return a NULL pointer from a function. */
401 static PyObject *
402 set_error(void)
404 #ifdef MS_WINDOWS
405 int err_no = WSAGetLastError();
406 static struct {
407 int no;
408 const char *msg;
409 } *msgp, msgs[] = {
410 {WSAEINTR, "Interrupted system call"},
411 {WSAEBADF, "Bad file descriptor"},
412 {WSAEACCES, "Permission denied"},
413 {WSAEFAULT, "Bad address"},
414 {WSAEINVAL, "Invalid argument"},
415 {WSAEMFILE, "Too many open files"},
416 {WSAEWOULDBLOCK,
417 "The socket operation could not complete "
418 "without blocking"},
419 {WSAEINPROGRESS, "Operation now in progress"},
420 {WSAEALREADY, "Operation already in progress"},
421 {WSAENOTSOCK, "Socket operation on non-socket"},
422 {WSAEDESTADDRREQ, "Destination address required"},
423 {WSAEMSGSIZE, "Message too long"},
424 {WSAEPROTOTYPE, "Protocol wrong type for socket"},
425 {WSAENOPROTOOPT, "Protocol not available"},
426 {WSAEPROTONOSUPPORT, "Protocol not supported"},
427 {WSAESOCKTNOSUPPORT, "Socket type not supported"},
428 {WSAEOPNOTSUPP, "Operation not supported"},
429 {WSAEPFNOSUPPORT, "Protocol family not supported"},
430 {WSAEAFNOSUPPORT, "Address family not supported"},
431 {WSAEADDRINUSE, "Address already in use"},
432 {WSAEADDRNOTAVAIL, "Can't assign requested address"},
433 {WSAENETDOWN, "Network is down"},
434 {WSAENETUNREACH, "Network is unreachable"},
435 {WSAENETRESET, "Network dropped connection on reset"},
436 {WSAECONNABORTED, "Software caused connection abort"},
437 {WSAECONNRESET, "Connection reset by peer"},
438 {WSAENOBUFS, "No buffer space available"},
439 {WSAEISCONN, "Socket is already connected"},
440 {WSAENOTCONN, "Socket is not connected"},
441 {WSAESHUTDOWN, "Can't send after socket shutdown"},
442 {WSAETOOMANYREFS, "Too many references: can't splice"},
443 {WSAETIMEDOUT, "Operation timed out"},
444 {WSAECONNREFUSED, "Connection refused"},
445 {WSAELOOP, "Too many levels of symbolic links"},
446 {WSAENAMETOOLONG, "File name too long"},
447 {WSAEHOSTDOWN, "Host is down"},
448 {WSAEHOSTUNREACH, "No route to host"},
449 {WSAENOTEMPTY, "Directory not empty"},
450 {WSAEPROCLIM, "Too many processes"},
451 {WSAEUSERS, "Too many users"},
452 {WSAEDQUOT, "Disc quota exceeded"},
453 {WSAESTALE, "Stale NFS file handle"},
454 {WSAEREMOTE, "Too many levels of remote in path"},
455 {WSASYSNOTREADY, "Network subsystem is unvailable"},
456 {WSAVERNOTSUPPORTED, "WinSock version is not supported"},
457 {WSANOTINITIALISED,
458 "Successful WSAStartup() not yet performed"},
459 {WSAEDISCON, "Graceful shutdown in progress"},
460 /* Resolver errors */
461 {WSAHOST_NOT_FOUND, "No such host is known"},
462 {WSATRY_AGAIN, "Host not found, or server failed"},
463 {WSANO_RECOVERY, "Unexpected server error encountered"},
464 {WSANO_DATA, "Valid name without requested data"},
465 {WSANO_ADDRESS, "No address, look for MX record"},
466 {0, NULL}
468 if (err_no) {
469 PyObject *v;
470 const char *msg = "winsock error";
472 for (msgp = msgs; msgp->msg; msgp++) {
473 if (err_no == msgp->no) {
474 msg = msgp->msg;
475 break;
479 v = Py_BuildValue("(is)", err_no, msg);
480 if (v != NULL) {
481 PyErr_SetObject(socket_error, v);
482 Py_DECREF(v);
484 return NULL;
486 else
487 #endif
489 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
490 if (sock_errno() != NO_ERROR) {
491 APIRET rc;
492 ULONG msglen;
493 char outbuf[100];
494 int myerrorcode = sock_errno();
496 /* Retrieve socket-related error message from MPTN.MSG file */
497 rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf),
498 myerrorcode - SOCBASEERR + 26,
499 "mptn.msg",
500 &msglen);
501 if (rc == NO_ERROR) {
502 PyObject *v;
504 /* OS/2 doesn't guarantee a terminator */
505 outbuf[msglen] = '\0';
506 if (strlen(outbuf) > 0) {
507 /* If non-empty msg, trim CRLF */
508 char *lastc = &outbuf[ strlen(outbuf)-1 ];
509 while (lastc > outbuf &&
510 isspace(Py_CHARMASK(*lastc))) {
511 /* Trim trailing whitespace (CRLF) */
512 *lastc-- = '\0';
515 v = Py_BuildValue("(is)", myerrorcode, outbuf);
516 if (v != NULL) {
517 PyErr_SetObject(socket_error, v);
518 Py_DECREF(v);
520 return NULL;
523 #endif
525 #if defined(RISCOS)
526 if (_inet_error.errnum != NULL) {
527 PyObject *v;
528 v = Py_BuildValue("(is)", errno, _inet_err());
529 if (v != NULL) {
530 PyErr_SetObject(socket_error, v);
531 Py_DECREF(v);
533 return NULL;
535 #endif
537 return PyErr_SetFromErrno(socket_error);
541 static PyObject *
542 set_herror(int h_error)
544 PyObject *v;
546 #ifdef HAVE_HSTRERROR
547 v = Py_BuildValue("(is)", h_error, (char *)hstrerror(h_error));
548 #else
549 v = Py_BuildValue("(is)", h_error, "host not found");
550 #endif
551 if (v != NULL) {
552 PyErr_SetObject(socket_herror, v);
553 Py_DECREF(v);
556 return NULL;
560 static PyObject *
561 set_gaierror(int error)
563 PyObject *v;
565 #ifdef EAI_SYSTEM
566 /* EAI_SYSTEM is not available on Windows XP. */
567 if (error == EAI_SYSTEM)
568 return set_error();
569 #endif
571 #ifdef HAVE_GAI_STRERROR
572 v = Py_BuildValue("(is)", error, gai_strerror(error));
573 #else
574 v = Py_BuildValue("(is)", error, "getaddrinfo failed");
575 #endif
576 if (v != NULL) {
577 PyErr_SetObject(socket_gaierror, v);
578 Py_DECREF(v);
581 return NULL;
584 /* Function to perform the setting of socket blocking mode
585 internally. block = (1 | 0). */
586 static int
587 internal_setblocking(PySocketSockObject *s, int block)
589 #ifndef RISCOS
590 #ifndef MS_WINDOWS
591 int delay_flag;
592 #endif
593 #endif
595 Py_BEGIN_ALLOW_THREADS
596 #ifdef __BEOS__
597 block = !block;
598 setsockopt(s->sock_fd, SOL_SOCKET, SO_NONBLOCK,
599 (void *)(&block), sizeof(int));
600 #else
601 #ifndef RISCOS
602 #ifndef MS_WINDOWS
603 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
604 block = !block;
605 ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block));
606 #elif defined(__VMS)
607 block = !block;
608 ioctl(s->sock_fd, FIONBIO, (char *)&block);
609 #else /* !PYOS_OS2 && !_VMS */
610 delay_flag = fcntl(s->sock_fd, F_GETFL, 0);
611 if (block)
612 delay_flag &= (~O_NONBLOCK);
613 else
614 delay_flag |= O_NONBLOCK;
615 fcntl(s->sock_fd, F_SETFL, delay_flag);
616 #endif /* !PYOS_OS2 */
617 #else /* MS_WINDOWS */
618 block = !block;
619 ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
620 #endif /* MS_WINDOWS */
621 #else /* RISCOS */
622 block = !block;
623 socketioctl(s->sock_fd, FIONBIO, (u_long*)&block);
624 #endif /* RISCOS */
625 #endif /* __BEOS__ */
626 Py_END_ALLOW_THREADS
628 /* Since these don't return anything */
629 return 1;
632 /* Do a select() on the socket, if necessary (sock_timeout > 0).
633 The argument writing indicates the direction.
634 This does not raise an exception; we'll let our caller do that
635 after they've reacquired the interpreter lock.
636 Returns 1 on timeout, 0 otherwise. */
637 static int
638 internal_select(PySocketSockObject *s, int writing)
640 fd_set fds;
641 struct timeval tv;
642 int n;
644 /* Nothing to do unless we're in timeout mode (not non-blocking) */
645 if (s->sock_timeout <= 0.0)
646 return 0;
648 /* Guard against closed socket */
649 if (s->sock_fd < 0)
650 return 0;
652 /* Construct the arguments to select */
653 tv.tv_sec = (int)s->sock_timeout;
654 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
655 FD_ZERO(&fds);
656 FD_SET(s->sock_fd, &fds);
658 /* See if the socket is ready */
659 if (writing)
660 n = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
661 else
662 n = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
663 if (n == 0)
664 return 1;
665 return 0;
668 /* Initialize a new socket object. */
670 static double defaulttimeout = -1.0; /* Default timeout for new sockets */
672 PyMODINIT_FUNC
673 init_sockobject(PySocketSockObject *s,
674 SOCKET_T fd, int family, int type, int proto)
676 #ifdef RISCOS
677 int block = 1;
678 #endif
679 s->sock_fd = fd;
680 s->sock_family = family;
681 s->sock_type = type;
682 s->sock_proto = proto;
683 s->sock_timeout = defaulttimeout;
685 s->errorhandler = &set_error;
687 if (defaulttimeout >= 0.0)
688 internal_setblocking(s, 0);
690 #ifdef RISCOS
691 if (taskwindow)
692 socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
693 #endif
697 /* Create a new socket object.
698 This just creates the object and initializes it.
699 If the creation fails, return NULL and set an exception (implicit
700 in NEWOBJ()). */
702 static PySocketSockObject *
703 new_sockobject(SOCKET_T fd, int family, int type, int proto)
705 PySocketSockObject *s;
706 s = (PySocketSockObject *)
707 PyType_GenericNew(&sock_type, NULL, NULL);
708 if (s != NULL)
709 init_sockobject(s, fd, family, type, proto);
710 return s;
714 /* Lock to allow python interpreter to continue, but only allow one
715 thread to be in gethostbyname or getaddrinfo */
716 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
717 PyThread_type_lock netdb_lock;
718 #endif
721 /* Convert a string specifying a host name or one of a few symbolic
722 names to a numeric IP address. This usually calls gethostbyname()
723 to do the work; the names "" and "<broadcast>" are special.
724 Return the length (IPv4 should be 4 bytes), or negative if
725 an error occurred; then an exception is raised. */
727 static int
728 setipaddr(char *name, struct sockaddr *addr_ret, size_t addr_ret_size, int af)
730 struct addrinfo hints, *res;
731 int error;
732 int d1, d2, d3, d4;
733 char ch;
735 memset((void *) addr_ret, '\0', sizeof(*addr_ret));
736 if (name[0] == '\0') {
737 int siz;
738 memset(&hints, 0, sizeof(hints));
739 hints.ai_family = af;
740 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
741 hints.ai_flags = AI_PASSIVE;
742 Py_BEGIN_ALLOW_THREADS
743 ACQUIRE_GETADDRINFO_LOCK
744 error = getaddrinfo(NULL, "0", &hints, &res);
745 Py_END_ALLOW_THREADS
746 /* We assume that those thread-unsafe getaddrinfo() versions
747 *are* safe regarding their return value, ie. that a
748 subsequent call to getaddrinfo() does not destroy the
749 outcome of the first call. */
750 RELEASE_GETADDRINFO_LOCK
751 if (error) {
752 set_gaierror(error);
753 return -1;
755 switch (res->ai_family) {
756 case AF_INET:
757 siz = 4;
758 break;
759 #ifdef ENABLE_IPV6
760 case AF_INET6:
761 siz = 16;
762 break;
763 #endif
764 default:
765 freeaddrinfo(res);
766 PyErr_SetString(socket_error,
767 "unsupported address family");
768 return -1;
770 if (res->ai_next) {
771 freeaddrinfo(res);
772 PyErr_SetString(socket_error,
773 "wildcard resolved to multiple address");
774 return -1;
776 if (res->ai_addrlen < addr_ret_size)
777 addr_ret_size = res->ai_addrlen;
778 memcpy(addr_ret, res->ai_addr, addr_ret_size);
779 freeaddrinfo(res);
780 return siz;
782 if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
783 struct sockaddr_in *sin;
784 if (af != AF_INET && af != AF_UNSPEC) {
785 PyErr_SetString(socket_error,
786 "address family mismatched");
787 return -1;
789 sin = (struct sockaddr_in *)addr_ret;
790 memset((void *) sin, '\0', sizeof(*sin));
791 sin->sin_family = AF_INET;
792 #ifdef HAVE_SOCKADDR_SA_LEN
793 sin->sin_len = sizeof(*sin);
794 #endif
795 sin->sin_addr.s_addr = INADDR_BROADCAST;
796 return sizeof(sin->sin_addr);
798 if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 &&
799 0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 &&
800 0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) {
801 struct sockaddr_in *sin;
802 sin = (struct sockaddr_in *)addr_ret;
803 sin->sin_addr.s_addr = htonl(
804 ((long) d1 << 24) | ((long) d2 << 16) |
805 ((long) d3 << 8) | ((long) d4 << 0));
806 sin->sin_family = AF_INET;
807 #ifdef HAVE_SOCKADDR_SA_LEN
808 sin->sin_len = sizeof(*sin);
809 #endif
810 return 4;
812 memset(&hints, 0, sizeof(hints));
813 hints.ai_family = af;
814 Py_BEGIN_ALLOW_THREADS
815 ACQUIRE_GETADDRINFO_LOCK
816 error = getaddrinfo(name, NULL, &hints, &res);
817 #if defined(__digital__) && defined(__unix__)
818 if (error == EAI_NONAME && af == AF_UNSPEC) {
819 /* On Tru64 V5.1, numeric-to-addr conversion fails
820 if no address family is given. Assume IPv4 for now.*/
821 hints.ai_family = AF_INET;
822 error = getaddrinfo(name, NULL, &hints, &res);
824 #endif
825 Py_END_ALLOW_THREADS
826 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
827 if (error) {
828 set_gaierror(error);
829 return -1;
831 if (res->ai_addrlen < addr_ret_size)
832 addr_ret_size = res->ai_addrlen;
833 memcpy((char *) addr_ret, res->ai_addr, addr_ret_size);
834 freeaddrinfo(res);
835 switch (addr_ret->sa_family) {
836 case AF_INET:
837 return 4;
838 #ifdef ENABLE_IPV6
839 case AF_INET6:
840 return 16;
841 #endif
842 default:
843 PyErr_SetString(socket_error, "unknown address family");
844 return -1;
849 /* Create a string object representing an IP address.
850 This is always a string of the form 'dd.dd.dd.dd' (with variable
851 size numbers). */
853 static PyObject *
854 makeipaddr(struct sockaddr *addr, int addrlen)
856 char buf[NI_MAXHOST];
857 int error;
859 error = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0,
860 NI_NUMERICHOST);
861 if (error) {
862 set_gaierror(error);
863 return NULL;
865 return PyString_FromString(buf);
869 #ifdef USE_BLUETOOTH
870 /* Convert a string representation of a Bluetooth address into a numeric
871 address. Returns the length (6), or raises an exception and returns -1 if
872 an error occurred. */
874 static int
875 setbdaddr(char *name, bdaddr_t *bdaddr)
877 unsigned int b0, b1, b2, b3, b4, b5;
878 char ch;
879 int n;
881 n = sscanf(name, "%X:%X:%X:%X:%X:%X%c",
882 &b5, &b4, &b3, &b2, &b1, &b0, &ch);
883 if (n == 6 && (b0 | b1 | b2 | b3 | b4 | b5) < 256) {
884 bdaddr->b[0] = b0;
885 bdaddr->b[1] = b1;
886 bdaddr->b[2] = b2;
887 bdaddr->b[3] = b3;
888 bdaddr->b[4] = b4;
889 bdaddr->b[5] = b5;
890 return 6;
891 } else {
892 PyErr_SetString(socket_error, "bad bluetooth address");
893 return -1;
897 /* Create a string representation of the Bluetooth address. This is always a
898 string of the form 'XX:XX:XX:XX:XX:XX' where XX is a two digit hexadecimal
899 value (zero padded if necessary). */
901 static PyObject *
902 makebdaddr(bdaddr_t *bdaddr)
904 char buf[(6 * 2) + 5 + 1];
906 sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
907 bdaddr->b[5], bdaddr->b[4], bdaddr->b[3],
908 bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]);
909 return PyString_FromString(buf);
911 #endif
914 /* Create an object representing the given socket address,
915 suitable for passing it back to bind(), connect() etc.
916 The family field of the sockaddr structure is inspected
917 to determine what kind of address it really is. */
919 /*ARGSUSED*/
920 static PyObject *
921 makesockaddr(int sockfd, struct sockaddr *addr, int addrlen, int proto)
923 if (addrlen == 0) {
924 /* No address -- may be recvfrom() from known socket */
925 Py_INCREF(Py_None);
926 return Py_None;
929 #ifdef __BEOS__
930 /* XXX: BeOS version of accept() doesn't set family correctly */
931 addr->sa_family = AF_INET;
932 #endif
934 switch (addr->sa_family) {
936 case AF_INET:
938 struct sockaddr_in *a;
939 PyObject *addrobj = makeipaddr(addr, sizeof(*a));
940 PyObject *ret = NULL;
941 if (addrobj) {
942 a = (struct sockaddr_in *)addr;
943 ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
944 Py_DECREF(addrobj);
946 return ret;
949 #if defined(AF_UNIX)
950 case AF_UNIX:
952 struct sockaddr_un *a = (struct sockaddr_un *) addr;
953 return PyString_FromString(a->sun_path);
955 #endif /* AF_UNIX */
957 #if defined(AF_NETLINK)
958 case AF_NETLINK:
960 struct sockaddr_nl *a = (struct sockaddr_nl *) addr;
961 return Py_BuildValue("II", a->nl_pid, a->nl_groups);
963 #endif /* AF_NETLINK */
965 #ifdef ENABLE_IPV6
966 case AF_INET6:
968 struct sockaddr_in6 *a;
969 PyObject *addrobj = makeipaddr(addr, sizeof(*a));
970 PyObject *ret = NULL;
971 if (addrobj) {
972 a = (struct sockaddr_in6 *)addr;
973 ret = Py_BuildValue("Oiii",
974 addrobj,
975 ntohs(a->sin6_port),
976 a->sin6_flowinfo,
977 a->sin6_scope_id);
978 Py_DECREF(addrobj);
980 return ret;
982 #endif
984 #ifdef USE_BLUETOOTH
985 case AF_BLUETOOTH:
986 switch (proto) {
988 case BTPROTO_L2CAP:
990 struct sockaddr_l2 *a = (struct sockaddr_l2 *) addr;
991 PyObject *addrobj = makebdaddr(&_BT_L2_MEMB(a, bdaddr));
992 PyObject *ret = NULL;
993 if (addrobj) {
994 ret = Py_BuildValue("Oi",
995 addrobj,
996 _BT_L2_MEMB(a, psm));
997 Py_DECREF(addrobj);
999 return ret;
1002 case BTPROTO_RFCOMM:
1004 struct sockaddr_rc *a = (struct sockaddr_rc *) addr;
1005 PyObject *addrobj = makebdaddr(&_BT_RC_MEMB(a, bdaddr));
1006 PyObject *ret = NULL;
1007 if (addrobj) {
1008 ret = Py_BuildValue("Oi",
1009 addrobj,
1010 _BT_RC_MEMB(a, channel));
1011 Py_DECREF(addrobj);
1013 return ret;
1016 #if !defined(__FreeBSD__)
1017 case BTPROTO_SCO:
1019 struct sockaddr_sco *a = (struct sockaddr_sco *) addr;
1020 return makebdaddr(&_BT_SCO_MEMB(a, bdaddr));
1022 #endif
1025 #endif
1027 #ifdef HAVE_NETPACKET_PACKET_H
1028 case AF_PACKET:
1030 struct sockaddr_ll *a = (struct sockaddr_ll *)addr;
1031 char *ifname = "";
1032 struct ifreq ifr;
1033 /* need to look up interface name give index */
1034 if (a->sll_ifindex) {
1035 ifr.ifr_ifindex = a->sll_ifindex;
1036 if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0)
1037 ifname = ifr.ifr_name;
1039 return Py_BuildValue("shbhs#",
1040 ifname,
1041 ntohs(a->sll_protocol),
1042 a->sll_pkttype,
1043 a->sll_hatype,
1044 a->sll_addr,
1045 a->sll_halen);
1047 #endif
1049 /* More cases here... */
1051 default:
1052 /* If we don't know the address family, don't raise an
1053 exception -- return it as a tuple. */
1054 return Py_BuildValue("is#",
1055 addr->sa_family,
1056 addr->sa_data,
1057 sizeof(addr->sa_data));
1063 /* Parse a socket address argument according to the socket object's
1064 address family. Return 1 if the address was in the proper format,
1065 0 of not. The address is returned through addr_ret, its length
1066 through len_ret. */
1068 static int
1069 getsockaddrarg(PySocketSockObject *s, PyObject *args,
1070 struct sockaddr **addr_ret, int *len_ret)
1072 switch (s->sock_family) {
1074 #if defined(AF_UNIX)
1075 case AF_UNIX:
1077 struct sockaddr_un* addr;
1078 char *path;
1079 int len;
1080 addr = (struct sockaddr_un*)&(s->sock_addr).un;
1081 if (!PyArg_Parse(args, "t#", &path, &len))
1082 return 0;
1083 if (len > sizeof addr->sun_path) {
1084 PyErr_SetString(socket_error,
1085 "AF_UNIX path too long");
1086 return 0;
1088 addr->sun_family = s->sock_family;
1089 memcpy(addr->sun_path, path, len);
1090 addr->sun_path[len] = 0;
1091 *addr_ret = (struct sockaddr *) addr;
1092 #if defined(PYOS_OS2)
1093 *len_ret = sizeof(*addr);
1094 #else
1095 *len_ret = len + sizeof(*addr) - sizeof(addr->sun_path);
1096 #endif
1097 return 1;
1099 #endif /* AF_UNIX */
1101 #if defined(AF_NETLINK)
1102 case AF_NETLINK:
1104 struct sockaddr_nl* addr;
1105 int pid, groups;
1106 addr = (struct sockaddr_nl *)&(s->sock_addr).nl;
1107 if (!PyTuple_Check(args)) {
1108 PyErr_Format(
1109 PyExc_TypeError,
1110 "getsockaddrarg: "
1111 "AF_NETLINK address must be tuple, not %.500s",
1112 args->ob_type->tp_name);
1113 return 0;
1115 if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &pid, &groups))
1116 return 0;
1117 addr->nl_family = AF_NETLINK;
1118 addr->nl_pid = pid;
1119 addr->nl_groups = groups;
1120 *addr_ret = (struct sockaddr *) addr;
1121 *len_ret = sizeof(*addr);
1122 return 1;
1124 #endif
1126 case AF_INET:
1128 struct sockaddr_in* addr;
1129 char *host;
1130 int port, result;
1131 addr=(struct sockaddr_in*)&(s->sock_addr).in;
1132 if (!PyTuple_Check(args)) {
1133 PyErr_Format(
1134 PyExc_TypeError,
1135 "getsockaddrarg: "
1136 "AF_INET address must be tuple, not %.500s",
1137 args->ob_type->tp_name);
1138 return 0;
1140 if (!PyArg_ParseTuple(args, "eti:getsockaddrarg",
1141 "idna", &host, &port))
1142 return 0;
1143 result = setipaddr(host, (struct sockaddr *)addr,
1144 sizeof(*addr), AF_INET);
1145 PyMem_Free(host);
1146 if (result < 0)
1147 return 0;
1148 addr->sin_family = AF_INET;
1149 addr->sin_port = htons((short)port);
1150 *addr_ret = (struct sockaddr *) addr;
1151 *len_ret = sizeof *addr;
1152 return 1;
1155 #ifdef ENABLE_IPV6
1156 case AF_INET6:
1158 struct sockaddr_in6* addr;
1159 char *host;
1160 int port, flowinfo, scope_id, result;
1161 addr = (struct sockaddr_in6*)&(s->sock_addr).in6;
1162 flowinfo = scope_id = 0;
1163 if (!PyArg_ParseTuple(args, "eti|ii",
1164 "idna", &host, &port, &flowinfo,
1165 &scope_id)) {
1166 return 0;
1168 result = setipaddr(host, (struct sockaddr *)addr,
1169 sizeof(*addr), AF_INET6);
1170 PyMem_Free(host);
1171 if (result < 0)
1172 return 0;
1173 addr->sin6_family = s->sock_family;
1174 addr->sin6_port = htons((short)port);
1175 addr->sin6_flowinfo = flowinfo;
1176 addr->sin6_scope_id = scope_id;
1177 *addr_ret = (struct sockaddr *) addr;
1178 *len_ret = sizeof *addr;
1179 return 1;
1181 #endif
1183 #ifdef USE_BLUETOOTH
1184 case AF_BLUETOOTH:
1186 switch (s->sock_proto) {
1187 case BTPROTO_L2CAP:
1189 struct sockaddr_l2 *addr = (struct sockaddr_l2 *) _BT_SOCKADDR_MEMB(s, l2);
1190 char *straddr;
1192 _BT_L2_MEMB(addr, family) = AF_BLUETOOTH;
1193 if (!PyArg_ParseTuple(args, "si", &straddr,
1194 &_BT_L2_MEMB(addr, psm))) {
1195 PyErr_SetString(socket_error, "getsockaddrarg: "
1196 "wrong format");
1197 return 0;
1199 if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0)
1200 return 0;
1202 *addr_ret = (struct sockaddr *) addr;
1203 *len_ret = sizeof *addr;
1204 return 1;
1206 case BTPROTO_RFCOMM:
1208 struct sockaddr_rc *addr = (struct sockaddr_rc *) _BT_SOCKADDR_MEMB(s, rc);
1209 char *straddr;
1211 _BT_RC_MEMB(addr, family) = AF_BLUETOOTH;
1212 if (!PyArg_ParseTuple(args, "si", &straddr,
1213 &_BT_RC_MEMB(addr, channel))) {
1214 PyErr_SetString(socket_error, "getsockaddrarg: "
1215 "wrong format");
1216 return 0;
1218 if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0)
1219 return 0;
1221 *addr_ret = (struct sockaddr *) addr;
1222 *len_ret = sizeof *addr;
1223 return 1;
1225 #if !defined(__FreeBSD__)
1226 case BTPROTO_SCO:
1228 struct sockaddr_sco *addr = (struct sockaddr_sco *) _BT_SOCKADDR_MEMB(s, sco);
1229 char *straddr;
1231 _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH;
1232 straddr = PyString_AsString(args);
1233 if (straddr == NULL) {
1234 PyErr_SetString(socket_error, "getsockaddrarg: "
1235 "wrong format");
1236 return 0;
1238 if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0)
1239 return 0;
1241 *addr_ret = (struct sockaddr *) addr;
1242 *len_ret = sizeof *addr;
1243 return 1;
1245 #endif
1246 default:
1247 PyErr_SetString(socket_error, "getsockaddrarg: unknown Bluetooth protocol");
1248 return 0;
1251 #endif
1253 #ifdef HAVE_NETPACKET_PACKET_H
1254 case AF_PACKET:
1256 struct sockaddr_ll* addr;
1257 struct ifreq ifr;
1258 char *interfaceName;
1259 int protoNumber;
1260 int hatype = 0;
1261 int pkttype = 0;
1262 char *haddr = NULL;
1263 unsigned int halen = 0;
1265 if (!PyArg_ParseTuple(args, "si|iis#", &interfaceName,
1266 &protoNumber, &pkttype, &hatype,
1267 &haddr, &halen))
1268 return 0;
1269 strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name));
1270 ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
1271 if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
1272 s->errorhandler();
1273 return 0;
1275 addr = &(s->sock_addr.ll);
1276 addr->sll_family = AF_PACKET;
1277 addr->sll_protocol = htons((short)protoNumber);
1278 addr->sll_ifindex = ifr.ifr_ifindex;
1279 addr->sll_pkttype = pkttype;
1280 addr->sll_hatype = hatype;
1281 if (halen > 8) {
1282 PyErr_SetString(PyExc_ValueError,
1283 "Hardware address must be 8 bytes or less");
1284 return 0;
1286 if (halen != 0) {
1287 memcpy(&addr->sll_addr, haddr, halen);
1289 addr->sll_halen = halen;
1290 *addr_ret = (struct sockaddr *) addr;
1291 *len_ret = sizeof *addr;
1292 return 1;
1294 #endif
1296 /* More cases here... */
1298 default:
1299 PyErr_SetString(socket_error, "getsockaddrarg: bad family");
1300 return 0;
1306 /* Get the address length according to the socket object's address family.
1307 Return 1 if the family is known, 0 otherwise. The length is returned
1308 through len_ret. */
1310 static int
1311 getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
1313 switch (s->sock_family) {
1315 #if defined(AF_UNIX)
1316 case AF_UNIX:
1318 *len_ret = sizeof (struct sockaddr_un);
1319 return 1;
1321 #endif /* AF_UNIX */
1322 #if defined(AF_NETLINK)
1323 case AF_NETLINK:
1325 *len_ret = sizeof (struct sockaddr_nl);
1326 return 1;
1328 #endif
1330 case AF_INET:
1332 *len_ret = sizeof (struct sockaddr_in);
1333 return 1;
1336 #ifdef ENABLE_IPV6
1337 case AF_INET6:
1339 *len_ret = sizeof (struct sockaddr_in6);
1340 return 1;
1342 #endif
1344 #ifdef USE_BLUETOOTH
1345 case AF_BLUETOOTH:
1347 switch(s->sock_proto)
1350 case BTPROTO_L2CAP:
1351 *len_ret = sizeof (struct sockaddr_l2);
1352 return 1;
1353 case BTPROTO_RFCOMM:
1354 *len_ret = sizeof (struct sockaddr_rc);
1355 return 1;
1356 #if !defined(__FreeBSD__)
1357 case BTPROTO_SCO:
1358 *len_ret = sizeof (struct sockaddr_sco);
1359 return 1;
1360 #endif
1361 default:
1362 PyErr_SetString(socket_error, "getsockaddrlen: "
1363 "unknown BT protocol");
1364 return 0;
1368 #endif
1370 #ifdef HAVE_NETPACKET_PACKET_H
1371 case AF_PACKET:
1373 *len_ret = sizeof (struct sockaddr_ll);
1374 return 1;
1376 #endif
1378 /* More cases here... */
1380 default:
1381 PyErr_SetString(socket_error, "getsockaddrlen: bad family");
1382 return 0;
1388 /* s.accept() method */
1390 static PyObject *
1391 sock_accept(PySocketSockObject *s)
1393 sock_addr_t addrbuf;
1394 SOCKET_T newfd;
1395 socklen_t addrlen;
1396 PyObject *sock = NULL;
1397 PyObject *addr = NULL;
1398 PyObject *res = NULL;
1399 int timeout;
1401 if (!getsockaddrlen(s, &addrlen))
1402 return NULL;
1403 memset(&addrbuf, 0, addrlen);
1405 #ifdef MS_WINDOWS
1406 newfd = INVALID_SOCKET;
1407 #else
1408 newfd = -1;
1409 #endif
1411 Py_BEGIN_ALLOW_THREADS
1412 timeout = internal_select(s, 0);
1413 if (!timeout)
1414 newfd = accept(s->sock_fd, (struct sockaddr *) &addrbuf,
1415 &addrlen);
1416 Py_END_ALLOW_THREADS
1418 if (timeout) {
1419 PyErr_SetString(socket_timeout, "timed out");
1420 return NULL;
1423 #ifdef MS_WINDOWS
1424 if (newfd == INVALID_SOCKET)
1425 #else
1426 if (newfd < 0)
1427 #endif
1428 return s->errorhandler();
1430 /* Create the new object with unspecified family,
1431 to avoid calls to bind() etc. on it. */
1432 sock = (PyObject *) new_sockobject(newfd,
1433 s->sock_family,
1434 s->sock_type,
1435 s->sock_proto);
1437 if (sock == NULL) {
1438 SOCKETCLOSE(newfd);
1439 goto finally;
1441 addr = makesockaddr(s->sock_fd, (struct sockaddr *) &addrbuf,
1442 addrlen, s->sock_proto);
1443 if (addr == NULL)
1444 goto finally;
1446 res = PyTuple_Pack(2, sock, addr);
1448 finally:
1449 Py_XDECREF(sock);
1450 Py_XDECREF(addr);
1451 return res;
1454 PyDoc_STRVAR(accept_doc,
1455 "accept() -> (socket object, address info)\n\
1457 Wait for an incoming connection. Return a new socket representing the\n\
1458 connection, and the address of the client. For IP sockets, the address\n\
1459 info is a pair (hostaddr, port).");
1461 /* s.setblocking(flag) method. Argument:
1462 False -- non-blocking mode; same as settimeout(0)
1463 True -- blocking mode; same as settimeout(None)
1466 static PyObject *
1467 sock_setblocking(PySocketSockObject *s, PyObject *arg)
1469 int block;
1471 block = PyInt_AsLong(arg);
1472 if (block == -1 && PyErr_Occurred())
1473 return NULL;
1475 s->sock_timeout = block ? -1.0 : 0.0;
1476 internal_setblocking(s, block);
1478 Py_INCREF(Py_None);
1479 return Py_None;
1482 PyDoc_STRVAR(setblocking_doc,
1483 "setblocking(flag)\n\
1485 Set the socket to blocking (flag is true) or non-blocking (false).\n\
1486 setblocking(True) is equivalent to settimeout(None);\n\
1487 setblocking(False) is equivalent to settimeout(0.0).");
1489 /* s.settimeout(timeout) method. Argument:
1490 None -- no timeout, blocking mode; same as setblocking(True)
1491 0.0 -- non-blocking mode; same as setblocking(False)
1492 > 0 -- timeout mode; operations time out after timeout seconds
1493 < 0 -- illegal; raises an exception
1495 static PyObject *
1496 sock_settimeout(PySocketSockObject *s, PyObject *arg)
1498 double timeout;
1500 if (arg == Py_None)
1501 timeout = -1.0;
1502 else {
1503 timeout = PyFloat_AsDouble(arg);
1504 if (timeout < 0.0) {
1505 if (!PyErr_Occurred())
1506 PyErr_SetString(PyExc_ValueError,
1507 "Timeout value out of range");
1508 return NULL;
1512 s->sock_timeout = timeout;
1513 internal_setblocking(s, timeout < 0.0);
1515 Py_INCREF(Py_None);
1516 return Py_None;
1519 PyDoc_STRVAR(settimeout_doc,
1520 "settimeout(timeout)\n\
1522 Set a timeout on socket operations. 'timeout' can be a float,\n\
1523 giving in seconds, or None. Setting a timeout of None disables\n\
1524 the timeout feature and is equivalent to setblocking(1).\n\
1525 Setting a timeout of zero is the same as setblocking(0).");
1527 /* s.gettimeout() method.
1528 Returns the timeout associated with a socket. */
1529 static PyObject *
1530 sock_gettimeout(PySocketSockObject *s)
1532 if (s->sock_timeout < 0.0) {
1533 Py_INCREF(Py_None);
1534 return Py_None;
1536 else
1537 return PyFloat_FromDouble(s->sock_timeout);
1540 PyDoc_STRVAR(gettimeout_doc,
1541 "gettimeout() -> timeout\n\
1543 Returns the timeout in floating seconds associated with socket \n\
1544 operations. A timeout of None indicates that timeouts on socket \n\
1545 operations are disabled.");
1547 #ifdef RISCOS
1548 /* s.sleeptaskw(1 | 0) method */
1550 static PyObject *
1551 sock_sleeptaskw(PySocketSockObject *s,PyObject *arg)
1553 int block;
1554 block = PyInt_AsLong(arg);
1555 if (block == -1 && PyErr_Occurred())
1556 return NULL;
1557 Py_BEGIN_ALLOW_THREADS
1558 socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
1559 Py_END_ALLOW_THREADS
1561 Py_INCREF(Py_None);
1562 return Py_None;
1564 PyDoc_STRVAR(sleeptaskw_doc,
1565 "sleeptaskw(flag)\n\
1567 Allow sleeps in taskwindows.");
1568 #endif
1571 /* s.setsockopt() method.
1572 With an integer third argument, sets an integer option.
1573 With a string third argument, sets an option from a buffer;
1574 use optional built-in module 'struct' to encode the string. */
1576 static PyObject *
1577 sock_setsockopt(PySocketSockObject *s, PyObject *args)
1579 int level;
1580 int optname;
1581 int res;
1582 char *buf;
1583 int buflen;
1584 int flag;
1586 if (PyArg_ParseTuple(args, "iii:setsockopt",
1587 &level, &optname, &flag)) {
1588 buf = (char *) &flag;
1589 buflen = sizeof flag;
1591 else {
1592 PyErr_Clear();
1593 if (!PyArg_ParseTuple(args, "iis#:setsockopt",
1594 &level, &optname, &buf, &buflen))
1595 return NULL;
1597 res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen);
1598 if (res < 0)
1599 return s->errorhandler();
1600 Py_INCREF(Py_None);
1601 return Py_None;
1604 PyDoc_STRVAR(setsockopt_doc,
1605 "setsockopt(level, option, value)\n\
1607 Set a socket option. See the Unix manual for level and option.\n\
1608 The value argument can either be an integer or a string.");
1611 /* s.getsockopt() method.
1612 With two arguments, retrieves an integer option.
1613 With a third integer argument, retrieves a string buffer of that size;
1614 use optional built-in module 'struct' to decode the string. */
1616 static PyObject *
1617 sock_getsockopt(PySocketSockObject *s, PyObject *args)
1619 int level;
1620 int optname;
1621 int res;
1622 PyObject *buf;
1623 socklen_t buflen = 0;
1625 #ifdef __BEOS__
1626 /* We have incomplete socket support. */
1627 PyErr_SetString(socket_error, "getsockopt not supported");
1628 return NULL;
1629 #else
1631 if (!PyArg_ParseTuple(args, "ii|i:getsockopt",
1632 &level, &optname, &buflen))
1633 return NULL;
1635 if (buflen == 0) {
1636 int flag = 0;
1637 socklen_t flagsize = sizeof flag;
1638 res = getsockopt(s->sock_fd, level, optname,
1639 (void *)&flag, &flagsize);
1640 if (res < 0)
1641 return s->errorhandler();
1642 return PyInt_FromLong(flag);
1644 #ifdef __VMS
1645 if (buflen > 1024) {
1646 #else
1647 if (buflen <= 0 || buflen > 1024) {
1648 #endif
1649 PyErr_SetString(socket_error,
1650 "getsockopt buflen out of range");
1651 return NULL;
1653 buf = PyString_FromStringAndSize((char *)NULL, buflen);
1654 if (buf == NULL)
1655 return NULL;
1656 res = getsockopt(s->sock_fd, level, optname,
1657 (void *)PyString_AS_STRING(buf), &buflen);
1658 if (res < 0) {
1659 Py_DECREF(buf);
1660 return s->errorhandler();
1662 _PyString_Resize(&buf, buflen);
1663 return buf;
1664 #endif /* __BEOS__ */
1667 PyDoc_STRVAR(getsockopt_doc,
1668 "getsockopt(level, option[, buffersize]) -> value\n\
1670 Get a socket option. See the Unix manual for level and option.\n\
1671 If a nonzero buffersize argument is given, the return value is a\n\
1672 string of that length; otherwise it is an integer.");
1675 /* s.bind(sockaddr) method */
1677 static PyObject *
1678 sock_bind(PySocketSockObject *s, PyObject *addro)
1680 struct sockaddr *addr;
1681 int addrlen;
1682 int res;
1684 if (!getsockaddrarg(s, addro, &addr, &addrlen))
1685 return NULL;
1686 Py_BEGIN_ALLOW_THREADS
1687 res = bind(s->sock_fd, addr, addrlen);
1688 Py_END_ALLOW_THREADS
1689 if (res < 0)
1690 return s->errorhandler();
1691 Py_INCREF(Py_None);
1692 return Py_None;
1695 PyDoc_STRVAR(bind_doc,
1696 "bind(address)\n\
1698 Bind the socket to a local address. For IP sockets, the address is a\n\
1699 pair (host, port); the host must refer to the local host. For raw packet\n\
1700 sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");
1703 /* s.close() method.
1704 Set the file descriptor to -1 so operations tried subsequently
1705 will surely fail. */
1707 static PyObject *
1708 sock_close(PySocketSockObject *s)
1710 SOCKET_T fd;
1712 if ((fd = s->sock_fd) != -1) {
1713 s->sock_fd = -1;
1714 Py_BEGIN_ALLOW_THREADS
1715 (void) SOCKETCLOSE(fd);
1716 Py_END_ALLOW_THREADS
1718 Py_INCREF(Py_None);
1719 return Py_None;
1722 PyDoc_STRVAR(close_doc,
1723 "close()\n\
1725 Close the socket. It cannot be used after this call.");
1727 static int
1728 internal_connect(PySocketSockObject *s, struct sockaddr *addr, int addrlen,
1729 int *timeoutp)
1731 int res, timeout;
1733 timeout = 0;
1734 res = connect(s->sock_fd, addr, addrlen);
1736 #ifdef MS_WINDOWS
1738 if (s->sock_timeout > 0.0) {
1739 if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK) {
1740 /* This is a mess. Best solution: trust select */
1741 fd_set fds;
1742 fd_set fds_exc;
1743 struct timeval tv;
1744 tv.tv_sec = (int)s->sock_timeout;
1745 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1746 FD_ZERO(&fds);
1747 FD_SET(s->sock_fd, &fds);
1748 FD_ZERO(&fds_exc);
1749 FD_SET(s->sock_fd, &fds_exc);
1750 res = select(s->sock_fd+1, NULL, &fds, &fds_exc, &tv);
1751 if (res == 0) {
1752 res = WSAEWOULDBLOCK;
1753 timeout = 1;
1754 } else if (res > 0) {
1755 if (FD_ISSET(s->sock_fd, &fds))
1756 /* The socket is in the writeable set - this
1757 means connected */
1758 res = 0;
1759 else {
1760 /* As per MS docs, we need to call getsockopt()
1761 to get the underlying error */
1762 int res_size = sizeof res;
1763 /* It must be in the exception set */
1764 assert(FD_ISSET(s->sock_fd, &fds_exc));
1765 if (0 == getsockopt(s->sock_fd, SOL_SOCKET, SO_ERROR,
1766 (char *)&res, &res_size))
1767 /* getsockopt also clears WSAGetLastError,
1768 so reset it back. */
1769 WSASetLastError(res);
1770 else
1771 res = WSAGetLastError();
1774 /* else if (res < 0) an error occurred */
1778 if (res < 0)
1779 res = WSAGetLastError();
1781 #else
1783 if (s->sock_timeout > 0.0) {
1784 if (res < 0 && errno == EINPROGRESS) {
1785 timeout = internal_select(s, 1);
1786 res = connect(s->sock_fd, addr, addrlen);
1787 if (res < 0 && errno == EISCONN)
1788 res = 0;
1792 if (res < 0)
1793 res = errno;
1795 #endif
1796 *timeoutp = timeout;
1798 return res;
1801 /* s.connect(sockaddr) method */
1803 static PyObject *
1804 sock_connect(PySocketSockObject *s, PyObject *addro)
1806 struct sockaddr *addr;
1807 int addrlen;
1808 int res;
1809 int timeout;
1811 if (!getsockaddrarg(s, addro, &addr, &addrlen))
1812 return NULL;
1814 Py_BEGIN_ALLOW_THREADS
1815 res = internal_connect(s, addr, addrlen, &timeout);
1816 Py_END_ALLOW_THREADS
1818 if (timeout) {
1819 PyErr_SetString(socket_timeout, "timed out");
1820 return NULL;
1822 if (res != 0)
1823 return s->errorhandler();
1824 Py_INCREF(Py_None);
1825 return Py_None;
1828 PyDoc_STRVAR(connect_doc,
1829 "connect(address)\n\
1831 Connect the socket to a remote address. For IP sockets, the address\n\
1832 is a pair (host, port).");
1835 /* s.connect_ex(sockaddr) method */
1837 static PyObject *
1838 sock_connect_ex(PySocketSockObject *s, PyObject *addro)
1840 struct sockaddr *addr;
1841 int addrlen;
1842 int res;
1843 int timeout;
1845 if (!getsockaddrarg(s, addro, &addr, &addrlen))
1846 return NULL;
1848 Py_BEGIN_ALLOW_THREADS
1849 res = internal_connect(s, addr, addrlen, &timeout);
1850 Py_END_ALLOW_THREADS
1852 return PyInt_FromLong((long) res);
1855 PyDoc_STRVAR(connect_ex_doc,
1856 "connect_ex(address) -> errno\n\
1858 This is like connect(address), but returns an error code (the errno value)\n\
1859 instead of raising an exception when an error occurs.");
1862 /* s.fileno() method */
1864 static PyObject *
1865 sock_fileno(PySocketSockObject *s)
1867 #if SIZEOF_SOCKET_T <= SIZEOF_LONG
1868 return PyInt_FromLong((long) s->sock_fd);
1869 #else
1870 return PyLong_FromLongLong((PY_LONG_LONG)s->sock_fd);
1871 #endif
1874 PyDoc_STRVAR(fileno_doc,
1875 "fileno() -> integer\n\
1877 Return the integer file descriptor of the socket.");
1880 #ifndef NO_DUP
1881 /* s.dup() method */
1883 static PyObject *
1884 sock_dup(PySocketSockObject *s)
1886 SOCKET_T newfd;
1887 PyObject *sock;
1889 newfd = dup(s->sock_fd);
1890 if (newfd < 0)
1891 return s->errorhandler();
1892 sock = (PyObject *) new_sockobject(newfd,
1893 s->sock_family,
1894 s->sock_type,
1895 s->sock_proto);
1896 if (sock == NULL)
1897 SOCKETCLOSE(newfd);
1898 return sock;
1901 PyDoc_STRVAR(dup_doc,
1902 "dup() -> socket object\n\
1904 Return a new socket object connected to the same system resource.");
1906 #endif
1909 /* s.getsockname() method */
1911 static PyObject *
1912 sock_getsockname(PySocketSockObject *s)
1914 sock_addr_t addrbuf;
1915 int res;
1916 socklen_t addrlen;
1918 if (!getsockaddrlen(s, &addrlen))
1919 return NULL;
1920 memset(&addrbuf, 0, addrlen);
1921 Py_BEGIN_ALLOW_THREADS
1922 res = getsockname(s->sock_fd, (struct sockaddr *) &addrbuf, &addrlen);
1923 Py_END_ALLOW_THREADS
1924 if (res < 0)
1925 return s->errorhandler();
1926 return makesockaddr(s->sock_fd, (struct sockaddr *) &addrbuf, addrlen,
1927 s->sock_proto);
1930 PyDoc_STRVAR(getsockname_doc,
1931 "getsockname() -> address info\n\
1933 Return the address of the local endpoint. For IP sockets, the address\n\
1934 info is a pair (hostaddr, port).");
1937 #ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
1938 /* s.getpeername() method */
1940 static PyObject *
1941 sock_getpeername(PySocketSockObject *s)
1943 sock_addr_t addrbuf;
1944 int res;
1945 socklen_t addrlen;
1947 if (!getsockaddrlen(s, &addrlen))
1948 return NULL;
1949 memset(&addrbuf, 0, addrlen);
1950 Py_BEGIN_ALLOW_THREADS
1951 res = getpeername(s->sock_fd, (struct sockaddr *) &addrbuf, &addrlen);
1952 Py_END_ALLOW_THREADS
1953 if (res < 0)
1954 return s->errorhandler();
1955 return makesockaddr(s->sock_fd, (struct sockaddr *) &addrbuf, addrlen,
1956 s->sock_proto);
1959 PyDoc_STRVAR(getpeername_doc,
1960 "getpeername() -> address info\n\
1962 Return the address of the remote endpoint. For IP sockets, the address\n\
1963 info is a pair (hostaddr, port).");
1965 #endif /* HAVE_GETPEERNAME */
1968 /* s.listen(n) method */
1970 static PyObject *
1971 sock_listen(PySocketSockObject *s, PyObject *arg)
1973 int backlog;
1974 int res;
1976 backlog = PyInt_AsLong(arg);
1977 if (backlog == -1 && PyErr_Occurred())
1978 return NULL;
1979 Py_BEGIN_ALLOW_THREADS
1980 if (backlog < 1)
1981 backlog = 1;
1982 res = listen(s->sock_fd, backlog);
1983 Py_END_ALLOW_THREADS
1984 if (res < 0)
1985 return s->errorhandler();
1986 Py_INCREF(Py_None);
1987 return Py_None;
1990 PyDoc_STRVAR(listen_doc,
1991 "listen(backlog)\n\
1993 Enable a server to accept connections. The backlog argument must be at\n\
1994 least 1; it specifies the number of unaccepted connection that the system\n\
1995 will allow before refusing new connections.");
1998 #ifndef NO_DUP
1999 /* s.makefile(mode) method.
2000 Create a new open file object referring to a dupped version of
2001 the socket's file descriptor. (The dup() call is necessary so
2002 that the open file and socket objects may be closed independent
2003 of each other.)
2004 The mode argument specifies 'r' or 'w' passed to fdopen(). */
2006 static PyObject *
2007 sock_makefile(PySocketSockObject *s, PyObject *args)
2009 extern int fclose(FILE *);
2010 char *mode = "r";
2011 int bufsize = -1;
2012 #ifdef MS_WIN32
2013 Py_intptr_t fd;
2014 #else
2015 int fd;
2016 #endif
2017 FILE *fp;
2018 PyObject *f;
2019 #ifdef __VMS
2020 char *mode_r = "r";
2021 char *mode_w = "w";
2022 #endif
2024 if (!PyArg_ParseTuple(args, "|si:makefile", &mode, &bufsize))
2025 return NULL;
2026 #ifdef __VMS
2027 if (strcmp(mode,"rb") == 0) {
2028 mode = mode_r;
2030 else {
2031 if (strcmp(mode,"wb") == 0) {
2032 mode = mode_w;
2035 #endif
2036 #ifdef MS_WIN32
2037 if (((fd = _open_osfhandle(s->sock_fd, _O_BINARY)) < 0) ||
2038 ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL))
2039 #else
2040 if ((fd = dup(s->sock_fd)) < 0 || (fp = fdopen(fd, mode)) == NULL)
2041 #endif
2043 if (fd >= 0)
2044 SOCKETCLOSE(fd);
2045 return s->errorhandler();
2047 f = PyFile_FromFile(fp, "<socket>", mode, fclose);
2048 if (f != NULL)
2049 PyFile_SetBufSize(f, bufsize);
2050 return f;
2053 PyDoc_STRVAR(makefile_doc,
2054 "makefile([mode[, buffersize]]) -> file object\n\
2056 Return a regular file object corresponding to the socket.\n\
2057 The mode and buffersize arguments are as for the built-in open() function.");
2059 #endif /* NO_DUP */
2062 /* s.recv(nbytes [,flags]) method */
2064 static PyObject *
2065 sock_recv(PySocketSockObject *s, PyObject *args)
2067 int len, n = 0, flags = 0, timeout;
2068 PyObject *buf;
2069 #ifdef __VMS
2070 int read_length;
2071 char *read_buf;
2072 #endif
2074 if (!PyArg_ParseTuple(args, "i|i:recv", &len, &flags))
2075 return NULL;
2077 if (len < 0) {
2078 PyErr_SetString(PyExc_ValueError,
2079 "negative buffersize in recv");
2080 return NULL;
2083 buf = PyString_FromStringAndSize((char *) 0, len);
2084 if (buf == NULL)
2085 return NULL;
2087 #ifndef __VMS
2088 Py_BEGIN_ALLOW_THREADS
2089 timeout = internal_select(s, 0);
2090 if (!timeout)
2091 n = recv(s->sock_fd, PyString_AS_STRING(buf), len, flags);
2092 Py_END_ALLOW_THREADS
2094 if (timeout) {
2095 Py_DECREF(buf);
2096 PyErr_SetString(socket_timeout, "timed out");
2097 return NULL;
2099 if (n < 0) {
2100 Py_DECREF(buf);
2101 return s->errorhandler();
2103 if (n != len)
2104 _PyString_Resize(&buf, n);
2105 #else
2106 read_buf = PyString_AsString(buf);
2107 read_length = len;
2108 while (read_length != 0) {
2109 unsigned int segment;
2111 segment = read_length /SEGMENT_SIZE;
2112 if (segment != 0) {
2113 segment = SEGMENT_SIZE;
2115 else {
2116 segment = read_length;
2119 Py_BEGIN_ALLOW_THREADS
2120 timeout = internal_select(s, 0);
2121 if (!timeout)
2122 n = recv(s->sock_fd, read_buf, segment, flags);
2123 Py_END_ALLOW_THREADS
2125 if (timeout) {
2126 Py_DECREF(buf);
2127 PyErr_SetString(socket_timeout, "timed out");
2128 return NULL;
2130 if (n < 0) {
2131 Py_DECREF(buf);
2132 return s->errorhandler();
2134 if (n != read_length) {
2135 read_buf += n;
2136 break;
2139 read_length -= segment;
2140 read_buf += segment;
2142 if (_PyString_Resize(&buf, (read_buf - PyString_AsString(buf))) < 0)
2144 return NULL;
2146 #endif /* !__VMS */
2147 return buf;
2150 PyDoc_STRVAR(recv_doc,
2151 "recv(buffersize[, flags]) -> data\n\
2153 Receive up to buffersize bytes from the socket. For the optional flags\n\
2154 argument, see the Unix manual. When no data is available, block until\n\
2155 at least one byte is available or until the remote end is closed. When\n\
2156 the remote end is closed and all data is read, return the empty string.");
2159 /* s.recvfrom(nbytes [,flags]) method */
2161 static PyObject *
2162 sock_recvfrom(PySocketSockObject *s, PyObject *args)
2164 sock_addr_t addrbuf;
2165 PyObject *buf = NULL;
2166 PyObject *addr = NULL;
2167 PyObject *ret = NULL;
2168 int len, n = 0, flags = 0, timeout;
2169 socklen_t addrlen;
2171 if (!PyArg_ParseTuple(args, "i|i:recvfrom", &len, &flags))
2172 return NULL;
2174 if (!getsockaddrlen(s, &addrlen))
2175 return NULL;
2176 buf = PyString_FromStringAndSize((char *) 0, len);
2177 if (buf == NULL)
2178 return NULL;
2180 Py_BEGIN_ALLOW_THREADS
2181 memset(&addrbuf, 0, addrlen);
2182 timeout = internal_select(s, 0);
2183 if (!timeout)
2184 n = recvfrom(s->sock_fd, PyString_AS_STRING(buf), len, flags,
2185 #ifndef MS_WINDOWS
2186 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
2187 (struct sockaddr *) &addrbuf, &addrlen
2188 #else
2189 (void *) &addrbuf, &addrlen
2190 #endif
2191 #else
2192 (struct sockaddr *) &addrbuf, &addrlen
2193 #endif
2195 Py_END_ALLOW_THREADS
2197 if (timeout) {
2198 Py_DECREF(buf);
2199 PyErr_SetString(socket_timeout, "timed out");
2200 return NULL;
2202 if (n < 0) {
2203 Py_DECREF(buf);
2204 return s->errorhandler();
2207 if (n != len && _PyString_Resize(&buf, n) < 0)
2208 return NULL;
2210 if (!(addr = makesockaddr(s->sock_fd, (struct sockaddr *) &addrbuf,
2211 addrlen, s->sock_proto)))
2212 goto finally;
2214 ret = PyTuple_Pack(2, buf, addr);
2216 finally:
2217 Py_XDECREF(addr);
2218 Py_XDECREF(buf);
2219 return ret;
2222 PyDoc_STRVAR(recvfrom_doc,
2223 "recvfrom(buffersize[, flags]) -> (data, address info)\n\
2225 Like recv(buffersize, flags) but also return the sender's address info.");
2227 /* s.send(data [,flags]) method */
2229 static PyObject *
2230 sock_send(PySocketSockObject *s, PyObject *args)
2232 char *buf;
2233 int len, n = 0, flags = 0, timeout;
2234 #ifdef __VMS
2235 int send_length;
2236 #endif
2238 if (!PyArg_ParseTuple(args, "s#|i:send", &buf, &len, &flags))
2239 return NULL;
2241 #ifndef __VMS
2242 Py_BEGIN_ALLOW_THREADS
2243 timeout = internal_select(s, 1);
2244 if (!timeout)
2245 n = send(s->sock_fd, buf, len, flags);
2246 Py_END_ALLOW_THREADS
2248 if (timeout) {
2249 PyErr_SetString(socket_timeout, "timed out");
2250 return NULL;
2252 if (n < 0)
2253 return s->errorhandler();
2254 #else
2255 /* Divide packet into smaller segments for */
2256 /* TCP/IP Services for OpenVMS */
2257 send_length = len;
2258 while (send_length != 0) {
2259 unsigned int segment;
2261 segment = send_length / SEGMENT_SIZE;
2262 if (segment != 0) {
2263 segment = SEGMENT_SIZE;
2265 else {
2266 segment = send_length;
2268 Py_BEGIN_ALLOW_THREADS
2269 timeout = internal_select(s, 1);
2270 if (!timeout)
2271 n = send(s->sock_fd, buf, segment, flags);
2272 Py_END_ALLOW_THREADS
2273 if (timeout) {
2274 PyErr_SetString(socket_timeout, "timed out");
2275 return NULL;
2277 if (n < 0) {
2278 return s->errorhandler();
2280 send_length -= segment;
2281 buf += segment;
2282 } /* end while */
2283 #endif /* !__VMS */
2284 return PyInt_FromLong((long)n);
2287 PyDoc_STRVAR(send_doc,
2288 "send(data[, flags]) -> count\n\
2290 Send a data string to the socket. For the optional flags\n\
2291 argument, see the Unix manual. Return the number of bytes\n\
2292 sent; this may be less than len(data) if the network is busy.");
2295 /* s.sendall(data [,flags]) method */
2297 static PyObject *
2298 sock_sendall(PySocketSockObject *s, PyObject *args)
2300 char *buf;
2301 int len, n = 0, flags = 0, timeout;
2303 if (!PyArg_ParseTuple(args, "s#|i:sendall", &buf, &len, &flags))
2304 return NULL;
2306 Py_BEGIN_ALLOW_THREADS
2307 do {
2308 timeout = internal_select(s, 1);
2309 if (timeout)
2310 break;
2311 n = send(s->sock_fd, buf, len, flags);
2312 if (n < 0)
2313 break;
2314 buf += n;
2315 len -= n;
2316 } while (len > 0);
2317 Py_END_ALLOW_THREADS
2319 if (timeout) {
2320 PyErr_SetString(socket_timeout, "timed out");
2321 return NULL;
2323 if (n < 0)
2324 return s->errorhandler();
2326 Py_INCREF(Py_None);
2327 return Py_None;
2330 PyDoc_STRVAR(sendall_doc,
2331 "sendall(data[, flags])\n\
2333 Send a data string to the socket. For the optional flags\n\
2334 argument, see the Unix manual. This calls send() repeatedly\n\
2335 until all data is sent. If an error occurs, it's impossible\n\
2336 to tell how much data has been sent.");
2339 /* s.sendto(data, [flags,] sockaddr) method */
2341 static PyObject *
2342 sock_sendto(PySocketSockObject *s, PyObject *args)
2344 PyObject *addro;
2345 char *buf;
2346 struct sockaddr *addr;
2347 int addrlen, len, n = 0, flags, timeout;
2349 flags = 0;
2350 if (!PyArg_ParseTuple(args, "s#O:sendto", &buf, &len, &addro)) {
2351 PyErr_Clear();
2352 if (!PyArg_ParseTuple(args, "s#iO:sendto",
2353 &buf, &len, &flags, &addro))
2354 return NULL;
2357 if (!getsockaddrarg(s, addro, &addr, &addrlen))
2358 return NULL;
2360 Py_BEGIN_ALLOW_THREADS
2361 timeout = internal_select(s, 1);
2362 if (!timeout)
2363 n = sendto(s->sock_fd, buf, len, flags, addr, addrlen);
2364 Py_END_ALLOW_THREADS
2366 if (timeout) {
2367 PyErr_SetString(socket_timeout, "timed out");
2368 return NULL;
2370 if (n < 0)
2371 return s->errorhandler();
2372 return PyInt_FromLong((long)n);
2375 PyDoc_STRVAR(sendto_doc,
2376 "sendto(data[, flags], address) -> count\n\
2378 Like send(data, flags) but allows specifying the destination address.\n\
2379 For IP sockets, the address is a pair (hostaddr, port).");
2382 /* s.shutdown(how) method */
2384 static PyObject *
2385 sock_shutdown(PySocketSockObject *s, PyObject *arg)
2387 int how;
2388 int res;
2390 how = PyInt_AsLong(arg);
2391 if (how == -1 && PyErr_Occurred())
2392 return NULL;
2393 Py_BEGIN_ALLOW_THREADS
2394 res = shutdown(s->sock_fd, how);
2395 Py_END_ALLOW_THREADS
2396 if (res < 0)
2397 return s->errorhandler();
2398 Py_INCREF(Py_None);
2399 return Py_None;
2402 PyDoc_STRVAR(shutdown_doc,
2403 "shutdown(flag)\n\
2405 Shut down the reading side of the socket (flag == SHUT_RD), the writing side\n\
2406 of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).");
2409 /* List of methods for socket objects */
2411 static PyMethodDef sock_methods[] = {
2412 {"accept", (PyCFunction)sock_accept, METH_NOARGS,
2413 accept_doc},
2414 {"bind", (PyCFunction)sock_bind, METH_O,
2415 bind_doc},
2416 {"close", (PyCFunction)sock_close, METH_NOARGS,
2417 close_doc},
2418 {"connect", (PyCFunction)sock_connect, METH_O,
2419 connect_doc},
2420 {"connect_ex", (PyCFunction)sock_connect_ex, METH_O,
2421 connect_ex_doc},
2422 #ifndef NO_DUP
2423 {"dup", (PyCFunction)sock_dup, METH_NOARGS,
2424 dup_doc},
2425 #endif
2426 {"fileno", (PyCFunction)sock_fileno, METH_NOARGS,
2427 fileno_doc},
2428 #ifdef HAVE_GETPEERNAME
2429 {"getpeername", (PyCFunction)sock_getpeername,
2430 METH_NOARGS, getpeername_doc},
2431 #endif
2432 {"getsockname", (PyCFunction)sock_getsockname,
2433 METH_NOARGS, getsockname_doc},
2434 {"getsockopt", (PyCFunction)sock_getsockopt, METH_VARARGS,
2435 getsockopt_doc},
2436 {"listen", (PyCFunction)sock_listen, METH_O,
2437 listen_doc},
2438 #ifndef NO_DUP
2439 {"makefile", (PyCFunction)sock_makefile, METH_VARARGS,
2440 makefile_doc},
2441 #endif
2442 {"recv", (PyCFunction)sock_recv, METH_VARARGS,
2443 recv_doc},
2444 {"recvfrom", (PyCFunction)sock_recvfrom, METH_VARARGS,
2445 recvfrom_doc},
2446 {"send", (PyCFunction)sock_send, METH_VARARGS,
2447 send_doc},
2448 {"sendall", (PyCFunction)sock_sendall, METH_VARARGS,
2449 sendall_doc},
2450 {"sendto", (PyCFunction)sock_sendto, METH_VARARGS,
2451 sendto_doc},
2452 {"setblocking", (PyCFunction)sock_setblocking, METH_O,
2453 setblocking_doc},
2454 {"settimeout", (PyCFunction)sock_settimeout, METH_O,
2455 settimeout_doc},
2456 {"gettimeout", (PyCFunction)sock_gettimeout, METH_NOARGS,
2457 gettimeout_doc},
2458 {"setsockopt", (PyCFunction)sock_setsockopt, METH_VARARGS,
2459 setsockopt_doc},
2460 {"shutdown", (PyCFunction)sock_shutdown, METH_O,
2461 shutdown_doc},
2462 #ifdef RISCOS
2463 {"sleeptaskw", (PyCFunction)sock_sleeptaskw, METH_O,
2464 sleeptaskw_doc},
2465 #endif
2466 {NULL, NULL} /* sentinel */
2470 /* Deallocate a socket object in response to the last Py_DECREF().
2471 First close the file description. */
2473 static void
2474 sock_dealloc(PySocketSockObject *s)
2476 if (s->sock_fd != -1)
2477 (void) SOCKETCLOSE(s->sock_fd);
2478 s->ob_type->tp_free((PyObject *)s);
2482 static PyObject *
2483 sock_repr(PySocketSockObject *s)
2485 char buf[512];
2486 #if SIZEOF_SOCKET_T > SIZEOF_LONG
2487 if (s->sock_fd > LONG_MAX) {
2488 /* this can occur on Win64, and actually there is a special
2489 ugly printf formatter for decimal pointer length integer
2490 printing, only bother if necessary*/
2491 PyErr_SetString(PyExc_OverflowError,
2492 "no printf formatter to display "
2493 "the socket descriptor in decimal");
2494 return NULL;
2496 #endif
2497 PyOS_snprintf(
2498 buf, sizeof(buf),
2499 "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
2500 (long)s->sock_fd, s->sock_family,
2501 s->sock_type,
2502 s->sock_proto);
2503 return PyString_FromString(buf);
2507 /* Create a new, uninitialized socket object. */
2509 static PyObject *
2510 sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2512 PyObject *new;
2514 new = type->tp_alloc(type, 0);
2515 if (new != NULL) {
2516 ((PySocketSockObject *)new)->sock_fd = -1;
2517 ((PySocketSockObject *)new)->sock_timeout = -1.0;
2518 ((PySocketSockObject *)new)->errorhandler = &set_error;
2520 return new;
2524 /* Initialize a new socket object. */
2526 /*ARGSUSED*/
2527 static int
2528 sock_initobj(PyObject *self, PyObject *args, PyObject *kwds)
2530 PySocketSockObject *s = (PySocketSockObject *)self;
2531 SOCKET_T fd;
2532 int family = AF_INET, type = SOCK_STREAM, proto = 0;
2533 static const char *keywords[] = {"family", "type", "proto", 0};
2535 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2536 "|iii:socket", keywords,
2537 &family, &type, &proto))
2538 return -1;
2540 Py_BEGIN_ALLOW_THREADS
2541 fd = socket(family, type, proto);
2542 Py_END_ALLOW_THREADS
2544 #ifdef MS_WINDOWS
2545 if (fd == INVALID_SOCKET)
2546 #else
2547 if (fd < 0)
2548 #endif
2550 set_error();
2551 return -1;
2553 init_sockobject(s, fd, family, type, proto);
2555 return 0;
2560 /* Type object for socket objects. */
2562 static PyTypeObject sock_type = {
2563 PyObject_HEAD_INIT(0) /* Must fill in type value later */
2564 0, /* ob_size */
2565 "_socket.socket", /* tp_name */
2566 sizeof(PySocketSockObject), /* tp_basicsize */
2567 0, /* tp_itemsize */
2568 (destructor)sock_dealloc, /* tp_dealloc */
2569 0, /* tp_print */
2570 0, /* tp_getattr */
2571 0, /* tp_setattr */
2572 0, /* tp_compare */
2573 (reprfunc)sock_repr, /* tp_repr */
2574 0, /* tp_as_number */
2575 0, /* tp_as_sequence */
2576 0, /* tp_as_mapping */
2577 0, /* tp_hash */
2578 0, /* tp_call */
2579 0, /* tp_str */
2580 PyObject_GenericGetAttr, /* tp_getattro */
2581 0, /* tp_setattro */
2582 0, /* tp_as_buffer */
2583 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2584 sock_doc, /* tp_doc */
2585 0, /* tp_traverse */
2586 0, /* tp_clear */
2587 0, /* tp_richcompare */
2588 0, /* tp_weaklistoffset */
2589 0, /* tp_iter */
2590 0, /* tp_iternext */
2591 sock_methods, /* tp_methods */
2592 0, /* tp_members */
2593 0, /* tp_getset */
2594 0, /* tp_base */
2595 0, /* tp_dict */
2596 0, /* tp_descr_get */
2597 0, /* tp_descr_set */
2598 0, /* tp_dictoffset */
2599 sock_initobj, /* tp_init */
2600 PyType_GenericAlloc, /* tp_alloc */
2601 sock_new, /* tp_new */
2602 PyObject_Del, /* tp_free */
2606 /* Python interface to gethostname(). */
2608 /*ARGSUSED*/
2609 static PyObject *
2610 socket_gethostname(PyObject *self, PyObject *args)
2612 char buf[1024];
2613 int res;
2614 if (!PyArg_ParseTuple(args, ":gethostname"))
2615 return NULL;
2616 Py_BEGIN_ALLOW_THREADS
2617 res = gethostname(buf, (int) sizeof buf - 1);
2618 Py_END_ALLOW_THREADS
2619 if (res < 0)
2620 return set_error();
2621 buf[sizeof buf - 1] = '\0';
2622 return PyString_FromString(buf);
2625 PyDoc_STRVAR(gethostname_doc,
2626 "gethostname() -> string\n\
2628 Return the current host name.");
2631 /* Python interface to gethostbyname(name). */
2633 /*ARGSUSED*/
2634 static PyObject *
2635 socket_gethostbyname(PyObject *self, PyObject *args)
2637 char *name;
2638 sock_addr_t addrbuf;
2640 if (!PyArg_ParseTuple(args, "s:gethostbyname", &name))
2641 return NULL;
2642 if (setipaddr(name, (struct sockaddr *)&addrbuf, sizeof(addrbuf), AF_INET) < 0)
2643 return NULL;
2644 return makeipaddr((struct sockaddr *)&addrbuf,
2645 sizeof(struct sockaddr_in));
2648 PyDoc_STRVAR(gethostbyname_doc,
2649 "gethostbyname(host) -> address\n\
2651 Return the IP address (a string of the form '255.255.255.255') for a host.");
2654 /* Convenience function common to gethostbyname_ex and gethostbyaddr */
2656 static PyObject *
2657 gethost_common(struct hostent *h, struct sockaddr *addr, int alen, int af)
2659 char **pch;
2660 PyObject *rtn_tuple = (PyObject *)NULL;
2661 PyObject *name_list = (PyObject *)NULL;
2662 PyObject *addr_list = (PyObject *)NULL;
2663 PyObject *tmp;
2665 if (h == NULL) {
2666 /* Let's get real error message to return */
2667 #ifndef RISCOS
2668 set_herror(h_errno);
2669 #else
2670 PyErr_SetString(socket_error, "host not found");
2671 #endif
2672 return NULL;
2675 if (h->h_addrtype != af) {
2676 #ifdef HAVE_STRERROR
2677 /* Let's get real error message to return */
2678 PyErr_SetString(socket_error,
2679 (char *)strerror(EAFNOSUPPORT));
2680 #else
2681 PyErr_SetString(
2682 socket_error,
2683 "Address family not supported by protocol family");
2684 #endif
2685 return NULL;
2688 switch (af) {
2690 case AF_INET:
2691 if (alen < sizeof(struct sockaddr_in))
2692 return NULL;
2693 break;
2695 #ifdef ENABLE_IPV6
2696 case AF_INET6:
2697 if (alen < sizeof(struct sockaddr_in6))
2698 return NULL;
2699 break;
2700 #endif
2704 if ((name_list = PyList_New(0)) == NULL)
2705 goto err;
2707 if ((addr_list = PyList_New(0)) == NULL)
2708 goto err;
2710 for (pch = h->h_aliases; *pch != NULL; pch++) {
2711 int status;
2712 tmp = PyString_FromString(*pch);
2713 if (tmp == NULL)
2714 goto err;
2716 status = PyList_Append(name_list, tmp);
2717 Py_DECREF(tmp);
2719 if (status)
2720 goto err;
2723 for (pch = h->h_addr_list; *pch != NULL; pch++) {
2724 int status;
2726 switch (af) {
2728 case AF_INET:
2730 struct sockaddr_in sin;
2731 memset(&sin, 0, sizeof(sin));
2732 sin.sin_family = af;
2733 #ifdef HAVE_SOCKADDR_SA_LEN
2734 sin.sin_len = sizeof(sin);
2735 #endif
2736 memcpy(&sin.sin_addr, *pch, sizeof(sin.sin_addr));
2737 tmp = makeipaddr((struct sockaddr *)&sin, sizeof(sin));
2739 if (pch == h->h_addr_list && alen >= sizeof(sin))
2740 memcpy((char *) addr, &sin, sizeof(sin));
2741 break;
2744 #ifdef ENABLE_IPV6
2745 case AF_INET6:
2747 struct sockaddr_in6 sin6;
2748 memset(&sin6, 0, sizeof(sin6));
2749 sin6.sin6_family = af;
2750 #ifdef HAVE_SOCKADDR_SA_LEN
2751 sin6.sin6_len = sizeof(sin6);
2752 #endif
2753 memcpy(&sin6.sin6_addr, *pch, sizeof(sin6.sin6_addr));
2754 tmp = makeipaddr((struct sockaddr *)&sin6,
2755 sizeof(sin6));
2757 if (pch == h->h_addr_list && alen >= sizeof(sin6))
2758 memcpy((char *) addr, &sin6, sizeof(sin6));
2759 break;
2761 #endif
2763 default: /* can't happen */
2764 PyErr_SetString(socket_error,
2765 "unsupported address family");
2766 return NULL;
2769 if (tmp == NULL)
2770 goto err;
2772 status = PyList_Append(addr_list, tmp);
2773 Py_DECREF(tmp);
2775 if (status)
2776 goto err;
2779 rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list);
2781 err:
2782 Py_XDECREF(name_list);
2783 Py_XDECREF(addr_list);
2784 return rtn_tuple;
2788 /* Python interface to gethostbyname_ex(name). */
2790 /*ARGSUSED*/
2791 static PyObject *
2792 socket_gethostbyname_ex(PyObject *self, PyObject *args)
2794 char *name;
2795 struct hostent *h;
2796 #ifdef ENABLE_IPV6
2797 struct sockaddr_storage addr;
2798 #else
2799 struct sockaddr_in addr;
2800 #endif
2801 struct sockaddr *sa;
2802 PyObject *ret;
2803 #ifdef HAVE_GETHOSTBYNAME_R
2804 struct hostent hp_allocated;
2805 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
2806 struct hostent_data data;
2807 #else
2808 char buf[16384];
2809 int buf_len = (sizeof buf) - 1;
2810 int errnop;
2811 #endif
2812 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2813 int result;
2814 #endif
2815 #endif /* HAVE_GETHOSTBYNAME_R */
2817 if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name))
2818 return NULL;
2819 if (setipaddr(name, (struct sockaddr *)&addr, sizeof(addr), AF_INET) < 0)
2820 return NULL;
2821 Py_BEGIN_ALLOW_THREADS
2822 #ifdef HAVE_GETHOSTBYNAME_R
2823 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2824 result = gethostbyname_r(name, &hp_allocated, buf, buf_len,
2825 &h, &errnop);
2826 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
2827 h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
2828 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
2829 memset((void *) &data, '\0', sizeof(data));
2830 result = gethostbyname_r(name, &hp_allocated, &data);
2831 h = (result != 0) ? NULL : &hp_allocated;
2832 #endif
2833 #else /* not HAVE_GETHOSTBYNAME_R */
2834 #ifdef USE_GETHOSTBYNAME_LOCK
2835 PyThread_acquire_lock(netdb_lock, 1);
2836 #endif
2837 h = gethostbyname(name);
2838 #endif /* HAVE_GETHOSTBYNAME_R */
2839 Py_END_ALLOW_THREADS
2840 /* Some C libraries would require addr.__ss_family instead of
2841 addr.ss_family.
2842 Therefore, we cast the sockaddr_storage into sockaddr to
2843 access sa_family. */
2844 sa = (struct sockaddr*)&addr;
2845 ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr),
2846 sa->sa_family);
2847 #ifdef USE_GETHOSTBYNAME_LOCK
2848 PyThread_release_lock(netdb_lock);
2849 #endif
2850 return ret;
2853 PyDoc_STRVAR(ghbn_ex_doc,
2854 "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
2856 Return the true host name, a list of aliases, and a list of IP addresses,\n\
2857 for a host. The host argument is a string giving a host name or IP number.");
2860 /* Python interface to gethostbyaddr(IP). */
2862 /*ARGSUSED*/
2863 static PyObject *
2864 socket_gethostbyaddr(PyObject *self, PyObject *args)
2866 #ifdef ENABLE_IPV6
2867 struct sockaddr_storage addr;
2868 #else
2869 struct sockaddr_in addr;
2870 #endif
2871 struct sockaddr *sa = (struct sockaddr *)&addr;
2872 char *ip_num;
2873 struct hostent *h;
2874 PyObject *ret;
2875 #ifdef HAVE_GETHOSTBYNAME_R
2876 struct hostent hp_allocated;
2877 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
2878 struct hostent_data data;
2879 #else
2880 char buf[16384];
2881 int buf_len = (sizeof buf) - 1;
2882 int errnop;
2883 #endif
2884 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2885 int result;
2886 #endif
2887 #endif /* HAVE_GETHOSTBYNAME_R */
2888 char *ap;
2889 int al;
2890 int af;
2892 if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num))
2893 return NULL;
2894 af = AF_UNSPEC;
2895 if (setipaddr(ip_num, sa, sizeof(addr), af) < 0)
2896 return NULL;
2897 af = sa->sa_family;
2898 ap = NULL;
2899 al = 0;
2900 switch (af) {
2901 case AF_INET:
2902 ap = (char *)&((struct sockaddr_in *)sa)->sin_addr;
2903 al = sizeof(((struct sockaddr_in *)sa)->sin_addr);
2904 break;
2905 #ifdef ENABLE_IPV6
2906 case AF_INET6:
2907 ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr;
2908 al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr);
2909 break;
2910 #endif
2911 default:
2912 PyErr_SetString(socket_error, "unsupported address family");
2913 return NULL;
2915 Py_BEGIN_ALLOW_THREADS
2916 #ifdef HAVE_GETHOSTBYNAME_R
2917 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2918 result = gethostbyaddr_r(ap, al, af,
2919 &hp_allocated, buf, buf_len,
2920 &h, &errnop);
2921 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
2922 h = gethostbyaddr_r(ap, al, af,
2923 &hp_allocated, buf, buf_len, &errnop);
2924 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
2925 memset((void *) &data, '\0', sizeof(data));
2926 result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data);
2927 h = (result != 0) ? NULL : &hp_allocated;
2928 #endif
2929 #else /* not HAVE_GETHOSTBYNAME_R */
2930 #ifdef USE_GETHOSTBYNAME_LOCK
2931 PyThread_acquire_lock(netdb_lock, 1);
2932 #endif
2933 h = gethostbyaddr(ap, al, af);
2934 #endif /* HAVE_GETHOSTBYNAME_R */
2935 Py_END_ALLOW_THREADS
2936 ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), af);
2937 #ifdef USE_GETHOSTBYNAME_LOCK
2938 PyThread_release_lock(netdb_lock);
2939 #endif
2940 return ret;
2943 PyDoc_STRVAR(gethostbyaddr_doc,
2944 "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
2946 Return the true host name, a list of aliases, and a list of IP addresses,\n\
2947 for a host. The host argument is a string giving a host name or IP number.");
2950 /* Python interface to getservbyname(name).
2951 This only returns the port number, since the other info is already
2952 known or not useful (like the list of aliases). */
2954 /*ARGSUSED*/
2955 static PyObject *
2956 socket_getservbyname(PyObject *self, PyObject *args)
2958 char *name, *proto=NULL;
2959 struct servent *sp;
2960 if (!PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto))
2961 return NULL;
2962 Py_BEGIN_ALLOW_THREADS
2963 sp = getservbyname(name, proto);
2964 Py_END_ALLOW_THREADS
2965 if (sp == NULL) {
2966 PyErr_SetString(socket_error, "service/proto not found");
2967 return NULL;
2969 return PyInt_FromLong((long) ntohs(sp->s_port));
2972 PyDoc_STRVAR(getservbyname_doc,
2973 "getservbyname(servicename[, protocolname]) -> integer\n\
2975 Return a port number from a service name and protocol name.\n\
2976 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
2977 otherwise any protocol will match.");
2980 /* Python interface to getservbyport(port).
2981 This only returns the service name, since the other info is already
2982 known or not useful (like the list of aliases). */
2984 /*ARGSUSED*/
2985 static PyObject *
2986 socket_getservbyport(PyObject *self, PyObject *args)
2988 unsigned short port;
2989 char *proto=NULL;
2990 struct servent *sp;
2991 if (!PyArg_ParseTuple(args, "H|s:getservbyport", &port, &proto))
2992 return NULL;
2993 Py_BEGIN_ALLOW_THREADS
2994 sp = getservbyport(htons(port), proto);
2995 Py_END_ALLOW_THREADS
2996 if (sp == NULL) {
2997 PyErr_SetString(socket_error, "port/proto not found");
2998 return NULL;
3000 return PyString_FromString(sp->s_name);
3003 PyDoc_STRVAR(getservbyport_doc,
3004 "getservbyport(port[, protocolname]) -> string\n\
3006 Return the service name from a port number and protocol name.\n\
3007 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3008 otherwise any protocol will match.");
3010 /* Python interface to getprotobyname(name).
3011 This only returns the protocol number, since the other info is
3012 already known or not useful (like the list of aliases). */
3014 /*ARGSUSED*/
3015 static PyObject *
3016 socket_getprotobyname(PyObject *self, PyObject *args)
3018 char *name;
3019 struct protoent *sp;
3020 #ifdef __BEOS__
3021 /* Not available in BeOS yet. - [cjh] */
3022 PyErr_SetString(socket_error, "getprotobyname not supported");
3023 return NULL;
3024 #else
3025 if (!PyArg_ParseTuple(args, "s:getprotobyname", &name))
3026 return NULL;
3027 Py_BEGIN_ALLOW_THREADS
3028 sp = getprotobyname(name);
3029 Py_END_ALLOW_THREADS
3030 if (sp == NULL) {
3031 PyErr_SetString(socket_error, "protocol not found");
3032 return NULL;
3034 return PyInt_FromLong((long) sp->p_proto);
3035 #endif
3038 PyDoc_STRVAR(getprotobyname_doc,
3039 "getprotobyname(name) -> integer\n\
3041 Return the protocol number for the named protocol. (Rarely used.)");
3044 #ifdef HAVE_SOCKETPAIR
3045 /* Create a pair of sockets using the socketpair() function.
3046 Arguments as for socket() except the default family is AF_UNIX if
3047 defined on the platform; otherwise, the default is AF_INET. */
3049 /*ARGSUSED*/
3050 static PyObject *
3051 socket_socketpair(PyObject *self, PyObject *args)
3053 PySocketSockObject *s0 = NULL, *s1 = NULL;
3054 SOCKET_T sv[2];
3055 int family, type = SOCK_STREAM, proto = 0;
3056 PyObject *res = NULL;
3058 #if defined(AF_UNIX)
3059 family = AF_UNIX;
3060 #else
3061 family = AF_INET;
3062 #endif
3063 if (!PyArg_ParseTuple(args, "|iii:socketpair",
3064 &family, &type, &proto))
3065 return NULL;
3066 /* Create a pair of socket fds */
3067 if (socketpair(family, type, proto, sv) < 0)
3068 return set_error();
3069 s0 = new_sockobject(sv[0], family, type, proto);
3070 if (s0 == NULL)
3071 goto finally;
3072 s1 = new_sockobject(sv[1], family, type, proto);
3073 if (s1 == NULL)
3074 goto finally;
3075 res = PyTuple_Pack(2, s0, s1);
3077 finally:
3078 if (res == NULL) {
3079 if (s0 == NULL)
3080 SOCKETCLOSE(sv[0]);
3081 if (s1 == NULL)
3082 SOCKETCLOSE(sv[1]);
3084 Py_XDECREF(s0);
3085 Py_XDECREF(s1);
3086 return res;
3089 PyDoc_STRVAR(socketpair_doc,
3090 "socketpair([family[, type[, proto]]]) -> (socket object, socket object)\n\
3092 Create a pair of socket objects from the sockets returned by the platform\n\
3093 socketpair() function.\n\
3094 The arguments are the same as for socket() except the default family is\n\
3095 AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");
3097 #endif /* HAVE_SOCKETPAIR */
3100 #ifndef NO_DUP
3101 /* Create a socket object from a numeric file description.
3102 Useful e.g. if stdin is a socket.
3103 Additional arguments as for socket(). */
3105 /*ARGSUSED*/
3106 static PyObject *
3107 socket_fromfd(PyObject *self, PyObject *args)
3109 PySocketSockObject *s;
3110 SOCKET_T fd;
3111 int family, type, proto = 0;
3112 if (!PyArg_ParseTuple(args, "iii|i:fromfd",
3113 &fd, &family, &type, &proto))
3114 return NULL;
3115 /* Dup the fd so it and the socket can be closed independently */
3116 fd = dup(fd);
3117 if (fd < 0)
3118 return set_error();
3119 s = new_sockobject(fd, family, type, proto);
3120 return (PyObject *) s;
3123 PyDoc_STRVAR(fromfd_doc,
3124 "fromfd(fd, family, type[, proto]) -> socket object\n\
3126 Create a socket object from the given file descriptor.\n\
3127 The remaining arguments are the same as for socket().");
3129 #endif /* NO_DUP */
3132 static PyObject *
3133 socket_ntohs(PyObject *self, PyObject *args)
3135 int x1, x2;
3137 if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) {
3138 return NULL;
3140 x2 = (int)ntohs((short)x1);
3141 return PyInt_FromLong(x2);
3144 PyDoc_STRVAR(ntohs_doc,
3145 "ntohs(integer) -> integer\n\
3147 Convert a 16-bit integer from network to host byte order.");
3150 static PyObject *
3151 socket_ntohl(PyObject *self, PyObject *arg)
3153 unsigned long x;
3155 if (PyInt_Check(arg)) {
3156 x = PyInt_AS_LONG(arg);
3157 if (x == (unsigned long) -1 && PyErr_Occurred())
3158 return NULL;
3160 else if (PyLong_Check(arg)) {
3161 x = PyLong_AsUnsignedLong(arg);
3162 if (x == (unsigned long) -1 && PyErr_Occurred())
3163 return NULL;
3164 #if SIZEOF_LONG > 4
3166 unsigned long y;
3167 /* only want the trailing 32 bits */
3168 y = x & 0xFFFFFFFFUL;
3169 if (y ^ x)
3170 return PyErr_Format(PyExc_OverflowError,
3171 "long int larger than 32 bits");
3172 x = y;
3174 #endif
3176 else
3177 return PyErr_Format(PyExc_TypeError,
3178 "expected int/long, %s found",
3179 arg->ob_type->tp_name);
3180 if (x == (unsigned long) -1 && PyErr_Occurred())
3181 return NULL;
3182 return PyInt_FromLong(ntohl(x));
3185 PyDoc_STRVAR(ntohl_doc,
3186 "ntohl(integer) -> integer\n\
3188 Convert a 32-bit integer from network to host byte order.");
3191 static PyObject *
3192 socket_htons(PyObject *self, PyObject *args)
3194 int x1, x2;
3196 if (!PyArg_ParseTuple(args, "i:htons", &x1)) {
3197 return NULL;
3199 x2 = (int)htons((short)x1);
3200 return PyInt_FromLong(x2);
3203 PyDoc_STRVAR(htons_doc,
3204 "htons(integer) -> integer\n\
3206 Convert a 16-bit integer from host to network byte order.");
3209 static PyObject *
3210 socket_htonl(PyObject *self, PyObject *arg)
3212 unsigned long x;
3214 if (PyInt_Check(arg)) {
3215 x = PyInt_AS_LONG(arg);
3216 if (x == (unsigned long) -1 && PyErr_Occurred())
3217 return NULL;
3219 else if (PyLong_Check(arg)) {
3220 x = PyLong_AsUnsignedLong(arg);
3221 if (x == (unsigned long) -1 && PyErr_Occurred())
3222 return NULL;
3223 #if SIZEOF_LONG > 4
3225 unsigned long y;
3226 /* only want the trailing 32 bits */
3227 y = x & 0xFFFFFFFFUL;
3228 if (y ^ x)
3229 return PyErr_Format(PyExc_OverflowError,
3230 "long int larger than 32 bits");
3231 x = y;
3233 #endif
3235 else
3236 return PyErr_Format(PyExc_TypeError,
3237 "expected int/long, %s found",
3238 arg->ob_type->tp_name);
3239 return PyInt_FromLong(htonl(x));
3242 PyDoc_STRVAR(htonl_doc,
3243 "htonl(integer) -> integer\n\
3245 Convert a 32-bit integer from host to network byte order.");
3247 /* socket.inet_aton() and socket.inet_ntoa() functions. */
3249 PyDoc_STRVAR(inet_aton_doc,
3250 "inet_aton(string) -> packed 32-bit IP representation\n\
3252 Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
3253 binary format used in low-level network functions.");
3255 static PyObject*
3256 socket_inet_aton(PyObject *self, PyObject *args)
3258 #ifndef INADDR_NONE
3259 #define INADDR_NONE (-1)
3260 #endif
3261 #ifdef HAVE_INET_ATON
3262 struct in_addr buf;
3263 #else
3264 /* Have to use inet_addr() instead */
3265 unsigned long packed_addr;
3266 #endif
3267 char *ip_addr;
3269 if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr))
3270 return NULL;
3273 #ifdef HAVE_INET_ATON
3274 if (inet_aton(ip_addr, &buf))
3275 return PyString_FromStringAndSize((char *)(&buf),
3276 sizeof(buf));
3278 PyErr_SetString(socket_error,
3279 "illegal IP address string passed to inet_aton");
3280 return NULL;
3282 #else /* ! HAVE_INET_ATON */
3283 /* special-case this address as inet_addr might return INADDR_NONE
3284 * for this */
3285 if (strcmp(ip_addr, "255.255.255.255") == 0) {
3286 packed_addr = 0xFFFFFFFF;
3287 } else {
3289 packed_addr = inet_addr(ip_addr);
3291 if (packed_addr == INADDR_NONE) { /* invalid address */
3292 PyErr_SetString(socket_error,
3293 "illegal IP address string passed to inet_aton");
3294 return NULL;
3297 return PyString_FromStringAndSize((char *) &packed_addr,
3298 sizeof(packed_addr));
3299 #endif
3302 PyDoc_STRVAR(inet_ntoa_doc,
3303 "inet_ntoa(packed_ip) -> ip_address_string\n\
3305 Convert an IP address from 32-bit packed binary format to string format");
3307 static PyObject*
3308 socket_inet_ntoa(PyObject *self, PyObject *args)
3310 char *packed_str;
3311 int addr_len;
3312 struct in_addr packed_addr;
3314 if (!PyArg_ParseTuple(args, "s#:inet_ntoa", &packed_str, &addr_len)) {
3315 return NULL;
3318 if (addr_len != sizeof(packed_addr)) {
3319 PyErr_SetString(socket_error,
3320 "packed IP wrong length for inet_ntoa");
3321 return NULL;
3324 memcpy(&packed_addr, packed_str, addr_len);
3326 return PyString_FromString(inet_ntoa(packed_addr));
3329 #ifdef HAVE_INET_PTON
3331 PyDoc_STRVAR(inet_pton_doc,
3332 "inet_pton(af, ip) -> packed IP address string\n\
3334 Convert an IP address from string format to a packed string suitable\n\
3335 for use with low-level network functions.");
3337 static PyObject *
3338 socket_inet_pton(PyObject *self, PyObject *args)
3340 int af;
3341 char* ip;
3342 int retval;
3343 #ifdef ENABLE_IPV6
3344 char packed[MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
3345 #else
3346 char packed[sizeof(struct in_addr)];
3347 #endif
3348 if (!PyArg_ParseTuple(args, "is:inet_pton", &af, &ip)) {
3349 return NULL;
3352 #if !defined(ENABLE_IPV6) && defined(AF_INET6)
3353 if(af == AF_INET6) {
3354 PyErr_SetString(socket_error,
3355 "can't use AF_INET6, IPv6 is disabled");
3356 return NULL;
3358 #endif
3360 retval = inet_pton(af, ip, packed);
3361 if (retval < 0) {
3362 PyErr_SetFromErrno(socket_error);
3363 return NULL;
3364 } else if (retval == 0) {
3365 PyErr_SetString(socket_error,
3366 "illegal IP address string passed to inet_pton");
3367 return NULL;
3368 } else if (af == AF_INET) {
3369 return PyString_FromStringAndSize(packed,
3370 sizeof(struct in_addr));
3371 #ifdef ENABLE_IPV6
3372 } else if (af == AF_INET6) {
3373 return PyString_FromStringAndSize(packed,
3374 sizeof(struct in6_addr));
3375 #endif
3376 } else {
3377 PyErr_SetString(socket_error, "unknown address family");
3378 return NULL;
3382 PyDoc_STRVAR(inet_ntop_doc,
3383 "inet_ntop(af, packed_ip) -> string formatted IP address\n\
3385 Convert a packed IP address of the given family to string format.");
3387 static PyObject *
3388 socket_inet_ntop(PyObject *self, PyObject *args)
3390 int af;
3391 char* packed;
3392 int len;
3393 const char* retval;
3394 #ifdef ENABLE_IPV6
3395 char ip[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) + 1];
3396 #else
3397 char ip[INET_ADDRSTRLEN + 1];
3398 #endif
3400 /* Guarantee NUL-termination for PyString_FromString() below */
3401 memset((void *) &ip[0], '\0', sizeof(ip));
3403 if (!PyArg_ParseTuple(args, "is#:inet_ntop", &af, &packed, &len)) {
3404 return NULL;
3407 if (af == AF_INET) {
3408 if (len != sizeof(struct in_addr)) {
3409 PyErr_SetString(PyExc_ValueError,
3410 "invalid length of packed IP address string");
3411 return NULL;
3413 #ifdef ENABLE_IPV6
3414 } else if (af == AF_INET6) {
3415 if (len != sizeof(struct in6_addr)) {
3416 PyErr_SetString(PyExc_ValueError,
3417 "invalid length of packed IP address string");
3418 return NULL;
3420 #endif
3421 } else {
3422 PyErr_Format(PyExc_ValueError,
3423 "unknown address family %d", af);
3424 return NULL;
3427 retval = inet_ntop(af, packed, ip, sizeof(ip));
3428 if (!retval) {
3429 PyErr_SetFromErrno(socket_error);
3430 return NULL;
3431 } else {
3432 return PyString_FromString(retval);
3435 /* NOTREACHED */
3436 PyErr_SetString(PyExc_RuntimeError, "invalid handling of inet_ntop");
3437 return NULL;
3440 #endif /* HAVE_INET_PTON */
3442 /* Python interface to getaddrinfo(host, port). */
3444 /*ARGSUSED*/
3445 static PyObject *
3446 socket_getaddrinfo(PyObject *self, PyObject *args)
3448 struct addrinfo hints, *res;
3449 struct addrinfo *res0 = NULL;
3450 PyObject *hobj = NULL;
3451 PyObject *pobj = (PyObject *)NULL;
3452 char pbuf[30];
3453 char *hptr, *pptr;
3454 int family, socktype, protocol, flags;
3455 int error;
3456 PyObject *all = (PyObject *)NULL;
3457 PyObject *single = (PyObject *)NULL;
3458 PyObject *idna = NULL;
3460 family = socktype = protocol = flags = 0;
3461 family = AF_UNSPEC;
3462 if (!PyArg_ParseTuple(args, "OO|iiii:getaddrinfo",
3463 &hobj, &pobj, &family, &socktype,
3464 &protocol, &flags)) {
3465 return NULL;
3467 if (hobj == Py_None) {
3468 hptr = NULL;
3469 } else if (PyUnicode_Check(hobj)) {
3470 idna = PyObject_CallMethod(hobj, "encode", "s", "idna");
3471 if (!idna)
3472 return NULL;
3473 hptr = PyString_AsString(idna);
3474 } else if (PyString_Check(hobj)) {
3475 hptr = PyString_AsString(hobj);
3476 } else {
3477 PyErr_SetString(PyExc_TypeError,
3478 "getaddrinfo() argument 1 must be string or None");
3479 return NULL;
3481 if (PyInt_Check(pobj)) {
3482 PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", PyInt_AsLong(pobj));
3483 pptr = pbuf;
3484 } else if (PyString_Check(pobj)) {
3485 pptr = PyString_AsString(pobj);
3486 } else if (pobj == Py_None) {
3487 pptr = (char *)NULL;
3488 } else {
3489 PyErr_SetString(socket_error, "Int or String expected");
3490 goto err;
3492 memset(&hints, 0, sizeof(hints));
3493 hints.ai_family = family;
3494 hints.ai_socktype = socktype;
3495 hints.ai_protocol = protocol;
3496 hints.ai_flags = flags;
3497 Py_BEGIN_ALLOW_THREADS
3498 ACQUIRE_GETADDRINFO_LOCK
3499 error = getaddrinfo(hptr, pptr, &hints, &res0);
3500 Py_END_ALLOW_THREADS
3501 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
3502 if (error) {
3503 set_gaierror(error);
3504 goto err;
3507 if ((all = PyList_New(0)) == NULL)
3508 goto err;
3509 for (res = res0; res; res = res->ai_next) {
3510 PyObject *addr =
3511 makesockaddr(-1, res->ai_addr, res->ai_addrlen, protocol);
3512 if (addr == NULL)
3513 goto err;
3514 single = Py_BuildValue("iiisO", res->ai_family,
3515 res->ai_socktype, res->ai_protocol,
3516 res->ai_canonname ? res->ai_canonname : "",
3517 addr);
3518 Py_DECREF(addr);
3519 if (single == NULL)
3520 goto err;
3522 if (PyList_Append(all, single))
3523 goto err;
3524 Py_XDECREF(single);
3526 Py_XDECREF(idna);
3527 if (res0)
3528 freeaddrinfo(res0);
3529 return all;
3530 err:
3531 Py_XDECREF(single);
3532 Py_XDECREF(all);
3533 Py_XDECREF(idna);
3534 if (res0)
3535 freeaddrinfo(res0);
3536 return (PyObject *)NULL;
3539 PyDoc_STRVAR(getaddrinfo_doc,
3540 "getaddrinfo(host, port [, family, socktype, proto, flags])\n\
3541 -> list of (family, socktype, proto, canonname, sockaddr)\n\
3543 Resolve host and port into addrinfo struct.");
3545 /* Python interface to getnameinfo(sa, flags). */
3547 /*ARGSUSED*/
3548 static PyObject *
3549 socket_getnameinfo(PyObject *self, PyObject *args)
3551 PyObject *sa = (PyObject *)NULL;
3552 int flags;
3553 char *hostp;
3554 int port, flowinfo, scope_id;
3555 char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
3556 struct addrinfo hints, *res = NULL;
3557 int error;
3558 PyObject *ret = (PyObject *)NULL;
3560 flags = flowinfo = scope_id = 0;
3561 if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags))
3562 return NULL;
3563 if (!PyArg_ParseTuple(sa, "si|ii",
3564 &hostp, &port, &flowinfo, &scope_id))
3565 return NULL;
3566 PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port);
3567 memset(&hints, 0, sizeof(hints));
3568 hints.ai_family = AF_UNSPEC;
3569 hints.ai_socktype = SOCK_DGRAM; /* make numeric port happy */
3570 Py_BEGIN_ALLOW_THREADS
3571 ACQUIRE_GETADDRINFO_LOCK
3572 error = getaddrinfo(hostp, pbuf, &hints, &res);
3573 Py_END_ALLOW_THREADS
3574 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
3575 if (error) {
3576 set_gaierror(error);
3577 goto fail;
3579 if (res->ai_next) {
3580 PyErr_SetString(socket_error,
3581 "sockaddr resolved to multiple addresses");
3582 goto fail;
3584 switch (res->ai_family) {
3585 case AF_INET:
3587 char *t1;
3588 int t2;
3589 if (PyArg_ParseTuple(sa, "si", &t1, &t2) == 0) {
3590 PyErr_SetString(socket_error,
3591 "IPv4 sockaddr must be 2 tuple");
3592 goto fail;
3594 break;
3596 #ifdef ENABLE_IPV6
3597 case AF_INET6:
3599 struct sockaddr_in6 *sin6;
3600 sin6 = (struct sockaddr_in6 *)res->ai_addr;
3601 sin6->sin6_flowinfo = flowinfo;
3602 sin6->sin6_scope_id = scope_id;
3603 break;
3605 #endif
3607 error = getnameinfo(res->ai_addr, res->ai_addrlen,
3608 hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags);
3609 if (error) {
3610 set_gaierror(error);
3611 goto fail;
3613 ret = Py_BuildValue("ss", hbuf, pbuf);
3615 fail:
3616 if (res)
3617 freeaddrinfo(res);
3618 return ret;
3621 PyDoc_STRVAR(getnameinfo_doc,
3622 "getnameinfo(sockaddr, flags) --> (host, port)\n\
3624 Get host and port for a sockaddr.");
3627 /* Python API to getting and setting the default timeout value. */
3629 static PyObject *
3630 socket_getdefaulttimeout(PyObject *self)
3632 if (defaulttimeout < 0.0) {
3633 Py_INCREF(Py_None);
3634 return Py_None;
3636 else
3637 return PyFloat_FromDouble(defaulttimeout);
3640 PyDoc_STRVAR(getdefaulttimeout_doc,
3641 "getdefaulttimeout() -> timeout\n\
3643 Returns the default timeout in floating seconds for new socket objects.\n\
3644 A value of None indicates that new socket objects have no timeout.\n\
3645 When the socket module is first imported, the default is None.");
3647 static PyObject *
3648 socket_setdefaulttimeout(PyObject *self, PyObject *arg)
3650 double timeout;
3652 if (arg == Py_None)
3653 timeout = -1.0;
3654 else {
3655 timeout = PyFloat_AsDouble(arg);
3656 if (timeout < 0.0) {
3657 if (!PyErr_Occurred())
3658 PyErr_SetString(PyExc_ValueError,
3659 "Timeout value out of range");
3660 return NULL;
3664 defaulttimeout = timeout;
3666 Py_INCREF(Py_None);
3667 return Py_None;
3670 PyDoc_STRVAR(setdefaulttimeout_doc,
3671 "setdefaulttimeout(timeout)\n\
3673 Set the default timeout in floating seconds for new socket objects.\n\
3674 A value of None indicates that new socket objects have no timeout.\n\
3675 When the socket module is first imported, the default is None.");
3678 /* List of functions exported by this module. */
3680 static PyMethodDef socket_methods[] = {
3681 {"gethostbyname", socket_gethostbyname,
3682 METH_VARARGS, gethostbyname_doc},
3683 {"gethostbyname_ex", socket_gethostbyname_ex,
3684 METH_VARARGS, ghbn_ex_doc},
3685 {"gethostbyaddr", socket_gethostbyaddr,
3686 METH_VARARGS, gethostbyaddr_doc},
3687 {"gethostname", socket_gethostname,
3688 METH_VARARGS, gethostname_doc},
3689 {"getservbyname", socket_getservbyname,
3690 METH_VARARGS, getservbyname_doc},
3691 {"getservbyport", socket_getservbyport,
3692 METH_VARARGS, getservbyport_doc},
3693 {"getprotobyname", socket_getprotobyname,
3694 METH_VARARGS,getprotobyname_doc},
3695 #ifndef NO_DUP
3696 {"fromfd", socket_fromfd,
3697 METH_VARARGS, fromfd_doc},
3698 #endif
3699 #ifdef HAVE_SOCKETPAIR
3700 {"socketpair", socket_socketpair,
3701 METH_VARARGS, socketpair_doc},
3702 #endif
3703 {"ntohs", socket_ntohs,
3704 METH_VARARGS, ntohs_doc},
3705 {"ntohl", socket_ntohl,
3706 METH_O, ntohl_doc},
3707 {"htons", socket_htons,
3708 METH_VARARGS, htons_doc},
3709 {"htonl", socket_htonl,
3710 METH_O, htonl_doc},
3711 {"inet_aton", socket_inet_aton,
3712 METH_VARARGS, inet_aton_doc},
3713 {"inet_ntoa", socket_inet_ntoa,
3714 METH_VARARGS, inet_ntoa_doc},
3715 #ifdef HAVE_INET_PTON
3716 {"inet_pton", socket_inet_pton,
3717 METH_VARARGS, inet_pton_doc},
3718 {"inet_ntop", socket_inet_ntop,
3719 METH_VARARGS, inet_ntop_doc},
3720 #endif
3721 {"getaddrinfo", socket_getaddrinfo,
3722 METH_VARARGS, getaddrinfo_doc},
3723 {"getnameinfo", socket_getnameinfo,
3724 METH_VARARGS, getnameinfo_doc},
3725 {"getdefaulttimeout", (PyCFunction)socket_getdefaulttimeout,
3726 METH_NOARGS, getdefaulttimeout_doc},
3727 {"setdefaulttimeout", socket_setdefaulttimeout,
3728 METH_O, setdefaulttimeout_doc},
3729 {NULL, NULL} /* Sentinel */
3733 #ifdef RISCOS
3734 #define OS_INIT_DEFINED
3736 static int
3737 os_init(void)
3739 _kernel_swi_regs r;
3741 r.r[0] = 0;
3742 _kernel_swi(0x43380, &r, &r);
3743 taskwindow = r.r[0];
3745 return 1;
3748 #endif /* RISCOS */
3751 #ifdef MS_WINDOWS
3752 #define OS_INIT_DEFINED
3754 /* Additional initialization and cleanup for Windows */
3756 static void
3757 os_cleanup(void)
3759 WSACleanup();
3762 static int
3763 os_init(void)
3765 WSADATA WSAData;
3766 int ret;
3767 char buf[100];
3768 ret = WSAStartup(0x0101, &WSAData);
3769 switch (ret) {
3770 case 0: /* No error */
3771 Py_AtExit(os_cleanup);
3772 return 1; /* Success */
3773 case WSASYSNOTREADY:
3774 PyErr_SetString(PyExc_ImportError,
3775 "WSAStartup failed: network not ready");
3776 break;
3777 case WSAVERNOTSUPPORTED:
3778 case WSAEINVAL:
3779 PyErr_SetString(
3780 PyExc_ImportError,
3781 "WSAStartup failed: requested version not supported");
3782 break;
3783 default:
3784 PyOS_snprintf(buf, sizeof(buf),
3785 "WSAStartup failed: error code %d", ret);
3786 PyErr_SetString(PyExc_ImportError, buf);
3787 break;
3789 return 0; /* Failure */
3792 #endif /* MS_WINDOWS */
3795 #ifdef PYOS_OS2
3796 #define OS_INIT_DEFINED
3798 /* Additional initialization for OS/2 */
3800 static int
3801 os_init(void)
3803 #ifndef PYCC_GCC
3804 char reason[64];
3805 int rc = sock_init();
3807 if (rc == 0) {
3808 return 1; /* Success */
3811 PyOS_snprintf(reason, sizeof(reason),
3812 "OS/2 TCP/IP Error# %d", sock_errno());
3813 PyErr_SetString(PyExc_ImportError, reason);
3815 return 0; /* Failure */
3816 #else
3817 /* No need to initialise sockets with GCC/EMX */
3818 return 1; /* Success */
3819 #endif
3822 #endif /* PYOS_OS2 */
3825 #ifndef OS_INIT_DEFINED
3826 static int
3827 os_init(void)
3829 return 1; /* Success */
3831 #endif
3834 /* C API table - always add new things to the end for binary
3835 compatibility. */
3836 static
3837 PySocketModule_APIObject PySocketModuleAPI =
3839 &sock_type,
3840 NULL
3844 /* Initialize the _socket module.
3846 This module is actually called "_socket", and there's a wrapper
3847 "socket.py" which implements some additional functionality. On some
3848 platforms (e.g. Windows and OS/2), socket.py also implements a
3849 wrapper for the socket type that provides missing functionality such
3850 as makefile(), dup() and fromfd(). The import of "_socket" may fail
3851 with an ImportError exception if os-specific initialization fails.
3852 On Windows, this does WINSOCK initialization. When WINSOCK is
3853 initialized succesfully, a call to WSACleanup() is scheduled to be
3854 made at exit time.
3857 PyDoc_STRVAR(socket_doc,
3858 "Implementation module for socket operations.\n\
3860 See the socket module for documentation.");
3862 PyMODINIT_FUNC
3863 init_socket(void)
3865 PyObject *m, *has_ipv6;
3867 if (!os_init())
3868 return;
3870 sock_type.ob_type = &PyType_Type;
3871 m = Py_InitModule3(PySocket_MODULE_NAME,
3872 socket_methods,
3873 socket_doc);
3875 socket_error = PyErr_NewException("socket.error", NULL, NULL);
3876 if (socket_error == NULL)
3877 return;
3878 PySocketModuleAPI.error = socket_error;
3879 Py_INCREF(socket_error);
3880 PyModule_AddObject(m, "error", socket_error);
3881 socket_herror = PyErr_NewException("socket.herror",
3882 socket_error, NULL);
3883 if (socket_herror == NULL)
3884 return;
3885 Py_INCREF(socket_herror);
3886 PyModule_AddObject(m, "herror", socket_herror);
3887 socket_gaierror = PyErr_NewException("socket.gaierror", socket_error,
3888 NULL);
3889 if (socket_gaierror == NULL)
3890 return;
3891 Py_INCREF(socket_gaierror);
3892 PyModule_AddObject(m, "gaierror", socket_gaierror);
3893 socket_timeout = PyErr_NewException("socket.timeout",
3894 socket_error, NULL);
3895 if (socket_timeout == NULL)
3896 return;
3897 Py_INCREF(socket_timeout);
3898 PyModule_AddObject(m, "timeout", socket_timeout);
3899 Py_INCREF((PyObject *)&sock_type);
3900 if (PyModule_AddObject(m, "SocketType",
3901 (PyObject *)&sock_type) != 0)
3902 return;
3903 Py_INCREF((PyObject *)&sock_type);
3904 if (PyModule_AddObject(m, "socket",
3905 (PyObject *)&sock_type) != 0)
3906 return;
3908 #ifdef ENABLE_IPV6
3909 has_ipv6 = Py_True;
3910 #else
3911 has_ipv6 = Py_False;
3912 #endif
3913 Py_INCREF(has_ipv6);
3914 PyModule_AddObject(m, "has_ipv6", has_ipv6);
3916 /* Export C API */
3917 if (PyModule_AddObject(m, PySocket_CAPI_NAME,
3918 PyCObject_FromVoidPtr((void *)&PySocketModuleAPI, NULL)
3919 ) != 0)
3920 return;
3922 /* Address families (we only support AF_INET and AF_UNIX) */
3923 #ifdef AF_UNSPEC
3924 PyModule_AddIntConstant(m, "AF_UNSPEC", AF_UNSPEC);
3925 #endif
3926 PyModule_AddIntConstant(m, "AF_INET", AF_INET);
3927 #ifdef AF_INET6
3928 PyModule_AddIntConstant(m, "AF_INET6", AF_INET6);
3929 #endif /* AF_INET6 */
3930 #if defined(AF_UNIX)
3931 PyModule_AddIntConstant(m, "AF_UNIX", AF_UNIX);
3932 #endif /* AF_UNIX */
3933 #ifdef AF_AX25
3934 /* Amateur Radio AX.25 */
3935 PyModule_AddIntConstant(m, "AF_AX25", AF_AX25);
3936 #endif
3937 #ifdef AF_IPX
3938 PyModule_AddIntConstant(m, "AF_IPX", AF_IPX); /* Novell IPX */
3939 #endif
3940 #ifdef AF_APPLETALK
3941 /* Appletalk DDP */
3942 PyModule_AddIntConstant(m, "AF_APPLETALK", AF_APPLETALK);
3943 #endif
3944 #ifdef AF_NETROM
3945 /* Amateur radio NetROM */
3946 PyModule_AddIntConstant(m, "AF_NETROM", AF_NETROM);
3947 #endif
3948 #ifdef AF_BRIDGE
3949 /* Multiprotocol bridge */
3950 PyModule_AddIntConstant(m, "AF_BRIDGE", AF_BRIDGE);
3951 #endif
3952 #ifdef AF_ATMPVC
3953 /* ATM PVCs */
3954 PyModule_AddIntConstant(m, "AF_ATMPVC", AF_ATMPVC);
3955 #endif
3956 #ifdef AF_AAL5
3957 /* Reserved for Werner's ATM */
3958 PyModule_AddIntConstant(m, "AF_AAL5", AF_AAL5);
3959 #endif
3960 #ifdef AF_X25
3961 /* Reserved for X.25 project */
3962 PyModule_AddIntConstant(m, "AF_X25", AF_X25);
3963 #endif
3964 #ifdef AF_INET6
3965 PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); /* IP version 6 */
3966 #endif
3967 #ifdef AF_ROSE
3968 /* Amateur Radio X.25 PLP */
3969 PyModule_AddIntConstant(m, "AF_ROSE", AF_ROSE);
3970 #endif
3971 #ifdef AF_DECnet
3972 /* Reserved for DECnet project */
3973 PyModule_AddIntConstant(m, "AF_DECnet", AF_DECnet);
3974 #endif
3975 #ifdef AF_NETBEUI
3976 /* Reserved for 802.2LLC project */
3977 PyModule_AddIntConstant(m, "AF_NETBEUI", AF_NETBEUI);
3978 #endif
3979 #ifdef AF_SECURITY
3980 /* Security callback pseudo AF */
3981 PyModule_AddIntConstant(m, "AF_SECURITY", AF_SECURITY);
3982 #endif
3983 #ifdef AF_KEY
3984 /* PF_KEY key management API */
3985 PyModule_AddIntConstant(m, "AF_KEY", AF_KEY);
3986 #endif
3987 #ifdef AF_NETLINK
3988 /* */
3989 PyModule_AddIntConstant(m, "AF_NETLINK", AF_NETLINK);
3990 PyModule_AddIntConstant(m, "NETLINK_ROUTE", NETLINK_ROUTE);
3991 PyModule_AddIntConstant(m, "NETLINK_SKIP", NETLINK_SKIP);
3992 PyModule_AddIntConstant(m, "NETLINK_USERSOCK", NETLINK_USERSOCK);
3993 PyModule_AddIntConstant(m, "NETLINK_FIREWALL", NETLINK_FIREWALL);
3994 PyModule_AddIntConstant(m, "NETLINK_TCPDIAG", NETLINK_TCPDIAG);
3995 PyModule_AddIntConstant(m, "NETLINK_NFLOG", NETLINK_NFLOG);
3996 #ifdef NETLINK_XFRM
3997 PyModule_AddIntConstant(m, "NETLINK_XFRM", NETLINK_XFRM);
3998 #endif
3999 PyModule_AddIntConstant(m, "NETLINK_ARPD", NETLINK_ARPD);
4000 PyModule_AddIntConstant(m, "NETLINK_ROUTE6", NETLINK_ROUTE6);
4001 PyModule_AddIntConstant(m, "NETLINK_IP6_FW", NETLINK_IP6_FW);
4002 PyModule_AddIntConstant(m, "NETLINK_DNRTMSG", NETLINK_DNRTMSG);
4003 PyModule_AddIntConstant(m, "NETLINK_TAPBASE", NETLINK_TAPBASE);
4004 #endif
4005 #ifdef AF_ROUTE
4006 /* Alias to emulate 4.4BSD */
4007 PyModule_AddIntConstant(m, "AF_ROUTE", AF_ROUTE);
4008 #endif
4009 #ifdef AF_ASH
4010 /* Ash */
4011 PyModule_AddIntConstant(m, "AF_ASH", AF_ASH);
4012 #endif
4013 #ifdef AF_ECONET
4014 /* Acorn Econet */
4015 PyModule_AddIntConstant(m, "AF_ECONET", AF_ECONET);
4016 #endif
4017 #ifdef AF_ATMSVC
4018 /* ATM SVCs */
4019 PyModule_AddIntConstant(m, "AF_ATMSVC", AF_ATMSVC);
4020 #endif
4021 #ifdef AF_SNA
4022 /* Linux SNA Project (nutters!) */
4023 PyModule_AddIntConstant(m, "AF_SNA", AF_SNA);
4024 #endif
4025 #ifdef AF_IRDA
4026 /* IRDA sockets */
4027 PyModule_AddIntConstant(m, "AF_IRDA", AF_IRDA);
4028 #endif
4029 #ifdef AF_PPPOX
4030 /* PPPoX sockets */
4031 PyModule_AddIntConstant(m, "AF_PPPOX", AF_PPPOX);
4032 #endif
4033 #ifdef AF_WANPIPE
4034 /* Wanpipe API Sockets */
4035 PyModule_AddIntConstant(m, "AF_WANPIPE", AF_WANPIPE);
4036 #endif
4037 #ifdef AF_LLC
4038 /* Linux LLC */
4039 PyModule_AddIntConstant(m, "AF_LLC", AF_LLC);
4040 #endif
4042 #ifdef USE_BLUETOOTH
4043 PyModule_AddIntConstant(m, "AF_BLUETOOTH", AF_BLUETOOTH);
4044 PyModule_AddIntConstant(m, "BTPROTO_L2CAP", BTPROTO_L2CAP);
4045 #if !defined(__FreeBSD__)
4046 PyModule_AddIntConstant(m, "BTPROTO_SCO", BTPROTO_SCO);
4047 #endif
4048 PyModule_AddIntConstant(m, "BTPROTO_RFCOMM", BTPROTO_RFCOMM);
4049 PyModule_AddObject(m, "BDADDR_ANY", Py_BuildValue("s", "00:00:00:00:00:00"));
4050 PyModule_AddObject(m, "BDADDR_LOCAL", Py_BuildValue("s", "00:00:00:FF:FF:FF"));
4051 #endif
4053 #ifdef HAVE_NETPACKET_PACKET_H
4054 PyModule_AddIntConstant(m, "AF_PACKET", AF_PACKET);
4055 PyModule_AddIntConstant(m, "PF_PACKET", PF_PACKET);
4056 PyModule_AddIntConstant(m, "PACKET_HOST", PACKET_HOST);
4057 PyModule_AddIntConstant(m, "PACKET_BROADCAST", PACKET_BROADCAST);
4058 PyModule_AddIntConstant(m, "PACKET_MULTICAST", PACKET_MULTICAST);
4059 PyModule_AddIntConstant(m, "PACKET_OTHERHOST", PACKET_OTHERHOST);
4060 PyModule_AddIntConstant(m, "PACKET_OUTGOING", PACKET_OUTGOING);
4061 PyModule_AddIntConstant(m, "PACKET_LOOPBACK", PACKET_LOOPBACK);
4062 PyModule_AddIntConstant(m, "PACKET_FASTROUTE", PACKET_FASTROUTE);
4063 #endif
4065 /* Socket types */
4066 PyModule_AddIntConstant(m, "SOCK_STREAM", SOCK_STREAM);
4067 PyModule_AddIntConstant(m, "SOCK_DGRAM", SOCK_DGRAM);
4068 #ifndef __BEOS__
4069 /* We have incomplete socket support. */
4070 PyModule_AddIntConstant(m, "SOCK_RAW", SOCK_RAW);
4071 PyModule_AddIntConstant(m, "SOCK_SEQPACKET", SOCK_SEQPACKET);
4072 #if defined(SOCK_RDM)
4073 PyModule_AddIntConstant(m, "SOCK_RDM", SOCK_RDM);
4074 #endif
4075 #endif
4077 #ifdef SO_DEBUG
4078 PyModule_AddIntConstant(m, "SO_DEBUG", SO_DEBUG);
4079 #endif
4080 #ifdef SO_ACCEPTCONN
4081 PyModule_AddIntConstant(m, "SO_ACCEPTCONN", SO_ACCEPTCONN);
4082 #endif
4083 #ifdef SO_REUSEADDR
4084 PyModule_AddIntConstant(m, "SO_REUSEADDR", SO_REUSEADDR);
4085 #endif
4086 #ifdef SO_EXCLUSIVEADDRUSE
4087 PyModule_AddIntConstant(m, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE);
4088 #endif
4090 #ifdef SO_KEEPALIVE
4091 PyModule_AddIntConstant(m, "SO_KEEPALIVE", SO_KEEPALIVE);
4092 #endif
4093 #ifdef SO_DONTROUTE
4094 PyModule_AddIntConstant(m, "SO_DONTROUTE", SO_DONTROUTE);
4095 #endif
4096 #ifdef SO_BROADCAST
4097 PyModule_AddIntConstant(m, "SO_BROADCAST", SO_BROADCAST);
4098 #endif
4099 #ifdef SO_USELOOPBACK
4100 PyModule_AddIntConstant(m, "SO_USELOOPBACK", SO_USELOOPBACK);
4101 #endif
4102 #ifdef SO_LINGER
4103 PyModule_AddIntConstant(m, "SO_LINGER", SO_LINGER);
4104 #endif
4105 #ifdef SO_OOBINLINE
4106 PyModule_AddIntConstant(m, "SO_OOBINLINE", SO_OOBINLINE);
4107 #endif
4108 #ifdef SO_REUSEPORT
4109 PyModule_AddIntConstant(m, "SO_REUSEPORT", SO_REUSEPORT);
4110 #endif
4111 #ifdef SO_SNDBUF
4112 PyModule_AddIntConstant(m, "SO_SNDBUF", SO_SNDBUF);
4113 #endif
4114 #ifdef SO_RCVBUF
4115 PyModule_AddIntConstant(m, "SO_RCVBUF", SO_RCVBUF);
4116 #endif
4117 #ifdef SO_SNDLOWAT
4118 PyModule_AddIntConstant(m, "SO_SNDLOWAT", SO_SNDLOWAT);
4119 #endif
4120 #ifdef SO_RCVLOWAT
4121 PyModule_AddIntConstant(m, "SO_RCVLOWAT", SO_RCVLOWAT);
4122 #endif
4123 #ifdef SO_SNDTIMEO
4124 PyModule_AddIntConstant(m, "SO_SNDTIMEO", SO_SNDTIMEO);
4125 #endif
4126 #ifdef SO_RCVTIMEO
4127 PyModule_AddIntConstant(m, "SO_RCVTIMEO", SO_RCVTIMEO);
4128 #endif
4129 #ifdef SO_ERROR
4130 PyModule_AddIntConstant(m, "SO_ERROR", SO_ERROR);
4131 #endif
4132 #ifdef SO_TYPE
4133 PyModule_AddIntConstant(m, "SO_TYPE", SO_TYPE);
4134 #endif
4136 /* Maximum number of connections for "listen" */
4137 #ifdef SOMAXCONN
4138 PyModule_AddIntConstant(m, "SOMAXCONN", SOMAXCONN);
4139 #else
4140 PyModule_AddIntConstant(m, "SOMAXCONN", 5); /* Common value */
4141 #endif
4143 /* Flags for send, recv */
4144 #ifdef MSG_OOB
4145 PyModule_AddIntConstant(m, "MSG_OOB", MSG_OOB);
4146 #endif
4147 #ifdef MSG_PEEK
4148 PyModule_AddIntConstant(m, "MSG_PEEK", MSG_PEEK);
4149 #endif
4150 #ifdef MSG_DONTROUTE
4151 PyModule_AddIntConstant(m, "MSG_DONTROUTE", MSG_DONTROUTE);
4152 #endif
4153 #ifdef MSG_DONTWAIT
4154 PyModule_AddIntConstant(m, "MSG_DONTWAIT", MSG_DONTWAIT);
4155 #endif
4156 #ifdef MSG_EOR
4157 PyModule_AddIntConstant(m, "MSG_EOR", MSG_EOR);
4158 #endif
4159 #ifdef MSG_TRUNC
4160 PyModule_AddIntConstant(m, "MSG_TRUNC", MSG_TRUNC);
4161 #endif
4162 #ifdef MSG_CTRUNC
4163 PyModule_AddIntConstant(m, "MSG_CTRUNC", MSG_CTRUNC);
4164 #endif
4165 #ifdef MSG_WAITALL
4166 PyModule_AddIntConstant(m, "MSG_WAITALL", MSG_WAITALL);
4167 #endif
4168 #ifdef MSG_BTAG
4169 PyModule_AddIntConstant(m, "MSG_BTAG", MSG_BTAG);
4170 #endif
4171 #ifdef MSG_ETAG
4172 PyModule_AddIntConstant(m, "MSG_ETAG", MSG_ETAG);
4173 #endif
4175 /* Protocol level and numbers, usable for [gs]etsockopt */
4176 #ifdef SOL_SOCKET
4177 PyModule_AddIntConstant(m, "SOL_SOCKET", SOL_SOCKET);
4178 #endif
4179 #ifdef SOL_IP
4180 PyModule_AddIntConstant(m, "SOL_IP", SOL_IP);
4181 #else
4182 PyModule_AddIntConstant(m, "SOL_IP", 0);
4183 #endif
4184 #ifdef SOL_IPX
4185 PyModule_AddIntConstant(m, "SOL_IPX", SOL_IPX);
4186 #endif
4187 #ifdef SOL_AX25
4188 PyModule_AddIntConstant(m, "SOL_AX25", SOL_AX25);
4189 #endif
4190 #ifdef SOL_ATALK
4191 PyModule_AddIntConstant(m, "SOL_ATALK", SOL_ATALK);
4192 #endif
4193 #ifdef SOL_NETROM
4194 PyModule_AddIntConstant(m, "SOL_NETROM", SOL_NETROM);
4195 #endif
4196 #ifdef SOL_ROSE
4197 PyModule_AddIntConstant(m, "SOL_ROSE", SOL_ROSE);
4198 #endif
4199 #ifdef SOL_TCP
4200 PyModule_AddIntConstant(m, "SOL_TCP", SOL_TCP);
4201 #else
4202 PyModule_AddIntConstant(m, "SOL_TCP", 6);
4203 #endif
4204 #ifdef SOL_UDP
4205 PyModule_AddIntConstant(m, "SOL_UDP", SOL_UDP);
4206 #else
4207 PyModule_AddIntConstant(m, "SOL_UDP", 17);
4208 #endif
4209 #ifdef IPPROTO_IP
4210 PyModule_AddIntConstant(m, "IPPROTO_IP", IPPROTO_IP);
4211 #else
4212 PyModule_AddIntConstant(m, "IPPROTO_IP", 0);
4213 #endif
4214 #ifdef IPPROTO_HOPOPTS
4215 PyModule_AddIntConstant(m, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS);
4216 #endif
4217 #ifdef IPPROTO_ICMP
4218 PyModule_AddIntConstant(m, "IPPROTO_ICMP", IPPROTO_ICMP);
4219 #else
4220 PyModule_AddIntConstant(m, "IPPROTO_ICMP", 1);
4221 #endif
4222 #ifdef IPPROTO_IGMP
4223 PyModule_AddIntConstant(m, "IPPROTO_IGMP", IPPROTO_IGMP);
4224 #endif
4225 #ifdef IPPROTO_GGP
4226 PyModule_AddIntConstant(m, "IPPROTO_GGP", IPPROTO_GGP);
4227 #endif
4228 #ifdef IPPROTO_IPV4
4229 PyModule_AddIntConstant(m, "IPPROTO_IPV4", IPPROTO_IPV4);
4230 #endif
4231 #ifdef IPPROTO_IPV6
4232 PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
4233 #endif
4234 #ifdef IPPROTO_IPIP
4235 PyModule_AddIntConstant(m, "IPPROTO_IPIP", IPPROTO_IPIP);
4236 #endif
4237 #ifdef IPPROTO_TCP
4238 PyModule_AddIntConstant(m, "IPPROTO_TCP", IPPROTO_TCP);
4239 #else
4240 PyModule_AddIntConstant(m, "IPPROTO_TCP", 6);
4241 #endif
4242 #ifdef IPPROTO_EGP
4243 PyModule_AddIntConstant(m, "IPPROTO_EGP", IPPROTO_EGP);
4244 #endif
4245 #ifdef IPPROTO_PUP
4246 PyModule_AddIntConstant(m, "IPPROTO_PUP", IPPROTO_PUP);
4247 #endif
4248 #ifdef IPPROTO_UDP
4249 PyModule_AddIntConstant(m, "IPPROTO_UDP", IPPROTO_UDP);
4250 #else
4251 PyModule_AddIntConstant(m, "IPPROTO_UDP", 17);
4252 #endif
4253 #ifdef IPPROTO_IDP
4254 PyModule_AddIntConstant(m, "IPPROTO_IDP", IPPROTO_IDP);
4255 #endif
4256 #ifdef IPPROTO_HELLO
4257 PyModule_AddIntConstant(m, "IPPROTO_HELLO", IPPROTO_HELLO);
4258 #endif
4259 #ifdef IPPROTO_ND
4260 PyModule_AddIntConstant(m, "IPPROTO_ND", IPPROTO_ND);
4261 #endif
4262 #ifdef IPPROTO_TP
4263 PyModule_AddIntConstant(m, "IPPROTO_TP", IPPROTO_TP);
4264 #endif
4265 #ifdef IPPROTO_IPV6
4266 PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
4267 #endif
4268 #ifdef IPPROTO_ROUTING
4269 PyModule_AddIntConstant(m, "IPPROTO_ROUTING", IPPROTO_ROUTING);
4270 #endif
4271 #ifdef IPPROTO_FRAGMENT
4272 PyModule_AddIntConstant(m, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT);
4273 #endif
4274 #ifdef IPPROTO_RSVP
4275 PyModule_AddIntConstant(m, "IPPROTO_RSVP", IPPROTO_RSVP);
4276 #endif
4277 #ifdef IPPROTO_GRE
4278 PyModule_AddIntConstant(m, "IPPROTO_GRE", IPPROTO_GRE);
4279 #endif
4280 #ifdef IPPROTO_ESP
4281 PyModule_AddIntConstant(m, "IPPROTO_ESP", IPPROTO_ESP);
4282 #endif
4283 #ifdef IPPROTO_AH
4284 PyModule_AddIntConstant(m, "IPPROTO_AH", IPPROTO_AH);
4285 #endif
4286 #ifdef IPPROTO_MOBILE
4287 PyModule_AddIntConstant(m, "IPPROTO_MOBILE", IPPROTO_MOBILE);
4288 #endif
4289 #ifdef IPPROTO_ICMPV6
4290 PyModule_AddIntConstant(m, "IPPROTO_ICMPV6", IPPROTO_ICMPV6);
4291 #endif
4292 #ifdef IPPROTO_NONE
4293 PyModule_AddIntConstant(m, "IPPROTO_NONE", IPPROTO_NONE);
4294 #endif
4295 #ifdef IPPROTO_DSTOPTS
4296 PyModule_AddIntConstant(m, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS);
4297 #endif
4298 #ifdef IPPROTO_XTP
4299 PyModule_AddIntConstant(m, "IPPROTO_XTP", IPPROTO_XTP);
4300 #endif
4301 #ifdef IPPROTO_EON
4302 PyModule_AddIntConstant(m, "IPPROTO_EON", IPPROTO_EON);
4303 #endif
4304 #ifdef IPPROTO_PIM
4305 PyModule_AddIntConstant(m, "IPPROTO_PIM", IPPROTO_PIM);
4306 #endif
4307 #ifdef IPPROTO_IPCOMP
4308 PyModule_AddIntConstant(m, "IPPROTO_IPCOMP", IPPROTO_IPCOMP);
4309 #endif
4310 #ifdef IPPROTO_VRRP
4311 PyModule_AddIntConstant(m, "IPPROTO_VRRP", IPPROTO_VRRP);
4312 #endif
4313 #ifdef IPPROTO_BIP
4314 PyModule_AddIntConstant(m, "IPPROTO_BIP", IPPROTO_BIP);
4315 #endif
4316 /**/
4317 #ifdef IPPROTO_RAW
4318 PyModule_AddIntConstant(m, "IPPROTO_RAW", IPPROTO_RAW);
4319 #else
4320 PyModule_AddIntConstant(m, "IPPROTO_RAW", 255);
4321 #endif
4322 #ifdef IPPROTO_MAX
4323 PyModule_AddIntConstant(m, "IPPROTO_MAX", IPPROTO_MAX);
4324 #endif
4326 /* Some port configuration */
4327 #ifdef IPPORT_RESERVED
4328 PyModule_AddIntConstant(m, "IPPORT_RESERVED", IPPORT_RESERVED);
4329 #else
4330 PyModule_AddIntConstant(m, "IPPORT_RESERVED", 1024);
4331 #endif
4332 #ifdef IPPORT_USERRESERVED
4333 PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", IPPORT_USERRESERVED);
4334 #else
4335 PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", 5000);
4336 #endif
4338 /* Some reserved IP v.4 addresses */
4339 #ifdef INADDR_ANY
4340 PyModule_AddIntConstant(m, "INADDR_ANY", INADDR_ANY);
4341 #else
4342 PyModule_AddIntConstant(m, "INADDR_ANY", 0x00000000);
4343 #endif
4344 #ifdef INADDR_BROADCAST
4345 PyModule_AddIntConstant(m, "INADDR_BROADCAST", INADDR_BROADCAST);
4346 #else
4347 PyModule_AddIntConstant(m, "INADDR_BROADCAST", 0xffffffff);
4348 #endif
4349 #ifdef INADDR_LOOPBACK
4350 PyModule_AddIntConstant(m, "INADDR_LOOPBACK", INADDR_LOOPBACK);
4351 #else
4352 PyModule_AddIntConstant(m, "INADDR_LOOPBACK", 0x7F000001);
4353 #endif
4354 #ifdef INADDR_UNSPEC_GROUP
4355 PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
4356 #else
4357 PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", 0xe0000000);
4358 #endif
4359 #ifdef INADDR_ALLHOSTS_GROUP
4360 PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP",
4361 INADDR_ALLHOSTS_GROUP);
4362 #else
4363 PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
4364 #endif
4365 #ifdef INADDR_MAX_LOCAL_GROUP
4366 PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP",
4367 INADDR_MAX_LOCAL_GROUP);
4368 #else
4369 PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
4370 #endif
4371 #ifdef INADDR_NONE
4372 PyModule_AddIntConstant(m, "INADDR_NONE", INADDR_NONE);
4373 #else
4374 PyModule_AddIntConstant(m, "INADDR_NONE", 0xffffffff);
4375 #endif
4377 /* IPv4 [gs]etsockopt options */
4378 #ifdef IP_OPTIONS
4379 PyModule_AddIntConstant(m, "IP_OPTIONS", IP_OPTIONS);
4380 #endif
4381 #ifdef IP_HDRINCL
4382 PyModule_AddIntConstant(m, "IP_HDRINCL", IP_HDRINCL);
4383 #endif
4384 #ifdef IP_TOS
4385 PyModule_AddIntConstant(m, "IP_TOS", IP_TOS);
4386 #endif
4387 #ifdef IP_TTL
4388 PyModule_AddIntConstant(m, "IP_TTL", IP_TTL);
4389 #endif
4390 #ifdef IP_RECVOPTS
4391 PyModule_AddIntConstant(m, "IP_RECVOPTS", IP_RECVOPTS);
4392 #endif
4393 #ifdef IP_RECVRETOPTS
4394 PyModule_AddIntConstant(m, "IP_RECVRETOPTS", IP_RECVRETOPTS);
4395 #endif
4396 #ifdef IP_RECVDSTADDR
4397 PyModule_AddIntConstant(m, "IP_RECVDSTADDR", IP_RECVDSTADDR);
4398 #endif
4399 #ifdef IP_RETOPTS
4400 PyModule_AddIntConstant(m, "IP_RETOPTS", IP_RETOPTS);
4401 #endif
4402 #ifdef IP_MULTICAST_IF
4403 PyModule_AddIntConstant(m, "IP_MULTICAST_IF", IP_MULTICAST_IF);
4404 #endif
4405 #ifdef IP_MULTICAST_TTL
4406 PyModule_AddIntConstant(m, "IP_MULTICAST_TTL", IP_MULTICAST_TTL);
4407 #endif
4408 #ifdef IP_MULTICAST_LOOP
4409 PyModule_AddIntConstant(m, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
4410 #endif
4411 #ifdef IP_ADD_MEMBERSHIP
4412 PyModule_AddIntConstant(m, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
4413 #endif
4414 #ifdef IP_DROP_MEMBERSHIP
4415 PyModule_AddIntConstant(m, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
4416 #endif
4417 #ifdef IP_DEFAULT_MULTICAST_TTL
4418 PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_TTL",
4419 IP_DEFAULT_MULTICAST_TTL);
4420 #endif
4421 #ifdef IP_DEFAULT_MULTICAST_LOOP
4422 PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_LOOP",
4423 IP_DEFAULT_MULTICAST_LOOP);
4424 #endif
4425 #ifdef IP_MAX_MEMBERSHIPS
4426 PyModule_AddIntConstant(m, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS);
4427 #endif
4429 /* IPv6 [gs]etsockopt options, defined in RFC2553 */
4430 #ifdef IPV6_JOIN_GROUP
4431 PyModule_AddIntConstant(m, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP);
4432 #endif
4433 #ifdef IPV6_LEAVE_GROUP
4434 PyModule_AddIntConstant(m, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP);
4435 #endif
4436 #ifdef IPV6_MULTICAST_HOPS
4437 PyModule_AddIntConstant(m, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS);
4438 #endif
4439 #ifdef IPV6_MULTICAST_IF
4440 PyModule_AddIntConstant(m, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF);
4441 #endif
4442 #ifdef IPV6_MULTICAST_LOOP
4443 PyModule_AddIntConstant(m, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP);
4444 #endif
4445 #ifdef IPV6_UNICAST_HOPS
4446 PyModule_AddIntConstant(m, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS);
4447 #endif
4448 /* Additional IPV6 socket options, defined in RFC 3493 */
4449 #ifdef IPV6_V6ONLY
4450 PyModule_AddIntConstant(m, "IPV6_V6ONLY", IPV6_V6ONLY);
4451 #endif
4452 /* Advanced IPV6 socket options, from RFC 3542 */
4453 #ifdef IPV6_CHECKSUM
4454 PyModule_AddIntConstant(m, "IPV6_CHECKSUM", IPV6_CHECKSUM);
4455 #endif
4456 #ifdef IPV6_DONTFRAG
4457 PyModule_AddIntConstant(m, "IPV6_DONTFRAG", IPV6_DONTFRAG);
4458 #endif
4459 #ifdef IPV6_DSTOPTS
4460 PyModule_AddIntConstant(m, "IPV6_DSTOPTS", IPV6_DSTOPTS);
4461 #endif
4462 #ifdef IPV6_HOPLIMIT
4463 PyModule_AddIntConstant(m, "IPV6_HOPLIMIT", IPV6_HOPLIMIT);
4464 #endif
4465 #ifdef IPV6_HOPOPTS
4466 PyModule_AddIntConstant(m, "IPV6_HOPOPTS", IPV6_HOPOPTS);
4467 #endif
4468 #ifdef IPV6_NEXTHOP
4469 PyModule_AddIntConstant(m, "IPV6_NEXTHOP", IPV6_NEXTHOP);
4470 #endif
4471 #ifdef IPV6_PATHMTU
4472 PyModule_AddIntConstant(m, "IPV6_PATHMTU", IPV6_PATHMTU);
4473 #endif
4474 #ifdef IPV6_PKTINFO
4475 PyModule_AddIntConstant(m, "IPV6_PKTINFO", IPV6_PKTINFO);
4476 #endif
4477 #ifdef IPV6_RECVDSTOPTS
4478 PyModule_AddIntConstant(m, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS);
4479 #endif
4480 #ifdef IPV6_RECVHOPLIMIT
4481 PyModule_AddIntConstant(m, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT);
4482 #endif
4483 #ifdef IPV6_RECVHOPOPTS
4484 PyModule_AddIntConstant(m, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS);
4485 #endif
4486 #ifdef IPV6_RECVPKTINFO
4487 PyModule_AddIntConstant(m, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO);
4488 #endif
4489 #ifdef IPV6_RECVRTHDR
4490 PyModule_AddIntConstant(m, "IPV6_RECVRTHDR", IPV6_RECVRTHDR);
4491 #endif
4492 #ifdef IPV6_RECVTCLASS
4493 PyModule_AddIntConstant(m, "IPV6_RECVTCLASS", IPV6_RECVTCLASS);
4494 #endif
4495 #ifdef IPV6_RTHDR
4496 PyModule_AddIntConstant(m, "IPV6_RTHDR", IPV6_RTHDR);
4497 #endif
4498 #ifdef IPV6_RTHDRDSTOPTS
4499 PyModule_AddIntConstant(m, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS);
4500 #endif
4501 #ifdef IPV6_RTHDR_TYPE_0
4502 PyModule_AddIntConstant(m, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0);
4503 #endif
4504 #ifdef IPV6_RECVPATHMTU
4505 PyModule_AddIntConstant(m, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU);
4506 #endif
4507 #ifdef IPV6_TCLASS
4508 PyModule_AddIntConstant(m, "IPV6_TCLASS", IPV6_TCLASS);
4509 #endif
4510 #ifdef IPV6_USE_MIN_MTU
4511 PyModule_AddIntConstant(m, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU);
4512 #endif
4514 /* TCP options */
4515 #ifdef TCP_NODELAY
4516 PyModule_AddIntConstant(m, "TCP_NODELAY", TCP_NODELAY);
4517 #endif
4518 #ifdef TCP_MAXSEG
4519 PyModule_AddIntConstant(m, "TCP_MAXSEG", TCP_MAXSEG);
4520 #endif
4521 #ifdef TCP_CORK
4522 PyModule_AddIntConstant(m, "TCP_CORK", TCP_CORK);
4523 #endif
4524 #ifdef TCP_KEEPIDLE
4525 PyModule_AddIntConstant(m, "TCP_KEEPIDLE", TCP_KEEPIDLE);
4526 #endif
4527 #ifdef TCP_KEEPINTVL
4528 PyModule_AddIntConstant(m, "TCP_KEEPINTVL", TCP_KEEPINTVL);
4529 #endif
4530 #ifdef TCP_KEEPCNT
4531 PyModule_AddIntConstant(m, "TCP_KEEPCNT", TCP_KEEPCNT);
4532 #endif
4533 #ifdef TCP_SYNCNT
4534 PyModule_AddIntConstant(m, "TCP_SYNCNT", TCP_SYNCNT);
4535 #endif
4536 #ifdef TCP_LINGER2
4537 PyModule_AddIntConstant(m, "TCP_LINGER2", TCP_LINGER2);
4538 #endif
4539 #ifdef TCP_DEFER_ACCEPT
4540 PyModule_AddIntConstant(m, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT);
4541 #endif
4542 #ifdef TCP_WINDOW_CLAMP
4543 PyModule_AddIntConstant(m, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP);
4544 #endif
4545 #ifdef TCP_INFO
4546 PyModule_AddIntConstant(m, "TCP_INFO", TCP_INFO);
4547 #endif
4548 #ifdef TCP_QUICKACK
4549 PyModule_AddIntConstant(m, "TCP_QUICKACK", TCP_QUICKACK);
4550 #endif
4553 /* IPX options */
4554 #ifdef IPX_TYPE
4555 PyModule_AddIntConstant(m, "IPX_TYPE", IPX_TYPE);
4556 #endif
4558 /* get{addr,name}info parameters */
4559 #ifdef EAI_ADDRFAMILY
4560 PyModule_AddIntConstant(m, "EAI_ADDRFAMILY", EAI_ADDRFAMILY);
4561 #endif
4562 #ifdef EAI_AGAIN
4563 PyModule_AddIntConstant(m, "EAI_AGAIN", EAI_AGAIN);
4564 #endif
4565 #ifdef EAI_BADFLAGS
4566 PyModule_AddIntConstant(m, "EAI_BADFLAGS", EAI_BADFLAGS);
4567 #endif
4568 #ifdef EAI_FAIL
4569 PyModule_AddIntConstant(m, "EAI_FAIL", EAI_FAIL);
4570 #endif
4571 #ifdef EAI_FAMILY
4572 PyModule_AddIntConstant(m, "EAI_FAMILY", EAI_FAMILY);
4573 #endif
4574 #ifdef EAI_MEMORY
4575 PyModule_AddIntConstant(m, "EAI_MEMORY", EAI_MEMORY);
4576 #endif
4577 #ifdef EAI_NODATA
4578 PyModule_AddIntConstant(m, "EAI_NODATA", EAI_NODATA);
4579 #endif
4580 #ifdef EAI_NONAME
4581 PyModule_AddIntConstant(m, "EAI_NONAME", EAI_NONAME);
4582 #endif
4583 #ifdef EAI_OVERFLOW
4584 PyModule_AddIntConstant(m, "EAI_OVERFLOW", EAI_OVERFLOW);
4585 #endif
4586 #ifdef EAI_SERVICE
4587 PyModule_AddIntConstant(m, "EAI_SERVICE", EAI_SERVICE);
4588 #endif
4589 #ifdef EAI_SOCKTYPE
4590 PyModule_AddIntConstant(m, "EAI_SOCKTYPE", EAI_SOCKTYPE);
4591 #endif
4592 #ifdef EAI_SYSTEM
4593 PyModule_AddIntConstant(m, "EAI_SYSTEM", EAI_SYSTEM);
4594 #endif
4595 #ifdef EAI_BADHINTS
4596 PyModule_AddIntConstant(m, "EAI_BADHINTS", EAI_BADHINTS);
4597 #endif
4598 #ifdef EAI_PROTOCOL
4599 PyModule_AddIntConstant(m, "EAI_PROTOCOL", EAI_PROTOCOL);
4600 #endif
4601 #ifdef EAI_MAX
4602 PyModule_AddIntConstant(m, "EAI_MAX", EAI_MAX);
4603 #endif
4604 #ifdef AI_PASSIVE
4605 PyModule_AddIntConstant(m, "AI_PASSIVE", AI_PASSIVE);
4606 #endif
4607 #ifdef AI_CANONNAME
4608 PyModule_AddIntConstant(m, "AI_CANONNAME", AI_CANONNAME);
4609 #endif
4610 #ifdef AI_NUMERICHOST
4611 PyModule_AddIntConstant(m, "AI_NUMERICHOST", AI_NUMERICHOST);
4612 #endif
4613 #ifdef AI_NUMERICSERV
4614 PyModule_AddIntConstant(m, "AI_NUMERICSERV", AI_NUMERICSERV);
4615 #endif
4616 #ifdef AI_MASK
4617 PyModule_AddIntConstant(m, "AI_MASK", AI_MASK);
4618 #endif
4619 #ifdef AI_ALL
4620 PyModule_AddIntConstant(m, "AI_ALL", AI_ALL);
4621 #endif
4622 #ifdef AI_V4MAPPED_CFG
4623 PyModule_AddIntConstant(m, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG);
4624 #endif
4625 #ifdef AI_ADDRCONFIG
4626 PyModule_AddIntConstant(m, "AI_ADDRCONFIG", AI_ADDRCONFIG);
4627 #endif
4628 #ifdef AI_V4MAPPED
4629 PyModule_AddIntConstant(m, "AI_V4MAPPED", AI_V4MAPPED);
4630 #endif
4631 #ifdef AI_DEFAULT
4632 PyModule_AddIntConstant(m, "AI_DEFAULT", AI_DEFAULT);
4633 #endif
4634 #ifdef NI_MAXHOST
4635 PyModule_AddIntConstant(m, "NI_MAXHOST", NI_MAXHOST);
4636 #endif
4637 #ifdef NI_MAXSERV
4638 PyModule_AddIntConstant(m, "NI_MAXSERV", NI_MAXSERV);
4639 #endif
4640 #ifdef NI_NOFQDN
4641 PyModule_AddIntConstant(m, "NI_NOFQDN", NI_NOFQDN);
4642 #endif
4643 #ifdef NI_NUMERICHOST
4644 PyModule_AddIntConstant(m, "NI_NUMERICHOST", NI_NUMERICHOST);
4645 #endif
4646 #ifdef NI_NAMEREQD
4647 PyModule_AddIntConstant(m, "NI_NAMEREQD", NI_NAMEREQD);
4648 #endif
4649 #ifdef NI_NUMERICSERV
4650 PyModule_AddIntConstant(m, "NI_NUMERICSERV", NI_NUMERICSERV);
4651 #endif
4652 #ifdef NI_DGRAM
4653 PyModule_AddIntConstant(m, "NI_DGRAM", NI_DGRAM);
4654 #endif
4656 /* shutdown() parameters */
4657 #ifdef SHUT_RD
4658 PyModule_AddIntConstant(m, "SHUT_RD", SHUT_RD);
4659 #elif defined(SD_RECEIVE)
4660 PyModule_AddIntConstant(m, "SHUT_RD", SD_RECEIVE);
4661 #else
4662 PyModule_AddIntConstant(m, "SHUT_RD", 0);
4663 #endif
4664 #ifdef SHUT_WR
4665 PyModule_AddIntConstant(m, "SHUT_WR", SHUT_WR);
4666 #elif defined(SD_SEND)
4667 PyModule_AddIntConstant(m, "SHUT_WR", SD_SEND);
4668 #else
4669 PyModule_AddIntConstant(m, "SHUT_WR", 1);
4670 #endif
4671 #ifdef SHUT_RDWR
4672 PyModule_AddIntConstant(m, "SHUT_RDWR", SHUT_RDWR);
4673 #elif defined(SD_BOTH)
4674 PyModule_AddIntConstant(m, "SHUT_RDWR", SD_BOTH);
4675 #else
4676 PyModule_AddIntConstant(m, "SHUT_RDWR", 2);
4677 #endif
4679 /* Initialize gethostbyname lock */
4680 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
4681 netdb_lock = PyThread_allocate_lock();
4682 #endif
4686 #ifndef HAVE_INET_PTON
4688 /* Simplistic emulation code for inet_pton that only works for IPv4 */
4689 /* These are not exposed because they do not set errno properly */
4692 inet_pton(int af, const char *src, void *dst)
4694 if (af == AF_INET) {
4695 long packed_addr;
4696 packed_addr = inet_addr(src);
4697 if (packed_addr == INADDR_NONE)
4698 return 0;
4699 memcpy(dst, &packed_addr, 4);
4700 return 1;
4702 /* Should set errno to EAFNOSUPPORT */
4703 return -1;
4706 const char *
4707 inet_ntop(int af, const void *src, char *dst, socklen_t size)
4709 if (af == AF_INET) {
4710 struct in_addr packed_addr;
4711 if (size < 16)
4712 /* Should set errno to ENOSPC. */
4713 return NULL;
4714 memcpy(&packed_addr, src, sizeof(packed_addr));
4715 return strncpy(dst, inet_ntoa(packed_addr), size);
4717 /* Should set errno to EAFNOSUPPORT */
4718 return NULL;
4721 #endif