Fix argument order in pure python version of nsmallest() and nlargest().
[python/dscho.git] / Modules / socketmodule.c
blob3c17e9ce48b38694e4c21177babf90c91925f7b6
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 is 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 /* On systems on which getaddrinfo() is believed to not be thread-safe,
144 (this includes the getaddrinfo emulation) protect access with a lock. */
145 #if defined(WITH_THREAD) && (defined(__APPLE__) || defined(__FreeBSD__) || \
146 defined(__OpenBSD__) || defined(__NetBSD__) || !defined(HAVE_GETADDRINFO))
147 #define USE_GETADDRINFO_LOCK
148 #endif
150 #ifdef USE_GETADDRINFO_LOCK
151 #define ACQUIRE_GETADDRINFO_LOCK PyThread_acquire_lock(netdb_lock, 1);
152 #define RELEASE_GETADDRINFO_LOCK PyThread_release_lock(netdb_lock);
153 #else
154 #define ACQUIRE_GETADDRINFO_LOCK
155 #define RELEASE_GETADDRINFO_LOCK
156 #endif
158 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
159 # include "pythread.h"
160 #endif
162 #if defined(PYCC_VACPP)
163 # include <types.h>
164 # include <io.h>
165 # include <sys/ioctl.h>
166 # include <utils.h>
167 # include <ctype.h>
168 #endif
170 #if defined(__VMS)
171 #if ! defined(_SOCKADDR_LEN)
172 # ifdef getaddrinfo
173 # undef getaddrinfo
174 # endif
175 # include "TCPIP_IOCTL_ROUTINE"
176 #else
177 # include <ioctl.h>
178 #endif
179 #endif
181 #if defined(PYOS_OS2)
182 # define INCL_DOS
183 # define INCL_DOSERRORS
184 # define INCL_NOPMAPI
185 # include <os2.h>
186 #endif
188 #if defined(__sgi) && _COMPILER_VERSION>700 && !_SGIAPI
189 /* make sure that the reentrant (gethostbyaddr_r etc)
190 functions are declared correctly if compiling with
191 MIPSPro 7.x in ANSI C mode (default) */
193 /* XXX Using _SGIAPI is the wrong thing,
194 but I don't know what the right thing is. */
195 #undef _SGIAPI /* to avoid warning */
196 #define _SGIAPI 1
198 #undef _XOPEN_SOURCE
199 #include <sys/socket.h>
200 #include <sys/types.h>
201 #include <netinet/in.h>
202 #ifdef _SS_ALIGNSIZE
203 #define HAVE_GETADDRINFO 1
204 #define HAVE_GETNAMEINFO 1
205 #endif
207 #define HAVE_INET_PTON
208 #include <netdb.h>
209 #endif
211 /* Irix 6.5 fails to define this variable at all. This is needed
212 for both GCC and SGI's compiler. I'd say that the SGI headers
213 are just busted. */
214 #if defined(__sgi) && !defined(INET_ADDRSTRLEN)
215 #define INET_ADDRSTRLEN 16
216 #endif
218 /* Generic includes */
219 #include <sys/types.h>
221 /* Generic socket object definitions and includes */
222 #define PySocket_BUILDING_SOCKET
223 #include "socketmodule.h"
225 /* Addressing includes */
227 #ifndef MS_WINDOWS
229 /* Non-MS WINDOWS includes */
230 # include <netdb.h>
232 /* Headers needed for inet_ntoa() and inet_addr() */
233 # ifdef __BEOS__
234 # include <net/netdb.h>
235 # elif defined(PYOS_OS2) && defined(PYCC_VACPP)
236 # include <netdb.h>
237 typedef size_t socklen_t;
238 # else
239 # include <arpa/inet.h>
240 # endif
242 # ifndef RISCOS
243 # include <fcntl.h>
244 # else
245 # include <sys/ioctl.h>
246 # include <socklib.h>
247 # define NO_DUP
248 int h_errno; /* not used */
249 # define INET_ADDRSTRLEN 16
250 # endif
252 #else
254 /* MS_WINDOWS includes */
255 # include <fcntl.h>
257 #endif
259 #include <stddef.h>
261 #ifndef offsetof
262 # define offsetof(type, member) ((size_t)(&((type *)0)->member))
263 #endif
265 #ifndef O_NONBLOCK
266 # define O_NONBLOCK O_NDELAY
267 #endif
269 /* include Python's addrinfo.h unless it causes trouble */
270 #if defined(__sgi) && _COMPILER_VERSION>700 && defined(_SS_ALIGNSIZE)
271 /* Do not include addinfo.h on some newer IRIX versions.
272 * _SS_ALIGNSIZE is defined in sys/socket.h by 6.5.21,
273 * for example, but not by 6.5.10.
275 #elif defined(_MSC_VER) && _MSC_VER>1200
276 /* Do not include addrinfo.h for MSVC7 or greater. 'addrinfo' and
277 * EAI_* constants are defined in (the already included) ws2tcpip.h.
279 #else
280 # include "addrinfo.h"
281 #endif
283 #ifndef HAVE_INET_PTON
284 int inet_pton(int af, const char *src, void *dst);
285 const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
286 #endif
288 #ifdef __APPLE__
289 /* On OS X, getaddrinfo returns no error indication of lookup
290 failure, so we must use the emulation instead of the libinfo
291 implementation. Unfortunately, performing an autoconf test
292 for this bug would require DNS access for the machine performing
293 the configuration, which is not acceptable. Therefore, we
294 determine the bug just by checking for __APPLE__. If this bug
295 gets ever fixed, perhaps checking for sys/version.h would be
296 appropriate, which is 10/0 on the system with the bug. */
297 #ifndef HAVE_GETNAMEINFO
298 /* This bug seems to be fixed in Jaguar. Ths easiest way I could
299 Find to check for Jaguar is that it has getnameinfo(), which
300 older releases don't have */
301 #undef HAVE_GETADDRINFO
302 #endif
303 #endif
305 /* I know this is a bad practice, but it is the easiest... */
306 #if !defined(HAVE_GETADDRINFO)
307 /* avoid clashes with the C library definition of the symbol. */
308 #define getaddrinfo fake_getaddrinfo
309 #define gai_strerror fake_gai_strerror
310 #define freeaddrinfo fake_freeaddrinfo
311 #include "getaddrinfo.c"
312 #endif
313 #if !defined(HAVE_GETNAMEINFO)
314 #define getnameinfo fake_getnameinfo
315 #include "getnameinfo.c"
316 #endif
318 #if defined(MS_WINDOWS) || defined(__BEOS__)
319 /* BeOS suffers from the same socket dichotomy as Win32... - [cjh] */
320 /* seem to be a few differences in the API */
321 #define SOCKETCLOSE closesocket
322 #define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */
323 #endif
325 #ifdef MS_WIN32
326 #define EAFNOSUPPORT WSAEAFNOSUPPORT
327 #define snprintf _snprintf
328 #endif
330 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
331 #define SOCKETCLOSE soclose
332 #define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
333 #endif
335 #ifndef SOCKETCLOSE
336 #define SOCKETCLOSE close
337 #endif
339 #ifdef __VMS
340 /* TCP/IP Services for VMS uses a maximum send/revc buffer length of 65535 */
341 #define SEGMENT_SIZE 65535
342 #endif
344 #if defined(HAVE_BLUETOOTH_H) || defined(HAVE_BLUETOOTH_BLUETOOTH_H)
345 #define USE_BLUETOOTH 1
346 #if defined(__FreeBSD__)
347 #define BTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP
348 #define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM
349 #define sockaddr_l2 sockaddr_l2cap
350 #define sockaddr_rc sockaddr_rfcomm
351 #define _BT_SOCKADDR_MEMB(s, proto) &((s)->sock_addr)
352 #define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb)
353 #define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)
354 #else
355 #define _BT_SOCKADDR_MEMB(s, proto) (&((s)->sock_addr).bt_##proto)
356 #define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb)
357 #define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb)
358 #define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)
359 #endif
360 #endif
363 * Constants for getnameinfo()
365 #if !defined(NI_MAXHOST)
366 #define NI_MAXHOST 1025
367 #endif
368 #if !defined(NI_MAXSERV)
369 #define NI_MAXSERV 32
370 #endif
372 /* XXX There's a problem here: *static* functions are not supposed to have
373 a Py prefix (or use CapitalizedWords). Later... */
375 /* Global variable holding the exception type for errors detected
376 by this module (but not argument type or memory errors, etc.). */
377 static PyObject *socket_error;
378 static PyObject *socket_herror;
379 static PyObject *socket_gaierror;
380 static PyObject *socket_timeout;
382 #ifdef RISCOS
383 /* Global variable which is !=0 if Python is running in a RISC OS taskwindow */
384 static int taskwindow;
385 #endif
387 /* A forward reference to the socket type object.
388 The sock_type variable contains pointers to various functions,
389 some of which call new_sockobject(), which uses sock_type, so
390 there has to be a circular reference. */
391 static PyTypeObject sock_type;
393 /* Convenience function to raise an error according to errno
394 and return a NULL pointer from a function. */
396 static PyObject *
397 set_error(void)
399 #ifdef MS_WINDOWS
400 int err_no = WSAGetLastError();
401 static struct {
402 int no;
403 const char *msg;
404 } *msgp, msgs[] = {
405 {WSAEINTR, "Interrupted system call"},
406 {WSAEBADF, "Bad file descriptor"},
407 {WSAEACCES, "Permission denied"},
408 {WSAEFAULT, "Bad address"},
409 {WSAEINVAL, "Invalid argument"},
410 {WSAEMFILE, "Too many open files"},
411 {WSAEWOULDBLOCK,
412 "The socket operation could not complete "
413 "without blocking"},
414 {WSAEINPROGRESS, "Operation now in progress"},
415 {WSAEALREADY, "Operation already in progress"},
416 {WSAENOTSOCK, "Socket operation on non-socket"},
417 {WSAEDESTADDRREQ, "Destination address required"},
418 {WSAEMSGSIZE, "Message too long"},
419 {WSAEPROTOTYPE, "Protocol wrong type for socket"},
420 {WSAENOPROTOOPT, "Protocol not available"},
421 {WSAEPROTONOSUPPORT, "Protocol not supported"},
422 {WSAESOCKTNOSUPPORT, "Socket type not supported"},
423 {WSAEOPNOTSUPP, "Operation not supported"},
424 {WSAEPFNOSUPPORT, "Protocol family not supported"},
425 {WSAEAFNOSUPPORT, "Address family not supported"},
426 {WSAEADDRINUSE, "Address already in use"},
427 {WSAEADDRNOTAVAIL, "Can't assign requested address"},
428 {WSAENETDOWN, "Network is down"},
429 {WSAENETUNREACH, "Network is unreachable"},
430 {WSAENETRESET, "Network dropped connection on reset"},
431 {WSAECONNABORTED, "Software caused connection abort"},
432 {WSAECONNRESET, "Connection reset by peer"},
433 {WSAENOBUFS, "No buffer space available"},
434 {WSAEISCONN, "Socket is already connected"},
435 {WSAENOTCONN, "Socket is not connected"},
436 {WSAESHUTDOWN, "Can't send after socket shutdown"},
437 {WSAETOOMANYREFS, "Too many references: can't splice"},
438 {WSAETIMEDOUT, "Operation timed out"},
439 {WSAECONNREFUSED, "Connection refused"},
440 {WSAELOOP, "Too many levels of symbolic links"},
441 {WSAENAMETOOLONG, "File name too long"},
442 {WSAEHOSTDOWN, "Host is down"},
443 {WSAEHOSTUNREACH, "No route to host"},
444 {WSAENOTEMPTY, "Directory not empty"},
445 {WSAEPROCLIM, "Too many processes"},
446 {WSAEUSERS, "Too many users"},
447 {WSAEDQUOT, "Disc quota exceeded"},
448 {WSAESTALE, "Stale NFS file handle"},
449 {WSAEREMOTE, "Too many levels of remote in path"},
450 {WSASYSNOTREADY, "Network subsystem is unvailable"},
451 {WSAVERNOTSUPPORTED, "WinSock version is not supported"},
452 {WSANOTINITIALISED,
453 "Successful WSAStartup() not yet performed"},
454 {WSAEDISCON, "Graceful shutdown in progress"},
455 /* Resolver errors */
456 {WSAHOST_NOT_FOUND, "No such host is known"},
457 {WSATRY_AGAIN, "Host not found, or server failed"},
458 {WSANO_RECOVERY, "Unexpected server error encountered"},
459 {WSANO_DATA, "Valid name without requested data"},
460 {WSANO_ADDRESS, "No address, look for MX record"},
461 {0, NULL}
463 if (err_no) {
464 PyObject *v;
465 const char *msg = "winsock error";
467 for (msgp = msgs; msgp->msg; msgp++) {
468 if (err_no == msgp->no) {
469 msg = msgp->msg;
470 break;
474 v = Py_BuildValue("(is)", err_no, msg);
475 if (v != NULL) {
476 PyErr_SetObject(socket_error, v);
477 Py_DECREF(v);
479 return NULL;
481 else
482 #endif
484 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
485 if (sock_errno() != NO_ERROR) {
486 APIRET rc;
487 ULONG msglen;
488 char outbuf[100];
489 int myerrorcode = sock_errno();
491 /* Retrieve socket-related error message from MPTN.MSG file */
492 rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf),
493 myerrorcode - SOCBASEERR + 26,
494 "mptn.msg",
495 &msglen);
496 if (rc == NO_ERROR) {
497 PyObject *v;
499 /* OS/2 doesn't guarantee a terminator */
500 outbuf[msglen] = '\0';
501 if (strlen(outbuf) > 0) {
502 /* If non-empty msg, trim CRLF */
503 char *lastc = &outbuf[ strlen(outbuf)-1 ];
504 while (lastc > outbuf && isspace(*lastc)) {
505 /* Trim trailing whitespace (CRLF) */
506 *lastc-- = '\0';
509 v = Py_BuildValue("(is)", myerrorcode, outbuf);
510 if (v != NULL) {
511 PyErr_SetObject(socket_error, v);
512 Py_DECREF(v);
514 return NULL;
517 #endif
519 #if defined(RISCOS)
520 if (_inet_error.errnum != NULL) {
521 PyObject *v;
522 v = Py_BuildValue("(is)", errno, _inet_err());
523 if (v != NULL) {
524 PyErr_SetObject(socket_error, v);
525 Py_DECREF(v);
527 return NULL;
529 #endif
531 return PyErr_SetFromErrno(socket_error);
535 static PyObject *
536 set_herror(int h_error)
538 PyObject *v;
540 #ifdef HAVE_HSTRERROR
541 v = Py_BuildValue("(is)", h_error, (char *)hstrerror(h_error));
542 #else
543 v = Py_BuildValue("(is)", h_error, "host not found");
544 #endif
545 if (v != NULL) {
546 PyErr_SetObject(socket_herror, v);
547 Py_DECREF(v);
550 return NULL;
554 static PyObject *
555 set_gaierror(int error)
557 PyObject *v;
559 #ifdef EAI_SYSTEM
560 /* EAI_SYSTEM is not available on Windows XP. */
561 if (error == EAI_SYSTEM)
562 return set_error();
563 #endif
565 #ifdef HAVE_GAI_STRERROR
566 v = Py_BuildValue("(is)", error, gai_strerror(error));
567 #else
568 v = Py_BuildValue("(is)", error, "getaddrinfo failed");
569 #endif
570 if (v != NULL) {
571 PyErr_SetObject(socket_gaierror, v);
572 Py_DECREF(v);
575 return NULL;
578 /* Function to perform the setting of socket blocking mode
579 internally. block = (1 | 0). */
580 static int
581 internal_setblocking(PySocketSockObject *s, int block)
583 #ifndef RISCOS
584 #ifndef MS_WINDOWS
585 int delay_flag;
586 #endif
587 #endif
589 Py_BEGIN_ALLOW_THREADS
590 #ifdef __BEOS__
591 block = !block;
592 setsockopt(s->sock_fd, SOL_SOCKET, SO_NONBLOCK,
593 (void *)(&block), sizeof(int));
594 #else
595 #ifndef RISCOS
596 #ifndef MS_WINDOWS
597 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
598 block = !block;
599 ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block));
600 #elif defined(__VMS)
601 block = !block;
602 ioctl(s->sock_fd, FIONBIO, (char *)&block);
603 #else /* !PYOS_OS2 && !_VMS */
604 delay_flag = fcntl(s->sock_fd, F_GETFL, 0);
605 if (block)
606 delay_flag &= (~O_NONBLOCK);
607 else
608 delay_flag |= O_NONBLOCK;
609 fcntl(s->sock_fd, F_SETFL, delay_flag);
610 #endif /* !PYOS_OS2 */
611 #else /* MS_WINDOWS */
612 block = !block;
613 ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
614 #endif /* MS_WINDOWS */
615 #else /* RISCOS */
616 block = !block;
617 socketioctl(s->sock_fd, FIONBIO, (u_long*)&block);
618 #endif /* RISCOS */
619 #endif /* __BEOS__ */
620 Py_END_ALLOW_THREADS
622 /* Since these don't return anything */
623 return 1;
626 /* Do a select() on the socket, if necessary (sock_timeout > 0).
627 The argument writing indicates the direction.
628 This does not raise an exception; we'll let our caller do that
629 after they've reacquired the interpreter lock.
630 Returns 1 on timeout, 0 otherwise. */
631 static int
632 internal_select(PySocketSockObject *s, int writing)
634 fd_set fds;
635 struct timeval tv;
636 int n;
638 /* Nothing to do unless we're in timeout mode (not non-blocking) */
639 if (s->sock_timeout <= 0.0)
640 return 0;
642 /* Guard against closed socket */
643 if (s->sock_fd < 0)
644 return 0;
646 /* Construct the arguments to select */
647 tv.tv_sec = (int)s->sock_timeout;
648 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
649 FD_ZERO(&fds);
650 FD_SET(s->sock_fd, &fds);
652 /* See if the socket is ready */
653 if (writing)
654 n = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
655 else
656 n = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
657 if (n == 0)
658 return 1;
659 return 0;
662 /* Initialize a new socket object. */
664 static double defaulttimeout = -1.0; /* Default timeout for new sockets */
666 PyMODINIT_FUNC
667 init_sockobject(PySocketSockObject *s,
668 SOCKET_T fd, int family, int type, int proto)
670 #ifdef RISCOS
671 int block = 1;
672 #endif
673 s->sock_fd = fd;
674 s->sock_family = family;
675 s->sock_type = type;
676 s->sock_proto = proto;
677 s->sock_timeout = defaulttimeout;
679 s->errorhandler = &set_error;
681 if (defaulttimeout >= 0.0)
682 internal_setblocking(s, 0);
684 #ifdef RISCOS
685 if (taskwindow)
686 socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
687 #endif
691 /* Create a new socket object.
692 This just creates the object and initializes it.
693 If the creation fails, return NULL and set an exception (implicit
694 in NEWOBJ()). */
696 static PySocketSockObject *
697 new_sockobject(SOCKET_T fd, int family, int type, int proto)
699 PySocketSockObject *s;
700 s = (PySocketSockObject *)
701 PyType_GenericNew(&sock_type, NULL, NULL);
702 if (s != NULL)
703 init_sockobject(s, fd, family, type, proto);
704 return s;
708 /* Lock to allow python interpreter to continue, but only allow one
709 thread to be in gethostbyname or getaddrinfo */
710 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
711 PyThread_type_lock netdb_lock;
712 #endif
715 /* Convert a string specifying a host name or one of a few symbolic
716 names to a numeric IP address. This usually calls gethostbyname()
717 to do the work; the names "" and "<broadcast>" are special.
718 Return the length (IPv4 should be 4 bytes), or negative if
719 an error occurred; then an exception is raised. */
721 static int
722 setipaddr(char *name, struct sockaddr *addr_ret, size_t addr_ret_size, int af)
724 struct addrinfo hints, *res;
725 int error;
726 int d1, d2, d3, d4;
727 char ch;
729 memset((void *) addr_ret, '\0', sizeof(*addr_ret));
730 if (name[0] == '\0') {
731 int siz;
732 memset(&hints, 0, sizeof(hints));
733 hints.ai_family = af;
734 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
735 hints.ai_flags = AI_PASSIVE;
736 Py_BEGIN_ALLOW_THREADS
737 ACQUIRE_GETADDRINFO_LOCK
738 error = getaddrinfo(NULL, "0", &hints, &res);
739 Py_END_ALLOW_THREADS
740 /* We assume that those thread-unsafe getaddrinfo() versions
741 *are* safe regarding their return value, ie. that a
742 subsequent call to getaddrinfo() does not destroy the
743 outcome of the first call. */
744 RELEASE_GETADDRINFO_LOCK
745 if (error) {
746 set_gaierror(error);
747 return -1;
749 switch (res->ai_family) {
750 case AF_INET:
751 siz = 4;
752 break;
753 #ifdef ENABLE_IPV6
754 case AF_INET6:
755 siz = 16;
756 break;
757 #endif
758 default:
759 freeaddrinfo(res);
760 PyErr_SetString(socket_error,
761 "unsupported address family");
762 return -1;
764 if (res->ai_next) {
765 freeaddrinfo(res);
766 PyErr_SetString(socket_error,
767 "wildcard resolved to multiple address");
768 return -1;
770 if (res->ai_addrlen < addr_ret_size)
771 addr_ret_size = res->ai_addrlen;
772 memcpy(addr_ret, res->ai_addr, addr_ret_size);
773 freeaddrinfo(res);
774 return siz;
776 if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
777 struct sockaddr_in *sin;
778 if (af != AF_INET && af != AF_UNSPEC) {
779 PyErr_SetString(socket_error,
780 "address family mismatched");
781 return -1;
783 sin = (struct sockaddr_in *)addr_ret;
784 memset((void *) sin, '\0', sizeof(*sin));
785 sin->sin_family = AF_INET;
786 #ifdef HAVE_SOCKADDR_SA_LEN
787 sin->sin_len = sizeof(*sin);
788 #endif
789 sin->sin_addr.s_addr = INADDR_BROADCAST;
790 return sizeof(sin->sin_addr);
792 if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 &&
793 0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 &&
794 0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) {
795 struct sockaddr_in *sin;
796 sin = (struct sockaddr_in *)addr_ret;
797 sin->sin_addr.s_addr = htonl(
798 ((long) d1 << 24) | ((long) d2 << 16) |
799 ((long) d3 << 8) | ((long) d4 << 0));
800 sin->sin_family = AF_INET;
801 #ifdef HAVE_SOCKADDR_SA_LEN
802 sin->sin_len = sizeof(*sin);
803 #endif
804 return 4;
806 memset(&hints, 0, sizeof(hints));
807 hints.ai_family = af;
808 Py_BEGIN_ALLOW_THREADS
809 ACQUIRE_GETADDRINFO_LOCK
810 error = getaddrinfo(name, NULL, &hints, &res);
811 #if defined(__digital__) && defined(__unix__)
812 if (error == EAI_NONAME && af == AF_UNSPEC) {
813 /* On Tru64 V5.1, numeric-to-addr conversion fails
814 if no address family is given. Assume IPv4 for now.*/
815 hints.ai_family = AF_INET;
816 error = getaddrinfo(name, NULL, &hints, &res);
818 #endif
819 Py_END_ALLOW_THREADS
820 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
821 if (error) {
822 set_gaierror(error);
823 return -1;
825 if (res->ai_addrlen < addr_ret_size)
826 addr_ret_size = res->ai_addrlen;
827 memcpy((char *) addr_ret, res->ai_addr, addr_ret_size);
828 freeaddrinfo(res);
829 switch (addr_ret->sa_family) {
830 case AF_INET:
831 return 4;
832 #ifdef ENABLE_IPV6
833 case AF_INET6:
834 return 16;
835 #endif
836 default:
837 PyErr_SetString(socket_error, "unknown address family");
838 return -1;
843 /* Create a string object representing an IP address.
844 This is always a string of the form 'dd.dd.dd.dd' (with variable
845 size numbers). */
847 static PyObject *
848 makeipaddr(struct sockaddr *addr, int addrlen)
850 char buf[NI_MAXHOST];
851 int error;
853 error = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0,
854 NI_NUMERICHOST);
855 if (error) {
856 set_gaierror(error);
857 return NULL;
859 return PyString_FromString(buf);
863 #ifdef USE_BLUETOOTH
864 /* Convert a string representation of a Bluetooth address into a numeric
865 address. Returns the length (6), or raises an exception and returns -1 if
866 an error occurred. */
868 static int
869 setbdaddr(char *name, bdaddr_t *bdaddr)
871 unsigned int b0, b1, b2, b3, b4, b5;
872 char ch;
873 int n;
875 n = sscanf(name, "%X:%X:%X:%X:%X:%X%c",
876 &b5, &b4, &b3, &b2, &b1, &b0, &ch);
877 if (n == 6 && (b0 | b1 | b2 | b3 | b4 | b5) < 256) {
878 bdaddr->b[0] = b0;
879 bdaddr->b[1] = b1;
880 bdaddr->b[2] = b2;
881 bdaddr->b[3] = b3;
882 bdaddr->b[4] = b4;
883 bdaddr->b[5] = b5;
884 return 6;
885 } else {
886 PyErr_SetString(socket_error, "bad bluetooth address");
887 return -1;
891 /* Create a string representation of the Bluetooth address. This is always a
892 string of the form 'XX:XX:XX:XX:XX:XX' where XX is a two digit hexadecimal
893 value (zero padded if necessary). */
895 static PyObject *
896 makebdaddr(bdaddr_t *bdaddr)
898 char buf[(6 * 2) + 5 + 1];
900 sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
901 bdaddr->b[5], bdaddr->b[4], bdaddr->b[3],
902 bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]);
903 return PyString_FromString(buf);
905 #endif
908 /* Create an object representing the given socket address,
909 suitable for passing it back to bind(), connect() etc.
910 The family field of the sockaddr structure is inspected
911 to determine what kind of address it really is. */
913 /*ARGSUSED*/
914 static PyObject *
915 makesockaddr(int sockfd, struct sockaddr *addr, int addrlen, int proto)
917 if (addrlen == 0) {
918 /* No address -- may be recvfrom() from known socket */
919 Py_INCREF(Py_None);
920 return Py_None;
923 #ifdef __BEOS__
924 /* XXX: BeOS version of accept() doesn't set family correctly */
925 addr->sa_family = AF_INET;
926 #endif
928 switch (addr->sa_family) {
930 case AF_INET:
932 struct sockaddr_in *a;
933 PyObject *addrobj = makeipaddr(addr, sizeof(*a));
934 PyObject *ret = NULL;
935 if (addrobj) {
936 a = (struct sockaddr_in *)addr;
937 ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
938 Py_DECREF(addrobj);
940 return ret;
943 #if defined(AF_UNIX)
944 case AF_UNIX:
946 struct sockaddr_un *a = (struct sockaddr_un *) addr;
947 return PyString_FromString(a->sun_path);
949 #endif /* AF_UNIX */
951 #ifdef ENABLE_IPV6
952 case AF_INET6:
954 struct sockaddr_in6 *a;
955 PyObject *addrobj = makeipaddr(addr, sizeof(*a));
956 PyObject *ret = NULL;
957 if (addrobj) {
958 a = (struct sockaddr_in6 *)addr;
959 ret = Py_BuildValue("Oiii",
960 addrobj,
961 ntohs(a->sin6_port),
962 a->sin6_flowinfo,
963 a->sin6_scope_id);
964 Py_DECREF(addrobj);
966 return ret;
968 #endif
970 #ifdef USE_BLUETOOTH
971 case AF_BLUETOOTH:
972 switch (proto) {
974 case BTPROTO_L2CAP:
976 struct sockaddr_l2 *a = (struct sockaddr_l2 *) addr;
977 PyObject *addrobj = makebdaddr(&_BT_L2_MEMB(a, bdaddr));
978 PyObject *ret = NULL;
979 if (addrobj) {
980 ret = Py_BuildValue("Oi",
981 addrobj,
982 _BT_L2_MEMB(a, psm));
983 Py_DECREF(addrobj);
985 return ret;
988 case BTPROTO_RFCOMM:
990 struct sockaddr_rc *a = (struct sockaddr_rc *) addr;
991 PyObject *addrobj = makebdaddr(&_BT_RC_MEMB(a, bdaddr));
992 PyObject *ret = NULL;
993 if (addrobj) {
994 ret = Py_BuildValue("Oi",
995 addrobj,
996 _BT_RC_MEMB(a, channel));
997 Py_DECREF(addrobj);
999 return ret;
1002 #if !defined(__FreeBSD__)
1003 case BTPROTO_SCO:
1005 struct sockaddr_sco *a = (struct sockaddr_sco *) addr;
1006 return makebdaddr(&_BT_SCO_MEMB(a, bdaddr));
1008 #endif
1011 #endif
1013 #ifdef HAVE_NETPACKET_PACKET_H
1014 case AF_PACKET:
1016 struct sockaddr_ll *a = (struct sockaddr_ll *)addr;
1017 char *ifname = "";
1018 struct ifreq ifr;
1019 /* need to look up interface name give index */
1020 if (a->sll_ifindex) {
1021 ifr.ifr_ifindex = a->sll_ifindex;
1022 if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0)
1023 ifname = ifr.ifr_name;
1025 return Py_BuildValue("shbhs#",
1026 ifname,
1027 ntohs(a->sll_protocol),
1028 a->sll_pkttype,
1029 a->sll_hatype,
1030 a->sll_addr,
1031 a->sll_halen);
1033 #endif
1035 /* More cases here... */
1037 default:
1038 /* If we don't know the address family, don't raise an
1039 exception -- return it as a tuple. */
1040 return Py_BuildValue("is#",
1041 addr->sa_family,
1042 addr->sa_data,
1043 sizeof(addr->sa_data));
1049 /* Parse a socket address argument according to the socket object's
1050 address family. Return 1 if the address was in the proper format,
1051 0 of not. The address is returned through addr_ret, its length
1052 through len_ret. */
1054 static int
1055 getsockaddrarg(PySocketSockObject *s, PyObject *args,
1056 struct sockaddr **addr_ret, int *len_ret)
1058 switch (s->sock_family) {
1060 #if defined(AF_UNIX)
1061 case AF_UNIX:
1063 struct sockaddr_un* addr;
1064 char *path;
1065 int len;
1066 addr = (struct sockaddr_un*)&(s->sock_addr).un;
1067 if (!PyArg_Parse(args, "t#", &path, &len))
1068 return 0;
1069 if (len > sizeof addr->sun_path) {
1070 PyErr_SetString(socket_error,
1071 "AF_UNIX path too long");
1072 return 0;
1074 addr->sun_family = s->sock_family;
1075 memcpy(addr->sun_path, path, len);
1076 addr->sun_path[len] = 0;
1077 *addr_ret = (struct sockaddr *) addr;
1078 #if defined(PYOS_OS2)
1079 *len_ret = sizeof(*addr);
1080 #else
1081 *len_ret = len + sizeof(*addr) - sizeof(addr->sun_path);
1082 #endif
1083 return 1;
1085 #endif /* AF_UNIX */
1087 case AF_INET:
1089 struct sockaddr_in* addr;
1090 char *host;
1091 int port, result;
1092 addr=(struct sockaddr_in*)&(s->sock_addr).in;
1093 if (!PyTuple_Check(args)) {
1094 PyErr_Format(
1095 PyExc_TypeError,
1096 "getsockaddrarg: "
1097 "AF_INET address must be tuple, not %.500s",
1098 args->ob_type->tp_name);
1099 return 0;
1101 if (!PyArg_ParseTuple(args, "eti:getsockaddrarg",
1102 "idna", &host, &port))
1103 return 0;
1104 result = setipaddr(host, (struct sockaddr *)addr,
1105 sizeof(*addr), AF_INET);
1106 PyMem_Free(host);
1107 if (result < 0)
1108 return 0;
1109 addr->sin_family = AF_INET;
1110 addr->sin_port = htons((short)port);
1111 *addr_ret = (struct sockaddr *) addr;
1112 *len_ret = sizeof *addr;
1113 return 1;
1116 #ifdef ENABLE_IPV6
1117 case AF_INET6:
1119 struct sockaddr_in6* addr;
1120 char *host;
1121 int port, flowinfo, scope_id, result;
1122 addr = (struct sockaddr_in6*)&(s->sock_addr).in6;
1123 flowinfo = scope_id = 0;
1124 if (!PyArg_ParseTuple(args, "eti|ii",
1125 "idna", &host, &port, &flowinfo,
1126 &scope_id)) {
1127 return 0;
1129 result = setipaddr(host, (struct sockaddr *)addr,
1130 sizeof(*addr), AF_INET6);
1131 PyMem_Free(host);
1132 if (result < 0)
1133 return 0;
1134 addr->sin6_family = s->sock_family;
1135 addr->sin6_port = htons((short)port);
1136 addr->sin6_flowinfo = flowinfo;
1137 addr->sin6_scope_id = scope_id;
1138 *addr_ret = (struct sockaddr *) addr;
1139 *len_ret = sizeof *addr;
1140 return 1;
1142 #endif
1144 #ifdef USE_BLUETOOTH
1145 case AF_BLUETOOTH:
1147 switch (s->sock_proto) {
1148 case BTPROTO_L2CAP:
1150 struct sockaddr_l2 *addr = (struct sockaddr_l2 *) _BT_SOCKADDR_MEMB(s, l2);
1151 char *straddr;
1153 _BT_L2_MEMB(addr, family) = AF_BLUETOOTH;
1154 if (!PyArg_ParseTuple(args, "si", &straddr,
1155 &_BT_L2_MEMB(addr, psm))) {
1156 PyErr_SetString(socket_error, "getsockaddrarg: "
1157 "wrong format");
1158 return 0;
1160 if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0)
1161 return 0;
1163 *addr_ret = (struct sockaddr *) addr;
1164 *len_ret = sizeof *addr;
1165 return 1;
1167 case BTPROTO_RFCOMM:
1169 struct sockaddr_rc *addr = (struct sockaddr_rc *) _BT_SOCKADDR_MEMB(s, rc);
1170 char *straddr;
1172 _BT_RC_MEMB(addr, family) = AF_BLUETOOTH;
1173 if (!PyArg_ParseTuple(args, "si", &straddr,
1174 &_BT_RC_MEMB(addr, channel))) {
1175 PyErr_SetString(socket_error, "getsockaddrarg: "
1176 "wrong format");
1177 return 0;
1179 if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0)
1180 return 0;
1182 *addr_ret = (struct sockaddr *) addr;
1183 *len_ret = sizeof *addr;
1184 return 1;
1186 #if !defined(__FreeBSD__)
1187 case BTPROTO_SCO:
1189 struct sockaddr_sco *addr = (struct sockaddr_sco *) _BT_SOCKADDR_MEMB(s, sco);
1190 char *straddr;
1192 _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH;
1193 straddr = PyString_AsString(args);
1194 if (straddr == NULL) {
1195 PyErr_SetString(socket_error, "getsockaddrarg: "
1196 "wrong format");
1197 return 0;
1199 if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0)
1200 return 0;
1202 *addr_ret = (struct sockaddr *) addr;
1203 *len_ret = sizeof *addr;
1204 return 1;
1206 #endif
1207 default:
1208 PyErr_SetString(socket_error, "getsockaddrarg: unknown Bluetooth protocol");
1209 return 0;
1212 #endif
1214 #ifdef HAVE_NETPACKET_PACKET_H
1215 case AF_PACKET:
1217 struct sockaddr_ll* addr;
1218 struct ifreq ifr;
1219 char *interfaceName;
1220 int protoNumber;
1221 int hatype = 0;
1222 int pkttype = 0;
1223 char *haddr = NULL;
1224 unsigned int halen = 0;
1226 if (!PyArg_ParseTuple(args, "si|iis#", &interfaceName,
1227 &protoNumber, &pkttype, &hatype,
1228 &haddr, &halen))
1229 return 0;
1230 strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name));
1231 ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
1232 if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
1233 s->errorhandler();
1234 return 0;
1236 addr = &(s->sock_addr.ll);
1237 addr->sll_family = AF_PACKET;
1238 addr->sll_protocol = htons((short)protoNumber);
1239 addr->sll_ifindex = ifr.ifr_ifindex;
1240 addr->sll_pkttype = pkttype;
1241 addr->sll_hatype = hatype;
1242 if (halen > 8) {
1243 PyErr_SetString(PyExc_ValueError,
1244 "Hardware address must be 8 bytes or less");
1245 return 0;
1247 if (halen != 0) {
1248 memcpy(&addr->sll_addr, haddr, halen);
1250 addr->sll_halen = halen;
1251 *addr_ret = (struct sockaddr *) addr;
1252 *len_ret = sizeof *addr;
1253 return 1;
1255 #endif
1257 /* More cases here... */
1259 default:
1260 PyErr_SetString(socket_error, "getsockaddrarg: bad family");
1261 return 0;
1267 /* Get the address length according to the socket object's address family.
1268 Return 1 if the family is known, 0 otherwise. The length is returned
1269 through len_ret. */
1271 static int
1272 getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
1274 switch (s->sock_family) {
1276 #if defined(AF_UNIX)
1277 case AF_UNIX:
1279 *len_ret = sizeof (struct sockaddr_un);
1280 return 1;
1282 #endif /* AF_UNIX */
1284 case AF_INET:
1286 *len_ret = sizeof (struct sockaddr_in);
1287 return 1;
1290 #ifdef ENABLE_IPV6
1291 case AF_INET6:
1293 *len_ret = sizeof (struct sockaddr_in6);
1294 return 1;
1296 #endif
1298 #ifdef USE_BLUETOOTH
1299 case AF_BLUETOOTH:
1301 switch(s->sock_proto)
1304 case BTPROTO_L2CAP:
1305 *len_ret = sizeof (struct sockaddr_l2);
1306 return 1;
1307 case BTPROTO_RFCOMM:
1308 *len_ret = sizeof (struct sockaddr_rc);
1309 return 1;
1310 #if !defined(__FreeBSD__)
1311 case BTPROTO_SCO:
1312 *len_ret = sizeof (struct sockaddr_sco);
1313 return 1;
1314 #endif
1315 default:
1316 PyErr_SetString(socket_error, "getsockaddrlen: "
1317 "unknown BT protocol");
1318 return 0;
1322 #endif
1324 #ifdef HAVE_NETPACKET_PACKET_H
1325 case AF_PACKET:
1327 *len_ret = sizeof (struct sockaddr_ll);
1328 return 1;
1330 #endif
1332 /* More cases here... */
1334 default:
1335 PyErr_SetString(socket_error, "getsockaddrlen: bad family");
1336 return 0;
1342 /* s.accept() method */
1344 static PyObject *
1345 sock_accept(PySocketSockObject *s)
1347 char addrbuf[256];
1348 SOCKET_T newfd;
1349 socklen_t addrlen;
1350 PyObject *sock = NULL;
1351 PyObject *addr = NULL;
1352 PyObject *res = NULL;
1353 int timeout;
1355 if (!getsockaddrlen(s, &addrlen))
1356 return NULL;
1357 memset(addrbuf, 0, addrlen);
1359 #ifdef MS_WINDOWS
1360 newfd = INVALID_SOCKET;
1361 #else
1362 newfd = -1;
1363 #endif
1365 Py_BEGIN_ALLOW_THREADS
1366 timeout = internal_select(s, 0);
1367 if (!timeout)
1368 newfd = accept(s->sock_fd, (struct sockaddr *) addrbuf,
1369 &addrlen);
1370 Py_END_ALLOW_THREADS
1372 if (timeout) {
1373 PyErr_SetString(socket_timeout, "timed out");
1374 return NULL;
1377 #ifdef MS_WINDOWS
1378 if (newfd == INVALID_SOCKET)
1379 #else
1380 if (newfd < 0)
1381 #endif
1382 return s->errorhandler();
1384 /* Create the new object with unspecified family,
1385 to avoid calls to bind() etc. on it. */
1386 sock = (PyObject *) new_sockobject(newfd,
1387 s->sock_family,
1388 s->sock_type,
1389 s->sock_proto);
1391 if (sock == NULL) {
1392 SOCKETCLOSE(newfd);
1393 goto finally;
1395 addr = makesockaddr(s->sock_fd, (struct sockaddr *)addrbuf,
1396 addrlen, s->sock_proto);
1397 if (addr == NULL)
1398 goto finally;
1400 res = PyTuple_Pack(2, sock, addr);
1402 finally:
1403 Py_XDECREF(sock);
1404 Py_XDECREF(addr);
1405 return res;
1408 PyDoc_STRVAR(accept_doc,
1409 "accept() -> (socket object, address info)\n\
1411 Wait for an incoming connection. Return a new socket representing the\n\
1412 connection, and the address of the client. For IP sockets, the address\n\
1413 info is a pair (hostaddr, port).");
1415 /* s.setblocking(flag) method. Argument:
1416 False -- non-blocking mode; same as settimeout(0)
1417 True -- blocking mode; same as settimeout(None)
1420 static PyObject *
1421 sock_setblocking(PySocketSockObject *s, PyObject *arg)
1423 int block;
1425 block = PyInt_AsLong(arg);
1426 if (block == -1 && PyErr_Occurred())
1427 return NULL;
1429 s->sock_timeout = block ? -1.0 : 0.0;
1430 internal_setblocking(s, block);
1432 Py_INCREF(Py_None);
1433 return Py_None;
1436 PyDoc_STRVAR(setblocking_doc,
1437 "setblocking(flag)\n\
1439 Set the socket to blocking (flag is true) or non-blocking (false).\n\
1440 setblocking(True) is equivalent to settimeout(None);\n\
1441 setblocking(False) is equivalent to settimeout(0.0).");
1443 /* s.settimeout(timeout) method. Argument:
1444 None -- no timeout, blocking mode; same as setblocking(True)
1445 0.0 -- non-blocking mode; same as setblocking(False)
1446 > 0 -- timeout mode; operations time out after timeout seconds
1447 < 0 -- illegal; raises an exception
1449 static PyObject *
1450 sock_settimeout(PySocketSockObject *s, PyObject *arg)
1452 double timeout;
1454 if (arg == Py_None)
1455 timeout = -1.0;
1456 else {
1457 timeout = PyFloat_AsDouble(arg);
1458 if (timeout < 0.0) {
1459 if (!PyErr_Occurred())
1460 PyErr_SetString(PyExc_ValueError,
1461 "Timeout value out of range");
1462 return NULL;
1466 s->sock_timeout = timeout;
1467 internal_setblocking(s, timeout < 0.0);
1469 Py_INCREF(Py_None);
1470 return Py_None;
1473 PyDoc_STRVAR(settimeout_doc,
1474 "settimeout(timeout)\n\
1476 Set a timeout on socket operations. 'timeout' can be a float,\n\
1477 giving in seconds, or None. Setting a timeout of None disables\n\
1478 the timeout feature and is equivalent to setblocking(1).\n\
1479 Setting a timeout of zero is the same as setblocking(0).");
1481 /* s.gettimeout() method.
1482 Returns the timeout associated with a socket. */
1483 static PyObject *
1484 sock_gettimeout(PySocketSockObject *s)
1486 if (s->sock_timeout < 0.0) {
1487 Py_INCREF(Py_None);
1488 return Py_None;
1490 else
1491 return PyFloat_FromDouble(s->sock_timeout);
1494 PyDoc_STRVAR(gettimeout_doc,
1495 "gettimeout() -> timeout\n\
1497 Returns the timeout in floating seconds associated with socket \n\
1498 operations. A timeout of None indicates that timeouts on socket \n\
1499 operations are disabled.");
1501 #ifdef RISCOS
1502 /* s.sleeptaskw(1 | 0) method */
1504 static PyObject *
1505 sock_sleeptaskw(PySocketSockObject *s,PyObject *arg)
1507 int block;
1508 block = PyInt_AsLong(arg);
1509 if (block == -1 && PyErr_Occurred())
1510 return NULL;
1511 Py_BEGIN_ALLOW_THREADS
1512 socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
1513 Py_END_ALLOW_THREADS
1515 Py_INCREF(Py_None);
1516 return Py_None;
1518 PyDoc_STRVAR(sleeptaskw_doc,
1519 "sleeptaskw(flag)\n\
1521 Allow sleeps in taskwindows.");
1522 #endif
1525 /* s.setsockopt() method.
1526 With an integer third argument, sets an integer option.
1527 With a string third argument, sets an option from a buffer;
1528 use optional built-in module 'struct' to encode the string. */
1530 static PyObject *
1531 sock_setsockopt(PySocketSockObject *s, PyObject *args)
1533 int level;
1534 int optname;
1535 int res;
1536 char *buf;
1537 int buflen;
1538 int flag;
1540 if (PyArg_ParseTuple(args, "iii:setsockopt",
1541 &level, &optname, &flag)) {
1542 buf = (char *) &flag;
1543 buflen = sizeof flag;
1545 else {
1546 PyErr_Clear();
1547 if (!PyArg_ParseTuple(args, "iis#:setsockopt",
1548 &level, &optname, &buf, &buflen))
1549 return NULL;
1551 res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen);
1552 if (res < 0)
1553 return s->errorhandler();
1554 Py_INCREF(Py_None);
1555 return Py_None;
1558 PyDoc_STRVAR(setsockopt_doc,
1559 "setsockopt(level, option, value)\n\
1561 Set a socket option. See the Unix manual for level and option.\n\
1562 The value argument can either be an integer or a string.");
1565 /* s.getsockopt() method.
1566 With two arguments, retrieves an integer option.
1567 With a third integer argument, retrieves a string buffer of that size;
1568 use optional built-in module 'struct' to decode the string. */
1570 static PyObject *
1571 sock_getsockopt(PySocketSockObject *s, PyObject *args)
1573 int level;
1574 int optname;
1575 int res;
1576 PyObject *buf;
1577 socklen_t buflen = 0;
1579 #ifdef __BEOS__
1580 /* We have incomplete socket support. */
1581 PyErr_SetString(socket_error, "getsockopt not supported");
1582 return NULL;
1583 #else
1585 if (!PyArg_ParseTuple(args, "ii|i:getsockopt",
1586 &level, &optname, &buflen))
1587 return NULL;
1589 if (buflen == 0) {
1590 int flag = 0;
1591 socklen_t flagsize = sizeof flag;
1592 res = getsockopt(s->sock_fd, level, optname,
1593 (void *)&flag, &flagsize);
1594 if (res < 0)
1595 return s->errorhandler();
1596 return PyInt_FromLong(flag);
1598 #ifdef __VMS
1599 if (buflen > 1024) {
1600 #else
1601 if (buflen <= 0 || buflen > 1024) {
1602 #endif
1603 PyErr_SetString(socket_error,
1604 "getsockopt buflen out of range");
1605 return NULL;
1607 buf = PyString_FromStringAndSize((char *)NULL, buflen);
1608 if (buf == NULL)
1609 return NULL;
1610 res = getsockopt(s->sock_fd, level, optname,
1611 (void *)PyString_AS_STRING(buf), &buflen);
1612 if (res < 0) {
1613 Py_DECREF(buf);
1614 return s->errorhandler();
1616 _PyString_Resize(&buf, buflen);
1617 return buf;
1618 #endif /* __BEOS__ */
1621 PyDoc_STRVAR(getsockopt_doc,
1622 "getsockopt(level, option[, buffersize]) -> value\n\
1624 Get a socket option. See the Unix manual for level and option.\n\
1625 If a nonzero buffersize argument is given, the return value is a\n\
1626 string of that length; otherwise it is an integer.");
1629 /* s.bind(sockaddr) method */
1631 static PyObject *
1632 sock_bind(PySocketSockObject *s, PyObject *addro)
1634 struct sockaddr *addr;
1635 int addrlen;
1636 int res;
1638 if (!getsockaddrarg(s, addro, &addr, &addrlen))
1639 return NULL;
1640 Py_BEGIN_ALLOW_THREADS
1641 res = bind(s->sock_fd, addr, addrlen);
1642 Py_END_ALLOW_THREADS
1643 if (res < 0)
1644 return s->errorhandler();
1645 Py_INCREF(Py_None);
1646 return Py_None;
1649 PyDoc_STRVAR(bind_doc,
1650 "bind(address)\n\
1652 Bind the socket to a local address. For IP sockets, the address is a\n\
1653 pair (host, port); the host must refer to the local host. For raw packet\n\
1654 sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");
1657 /* s.close() method.
1658 Set the file descriptor to -1 so operations tried subsequently
1659 will surely fail. */
1661 static PyObject *
1662 sock_close(PySocketSockObject *s)
1664 SOCKET_T fd;
1666 if ((fd = s->sock_fd) != -1) {
1667 s->sock_fd = -1;
1668 Py_BEGIN_ALLOW_THREADS
1669 (void) SOCKETCLOSE(fd);
1670 Py_END_ALLOW_THREADS
1672 Py_INCREF(Py_None);
1673 return Py_None;
1676 PyDoc_STRVAR(close_doc,
1677 "close()\n\
1679 Close the socket. It cannot be used after this call.");
1681 static int
1682 internal_connect(PySocketSockObject *s, struct sockaddr *addr, int addrlen,
1683 int *timeoutp)
1685 int res, timeout;
1687 timeout = 0;
1688 res = connect(s->sock_fd, addr, addrlen);
1690 #ifdef MS_WINDOWS
1692 if (s->sock_timeout > 0.0) {
1693 if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK) {
1694 /* This is a mess. Best solution: trust select */
1695 fd_set fds;
1696 fd_set fds_exc;
1697 struct timeval tv;
1698 tv.tv_sec = (int)s->sock_timeout;
1699 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1700 FD_ZERO(&fds);
1701 FD_SET(s->sock_fd, &fds);
1702 FD_ZERO(&fds_exc);
1703 FD_SET(s->sock_fd, &fds_exc);
1704 res = select(s->sock_fd+1, NULL, &fds, &fds_exc, &tv);
1705 if (res == 0) {
1706 res = WSAEWOULDBLOCK;
1707 timeout = 1;
1708 } else if (res > 0) {
1709 if (FD_ISSET(s->sock_fd, &fds))
1710 /* The socket is in the writeable set - this
1711 means connected */
1712 res = 0;
1713 else {
1714 /* As per MS docs, we need to call getsockopt()
1715 to get the underlying error */
1716 int res_size = sizeof res;
1717 /* It must be in the exception set */
1718 assert(FD_ISSET(s->sock_fd, &fds_exc));
1719 if (0 == getsockopt(s->sock_fd, SOL_SOCKET, SO_ERROR,
1720 (char *)&res, &res_size))
1721 /* getsockopt also clears WSAGetLastError,
1722 so reset it back. */
1723 WSASetLastError(res);
1724 else
1725 res = WSAGetLastError();
1728 /* else if (res < 0) an error occurred */
1732 if (res < 0)
1733 res = WSAGetLastError();
1735 #else
1737 if (s->sock_timeout > 0.0) {
1738 if (res < 0 && errno == EINPROGRESS) {
1739 timeout = internal_select(s, 1);
1740 res = connect(s->sock_fd, addr, addrlen);
1741 if (res < 0 && errno == EISCONN)
1742 res = 0;
1746 if (res < 0)
1747 res = errno;
1749 #endif
1750 *timeoutp = timeout;
1752 return res;
1755 /* s.connect(sockaddr) method */
1757 static PyObject *
1758 sock_connect(PySocketSockObject *s, PyObject *addro)
1760 struct sockaddr *addr;
1761 int addrlen;
1762 int res;
1763 int timeout;
1765 if (!getsockaddrarg(s, addro, &addr, &addrlen))
1766 return NULL;
1768 Py_BEGIN_ALLOW_THREADS
1769 res = internal_connect(s, addr, addrlen, &timeout);
1770 Py_END_ALLOW_THREADS
1772 if (timeout) {
1773 PyErr_SetString(socket_timeout, "timed out");
1774 return NULL;
1776 if (res != 0)
1777 return s->errorhandler();
1778 Py_INCREF(Py_None);
1779 return Py_None;
1782 PyDoc_STRVAR(connect_doc,
1783 "connect(address)\n\
1785 Connect the socket to a remote address. For IP sockets, the address\n\
1786 is a pair (host, port).");
1789 /* s.connect_ex(sockaddr) method */
1791 static PyObject *
1792 sock_connect_ex(PySocketSockObject *s, PyObject *addro)
1794 struct sockaddr *addr;
1795 int addrlen;
1796 int res;
1797 int timeout;
1799 if (!getsockaddrarg(s, addro, &addr, &addrlen))
1800 return NULL;
1802 Py_BEGIN_ALLOW_THREADS
1803 res = internal_connect(s, addr, addrlen, &timeout);
1804 Py_END_ALLOW_THREADS
1806 return PyInt_FromLong((long) res);
1809 PyDoc_STRVAR(connect_ex_doc,
1810 "connect_ex(address) -> errno\n\
1812 This is like connect(address), but returns an error code (the errno value)\n\
1813 instead of raising an exception when an error occurs.");
1816 /* s.fileno() method */
1818 static PyObject *
1819 sock_fileno(PySocketSockObject *s)
1821 #if SIZEOF_SOCKET_T <= SIZEOF_LONG
1822 return PyInt_FromLong((long) s->sock_fd);
1823 #else
1824 return PyLong_FromLongLong((PY_LONG_LONG)s->sock_fd);
1825 #endif
1828 PyDoc_STRVAR(fileno_doc,
1829 "fileno() -> integer\n\
1831 Return the integer file descriptor of the socket.");
1834 #ifndef NO_DUP
1835 /* s.dup() method */
1837 static PyObject *
1838 sock_dup(PySocketSockObject *s)
1840 SOCKET_T newfd;
1841 PyObject *sock;
1843 newfd = dup(s->sock_fd);
1844 if (newfd < 0)
1845 return s->errorhandler();
1846 sock = (PyObject *) new_sockobject(newfd,
1847 s->sock_family,
1848 s->sock_type,
1849 s->sock_proto);
1850 if (sock == NULL)
1851 SOCKETCLOSE(newfd);
1852 return sock;
1855 PyDoc_STRVAR(dup_doc,
1856 "dup() -> socket object\n\
1858 Return a new socket object connected to the same system resource.");
1860 #endif
1863 /* s.getsockname() method */
1865 static PyObject *
1866 sock_getsockname(PySocketSockObject *s)
1868 char addrbuf[256];
1869 int res;
1870 socklen_t addrlen;
1872 if (!getsockaddrlen(s, &addrlen))
1873 return NULL;
1874 memset(addrbuf, 0, addrlen);
1875 Py_BEGIN_ALLOW_THREADS
1876 res = getsockname(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
1877 Py_END_ALLOW_THREADS
1878 if (res < 0)
1879 return s->errorhandler();
1880 return makesockaddr(s->sock_fd, (struct sockaddr *) addrbuf, addrlen,
1881 s->sock_proto);
1884 PyDoc_STRVAR(getsockname_doc,
1885 "getsockname() -> address info\n\
1887 Return the address of the local endpoint. For IP sockets, the address\n\
1888 info is a pair (hostaddr, port).");
1891 #ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
1892 /* s.getpeername() method */
1894 static PyObject *
1895 sock_getpeername(PySocketSockObject *s)
1897 char addrbuf[256];
1898 int res;
1899 socklen_t addrlen;
1901 if (!getsockaddrlen(s, &addrlen))
1902 return NULL;
1903 memset(addrbuf, 0, addrlen);
1904 Py_BEGIN_ALLOW_THREADS
1905 res = getpeername(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
1906 Py_END_ALLOW_THREADS
1907 if (res < 0)
1908 return s->errorhandler();
1909 return makesockaddr(s->sock_fd, (struct sockaddr *) addrbuf, addrlen,
1910 s->sock_proto);
1913 PyDoc_STRVAR(getpeername_doc,
1914 "getpeername() -> address info\n\
1916 Return the address of the remote endpoint. For IP sockets, the address\n\
1917 info is a pair (hostaddr, port).");
1919 #endif /* HAVE_GETPEERNAME */
1922 /* s.listen(n) method */
1924 static PyObject *
1925 sock_listen(PySocketSockObject *s, PyObject *arg)
1927 int backlog;
1928 int res;
1930 backlog = PyInt_AsLong(arg);
1931 if (backlog == -1 && PyErr_Occurred())
1932 return NULL;
1933 Py_BEGIN_ALLOW_THREADS
1934 if (backlog < 1)
1935 backlog = 1;
1936 res = listen(s->sock_fd, backlog);
1937 Py_END_ALLOW_THREADS
1938 if (res < 0)
1939 return s->errorhandler();
1940 Py_INCREF(Py_None);
1941 return Py_None;
1944 PyDoc_STRVAR(listen_doc,
1945 "listen(backlog)\n\
1947 Enable a server to accept connections. The backlog argument must be at\n\
1948 least 1; it specifies the number of unaccepted connection that the system\n\
1949 will allow before refusing new connections.");
1952 #ifndef NO_DUP
1953 /* s.makefile(mode) method.
1954 Create a new open file object referring to a dupped version of
1955 the socket's file descriptor. (The dup() call is necessary so
1956 that the open file and socket objects may be closed independent
1957 of each other.)
1958 The mode argument specifies 'r' or 'w' passed to fdopen(). */
1960 static PyObject *
1961 sock_makefile(PySocketSockObject *s, PyObject *args)
1963 extern int fclose(FILE *);
1964 char *mode = "r";
1965 int bufsize = -1;
1966 #ifdef MS_WIN32
1967 Py_intptr_t fd;
1968 #else
1969 int fd;
1970 #endif
1971 FILE *fp;
1972 PyObject *f;
1973 #ifdef __VMS
1974 char *mode_r = "r";
1975 char *mode_w = "w";
1976 #endif
1978 if (!PyArg_ParseTuple(args, "|si:makefile", &mode, &bufsize))
1979 return NULL;
1980 #ifdef __VMS
1981 if (strcmp(mode,"rb") == 0) {
1982 mode = mode_r;
1984 else {
1985 if (strcmp(mode,"wb") == 0) {
1986 mode = mode_w;
1989 #endif
1990 #ifdef MS_WIN32
1991 if (((fd = _open_osfhandle(s->sock_fd, _O_BINARY)) < 0) ||
1992 ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL))
1993 #else
1994 if ((fd = dup(s->sock_fd)) < 0 || (fp = fdopen(fd, mode)) == NULL)
1995 #endif
1997 if (fd >= 0)
1998 SOCKETCLOSE(fd);
1999 return s->errorhandler();
2001 f = PyFile_FromFile(fp, "<socket>", mode, fclose);
2002 if (f != NULL)
2003 PyFile_SetBufSize(f, bufsize);
2004 return f;
2007 PyDoc_STRVAR(makefile_doc,
2008 "makefile([mode[, buffersize]]) -> file object\n\
2010 Return a regular file object corresponding to the socket.\n\
2011 The mode and buffersize arguments are as for the built-in open() function.");
2013 #endif /* NO_DUP */
2016 /* s.recv(nbytes [,flags]) method */
2018 static PyObject *
2019 sock_recv(PySocketSockObject *s, PyObject *args)
2021 int len, n = 0, flags = 0, timeout;
2022 PyObject *buf;
2023 #ifdef __VMS
2024 int read_length;
2025 char *read_buf;
2026 #endif
2028 if (!PyArg_ParseTuple(args, "i|i:recv", &len, &flags))
2029 return NULL;
2031 if (len < 0) {
2032 PyErr_SetString(PyExc_ValueError,
2033 "negative buffersize in recv");
2034 return NULL;
2037 buf = PyString_FromStringAndSize((char *) 0, len);
2038 if (buf == NULL)
2039 return NULL;
2041 #ifndef __VMS
2042 Py_BEGIN_ALLOW_THREADS
2043 timeout = internal_select(s, 0);
2044 if (!timeout)
2045 n = recv(s->sock_fd, PyString_AS_STRING(buf), len, flags);
2046 Py_END_ALLOW_THREADS
2048 if (timeout) {
2049 Py_DECREF(buf);
2050 PyErr_SetString(socket_timeout, "timed out");
2051 return NULL;
2053 if (n < 0) {
2054 Py_DECREF(buf);
2055 return s->errorhandler();
2057 if (n != len)
2058 _PyString_Resize(&buf, n);
2059 #else
2060 read_buf = PyString_AsString(buf);
2061 read_length = len;
2062 while (read_length != 0) {
2063 unsigned int segment;
2065 segment = read_length /SEGMENT_SIZE;
2066 if (segment != 0) {
2067 segment = SEGMENT_SIZE;
2069 else {
2070 segment = read_length;
2073 Py_BEGIN_ALLOW_THREADS
2074 timeout = internal_select(s, 0);
2075 if (!timeout)
2076 n = recv(s->sock_fd, read_buf, segment, flags);
2077 Py_END_ALLOW_THREADS
2079 if (timeout) {
2080 Py_DECREF(buf);
2081 PyErr_SetString(socket_timeout, "timed out");
2082 return NULL;
2084 if (n < 0) {
2085 Py_DECREF(buf);
2086 return s->errorhandler();
2088 if (n != read_length) {
2089 read_buf += n;
2090 break;
2093 read_length -= segment;
2094 read_buf += segment;
2096 if (_PyString_Resize(&buf, (read_buf - PyString_AsString(buf))) < 0)
2098 return NULL;
2100 #endif /* !__VMS */
2101 return buf;
2104 PyDoc_STRVAR(recv_doc,
2105 "recv(buffersize[, flags]) -> data\n\
2107 Receive up to buffersize bytes from the socket. For the optional flags\n\
2108 argument, see the Unix manual. When no data is available, block until\n\
2109 at least one byte is available or until the remote end is closed. When\n\
2110 the remote end is closed and all data is read, return the empty string.");
2113 /* s.recvfrom(nbytes [,flags]) method */
2115 static PyObject *
2116 sock_recvfrom(PySocketSockObject *s, PyObject *args)
2118 char addrbuf[256];
2119 PyObject *buf = NULL;
2120 PyObject *addr = NULL;
2121 PyObject *ret = NULL;
2122 int len, n = 0, flags = 0, timeout;
2123 socklen_t addrlen;
2125 if (!PyArg_ParseTuple(args, "i|i:recvfrom", &len, &flags))
2126 return NULL;
2128 if (!getsockaddrlen(s, &addrlen))
2129 return NULL;
2130 buf = PyString_FromStringAndSize((char *) 0, len);
2131 if (buf == NULL)
2132 return NULL;
2134 Py_BEGIN_ALLOW_THREADS
2135 memset(addrbuf, 0, addrlen);
2136 timeout = internal_select(s, 0);
2137 if (!timeout)
2138 n = recvfrom(s->sock_fd, PyString_AS_STRING(buf), len, flags,
2139 #ifndef MS_WINDOWS
2140 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
2141 (struct sockaddr *)addrbuf, &addrlen
2142 #else
2143 (void *)addrbuf, &addrlen
2144 #endif
2145 #else
2146 (struct sockaddr *)addrbuf, &addrlen
2147 #endif
2149 Py_END_ALLOW_THREADS
2151 if (timeout) {
2152 Py_DECREF(buf);
2153 PyErr_SetString(socket_timeout, "timed out");
2154 return NULL;
2156 if (n < 0) {
2157 Py_DECREF(buf);
2158 return s->errorhandler();
2161 if (n != len && _PyString_Resize(&buf, n) < 0)
2162 return NULL;
2164 if (!(addr = makesockaddr(s->sock_fd, (struct sockaddr *)addrbuf,
2165 addrlen, s->sock_proto)))
2166 goto finally;
2168 ret = PyTuple_Pack(2, buf, addr);
2170 finally:
2171 Py_XDECREF(addr);
2172 Py_XDECREF(buf);
2173 return ret;
2176 PyDoc_STRVAR(recvfrom_doc,
2177 "recvfrom(buffersize[, flags]) -> (data, address info)\n\
2179 Like recv(buffersize, flags) but also return the sender's address info.");
2181 /* s.send(data [,flags]) method */
2183 static PyObject *
2184 sock_send(PySocketSockObject *s, PyObject *args)
2186 char *buf;
2187 int len, n = 0, flags = 0, timeout;
2188 #ifdef __VMS
2189 int send_length;
2190 #endif
2192 if (!PyArg_ParseTuple(args, "s#|i:send", &buf, &len, &flags))
2193 return NULL;
2195 #ifndef __VMS
2196 Py_BEGIN_ALLOW_THREADS
2197 timeout = internal_select(s, 1);
2198 if (!timeout)
2199 n = send(s->sock_fd, buf, len, flags);
2200 Py_END_ALLOW_THREADS
2202 if (timeout) {
2203 PyErr_SetString(socket_timeout, "timed out");
2204 return NULL;
2206 if (n < 0)
2207 return s->errorhandler();
2208 #else
2209 /* Divide packet into smaller segments for */
2210 /* TCP/IP Services for OpenVMS */
2211 send_length = len;
2212 while (send_length != 0) {
2213 unsigned int segment;
2215 segment = send_length / SEGMENT_SIZE;
2216 if (segment != 0) {
2217 segment = SEGMENT_SIZE;
2219 else {
2220 segment = send_length;
2222 Py_BEGIN_ALLOW_THREADS
2223 timeout = internal_select(s, 1);
2224 if (!timeout)
2225 n = send(s->sock_fd, buf, segment, flags);
2226 Py_END_ALLOW_THREADS
2227 if (timeout) {
2228 PyErr_SetString(socket_timeout, "timed out");
2229 return NULL;
2231 if (n < 0) {
2232 return s->errorhandler();
2234 send_length -= segment;
2235 buf += segment;
2236 } /* end while */
2237 #endif /* !__VMS */
2238 return PyInt_FromLong((long)n);
2241 PyDoc_STRVAR(send_doc,
2242 "send(data[, flags]) -> count\n\
2244 Send a data string to the socket. For the optional flags\n\
2245 argument, see the Unix manual. Return the number of bytes\n\
2246 sent; this may be less than len(data) if the network is busy.");
2249 /* s.sendall(data [,flags]) method */
2251 static PyObject *
2252 sock_sendall(PySocketSockObject *s, PyObject *args)
2254 char *buf;
2255 int len, n = 0, flags = 0, timeout;
2257 if (!PyArg_ParseTuple(args, "s#|i:sendall", &buf, &len, &flags))
2258 return NULL;
2260 Py_BEGIN_ALLOW_THREADS
2261 do {
2262 timeout = internal_select(s, 1);
2263 if (timeout)
2264 break;
2265 n = send(s->sock_fd, buf, len, flags);
2266 if (n < 0)
2267 break;
2268 buf += n;
2269 len -= n;
2270 } while (len > 0);
2271 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 Py_INCREF(Py_None);
2281 return Py_None;
2284 PyDoc_STRVAR(sendall_doc,
2285 "sendall(data[, flags])\n\
2287 Send a data string to the socket. For the optional flags\n\
2288 argument, see the Unix manual. This calls send() repeatedly\n\
2289 until all data is sent. If an error occurs, it's impossible\n\
2290 to tell how much data has been sent.");
2293 /* s.sendto(data, [flags,] sockaddr) method */
2295 static PyObject *
2296 sock_sendto(PySocketSockObject *s, PyObject *args)
2298 PyObject *addro;
2299 char *buf;
2300 struct sockaddr *addr;
2301 int addrlen, len, n = 0, flags, timeout;
2303 flags = 0;
2304 if (!PyArg_ParseTuple(args, "s#O:sendto", &buf, &len, &addro)) {
2305 PyErr_Clear();
2306 if (!PyArg_ParseTuple(args, "s#iO:sendto",
2307 &buf, &len, &flags, &addro))
2308 return NULL;
2311 if (!getsockaddrarg(s, addro, &addr, &addrlen))
2312 return NULL;
2314 Py_BEGIN_ALLOW_THREADS
2315 timeout = internal_select(s, 1);
2316 if (!timeout)
2317 n = sendto(s->sock_fd, buf, len, flags, addr, addrlen);
2318 Py_END_ALLOW_THREADS
2320 if (timeout) {
2321 PyErr_SetString(socket_timeout, "timed out");
2322 return NULL;
2324 if (n < 0)
2325 return s->errorhandler();
2326 return PyInt_FromLong((long)n);
2329 PyDoc_STRVAR(sendto_doc,
2330 "sendto(data[, flags], address) -> count\n\
2332 Like send(data, flags) but allows specifying the destination address.\n\
2333 For IP sockets, the address is a pair (hostaddr, port).");
2336 /* s.shutdown(how) method */
2338 static PyObject *
2339 sock_shutdown(PySocketSockObject *s, PyObject *arg)
2341 int how;
2342 int res;
2344 how = PyInt_AsLong(arg);
2345 if (how == -1 && PyErr_Occurred())
2346 return NULL;
2347 Py_BEGIN_ALLOW_THREADS
2348 res = shutdown(s->sock_fd, how);
2349 Py_END_ALLOW_THREADS
2350 if (res < 0)
2351 return s->errorhandler();
2352 Py_INCREF(Py_None);
2353 return Py_None;
2356 PyDoc_STRVAR(shutdown_doc,
2357 "shutdown(flag)\n\
2359 Shut down the reading side of the socket (flag == SHUT_RD), the writing side\n\
2360 of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).");
2363 /* List of methods for socket objects */
2365 static PyMethodDef sock_methods[] = {
2366 {"accept", (PyCFunction)sock_accept, METH_NOARGS,
2367 accept_doc},
2368 {"bind", (PyCFunction)sock_bind, METH_O,
2369 bind_doc},
2370 {"close", (PyCFunction)sock_close, METH_NOARGS,
2371 close_doc},
2372 {"connect", (PyCFunction)sock_connect, METH_O,
2373 connect_doc},
2374 {"connect_ex", (PyCFunction)sock_connect_ex, METH_O,
2375 connect_ex_doc},
2376 #ifndef NO_DUP
2377 {"dup", (PyCFunction)sock_dup, METH_NOARGS,
2378 dup_doc},
2379 #endif
2380 {"fileno", (PyCFunction)sock_fileno, METH_NOARGS,
2381 fileno_doc},
2382 #ifdef HAVE_GETPEERNAME
2383 {"getpeername", (PyCFunction)sock_getpeername,
2384 METH_NOARGS, getpeername_doc},
2385 #endif
2386 {"getsockname", (PyCFunction)sock_getsockname,
2387 METH_NOARGS, getsockname_doc},
2388 {"getsockopt", (PyCFunction)sock_getsockopt, METH_VARARGS,
2389 getsockopt_doc},
2390 {"listen", (PyCFunction)sock_listen, METH_O,
2391 listen_doc},
2392 #ifndef NO_DUP
2393 {"makefile", (PyCFunction)sock_makefile, METH_VARARGS,
2394 makefile_doc},
2395 #endif
2396 {"recv", (PyCFunction)sock_recv, METH_VARARGS,
2397 recv_doc},
2398 {"recvfrom", (PyCFunction)sock_recvfrom, METH_VARARGS,
2399 recvfrom_doc},
2400 {"send", (PyCFunction)sock_send, METH_VARARGS,
2401 send_doc},
2402 {"sendall", (PyCFunction)sock_sendall, METH_VARARGS,
2403 sendall_doc},
2404 {"sendto", (PyCFunction)sock_sendto, METH_VARARGS,
2405 sendto_doc},
2406 {"setblocking", (PyCFunction)sock_setblocking, METH_O,
2407 setblocking_doc},
2408 {"settimeout", (PyCFunction)sock_settimeout, METH_O,
2409 settimeout_doc},
2410 {"gettimeout", (PyCFunction)sock_gettimeout, METH_NOARGS,
2411 gettimeout_doc},
2412 {"setsockopt", (PyCFunction)sock_setsockopt, METH_VARARGS,
2413 setsockopt_doc},
2414 {"shutdown", (PyCFunction)sock_shutdown, METH_O,
2415 shutdown_doc},
2416 #ifdef RISCOS
2417 {"sleeptaskw", (PyCFunction)sock_sleeptaskw, METH_O,
2418 sleeptaskw_doc},
2419 #endif
2420 {NULL, NULL} /* sentinel */
2424 /* Deallocate a socket object in response to the last Py_DECREF().
2425 First close the file description. */
2427 static void
2428 sock_dealloc(PySocketSockObject *s)
2430 if (s->sock_fd != -1)
2431 (void) SOCKETCLOSE(s->sock_fd);
2432 s->ob_type->tp_free((PyObject *)s);
2436 static PyObject *
2437 sock_repr(PySocketSockObject *s)
2439 char buf[512];
2440 #if SIZEOF_SOCKET_T > SIZEOF_LONG
2441 if (s->sock_fd > LONG_MAX) {
2442 /* this can occur on Win64, and actually there is a special
2443 ugly printf formatter for decimal pointer length integer
2444 printing, only bother if necessary*/
2445 PyErr_SetString(PyExc_OverflowError,
2446 "no printf formatter to display "
2447 "the socket descriptor in decimal");
2448 return NULL;
2450 #endif
2451 PyOS_snprintf(
2452 buf, sizeof(buf),
2453 "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
2454 (long)s->sock_fd, s->sock_family,
2455 s->sock_type,
2456 s->sock_proto);
2457 return PyString_FromString(buf);
2461 /* Create a new, uninitialized socket object. */
2463 static PyObject *
2464 sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2466 PyObject *new;
2468 new = type->tp_alloc(type, 0);
2469 if (new != NULL) {
2470 ((PySocketSockObject *)new)->sock_fd = -1;
2471 ((PySocketSockObject *)new)->sock_timeout = -1.0;
2472 ((PySocketSockObject *)new)->errorhandler = &set_error;
2474 return new;
2478 /* Initialize a new socket object. */
2480 /*ARGSUSED*/
2481 static int
2482 sock_initobj(PyObject *self, PyObject *args, PyObject *kwds)
2484 PySocketSockObject *s = (PySocketSockObject *)self;
2485 SOCKET_T fd;
2486 int family = AF_INET, type = SOCK_STREAM, proto = 0;
2487 static char *keywords[] = {"family", "type", "proto", 0};
2489 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2490 "|iii:socket", keywords,
2491 &family, &type, &proto))
2492 return -1;
2494 Py_BEGIN_ALLOW_THREADS
2495 fd = socket(family, type, proto);
2496 Py_END_ALLOW_THREADS
2498 #ifdef MS_WINDOWS
2499 if (fd == INVALID_SOCKET)
2500 #else
2501 if (fd < 0)
2502 #endif
2504 set_error();
2505 return -1;
2507 init_sockobject(s, fd, family, type, proto);
2509 return 0;
2514 /* Type object for socket objects. */
2516 static PyTypeObject sock_type = {
2517 PyObject_HEAD_INIT(0) /* Must fill in type value later */
2518 0, /* ob_size */
2519 "_socket.socket", /* tp_name */
2520 sizeof(PySocketSockObject), /* tp_basicsize */
2521 0, /* tp_itemsize */
2522 (destructor)sock_dealloc, /* tp_dealloc */
2523 0, /* tp_print */
2524 0, /* tp_getattr */
2525 0, /* tp_setattr */
2526 0, /* tp_compare */
2527 (reprfunc)sock_repr, /* tp_repr */
2528 0, /* tp_as_number */
2529 0, /* tp_as_sequence */
2530 0, /* tp_as_mapping */
2531 0, /* tp_hash */
2532 0, /* tp_call */
2533 0, /* tp_str */
2534 PyObject_GenericGetAttr, /* tp_getattro */
2535 0, /* tp_setattro */
2536 0, /* tp_as_buffer */
2537 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2538 sock_doc, /* tp_doc */
2539 0, /* tp_traverse */
2540 0, /* tp_clear */
2541 0, /* tp_richcompare */
2542 0, /* tp_weaklistoffset */
2543 0, /* tp_iter */
2544 0, /* tp_iternext */
2545 sock_methods, /* tp_methods */
2546 0, /* tp_members */
2547 0, /* tp_getset */
2548 0, /* tp_base */
2549 0, /* tp_dict */
2550 0, /* tp_descr_get */
2551 0, /* tp_descr_set */
2552 0, /* tp_dictoffset */
2553 sock_initobj, /* tp_init */
2554 PyType_GenericAlloc, /* tp_alloc */
2555 sock_new, /* tp_new */
2556 PyObject_Del, /* tp_free */
2560 /* Python interface to gethostname(). */
2562 /*ARGSUSED*/
2563 static PyObject *
2564 socket_gethostname(PyObject *self, PyObject *args)
2566 char buf[1024];
2567 int res;
2568 if (!PyArg_ParseTuple(args, ":gethostname"))
2569 return NULL;
2570 Py_BEGIN_ALLOW_THREADS
2571 res = gethostname(buf, (int) sizeof buf - 1);
2572 Py_END_ALLOW_THREADS
2573 if (res < 0)
2574 return set_error();
2575 buf[sizeof buf - 1] = '\0';
2576 return PyString_FromString(buf);
2579 PyDoc_STRVAR(gethostname_doc,
2580 "gethostname() -> string\n\
2582 Return the current host name.");
2585 /* Python interface to gethostbyname(name). */
2587 /*ARGSUSED*/
2588 static PyObject *
2589 socket_gethostbyname(PyObject *self, PyObject *args)
2591 char *name;
2592 #ifdef ENABLE_IPV6
2593 struct sockaddr_storage addrbuf;
2594 #else
2595 struct sockaddr_in addrbuf;
2596 #endif
2598 if (!PyArg_ParseTuple(args, "s:gethostbyname", &name))
2599 return NULL;
2600 if (setipaddr(name, (struct sockaddr *)&addrbuf, sizeof(addrbuf), AF_INET) < 0)
2601 return NULL;
2602 return makeipaddr((struct sockaddr *)&addrbuf,
2603 sizeof(struct sockaddr_in));
2606 PyDoc_STRVAR(gethostbyname_doc,
2607 "gethostbyname(host) -> address\n\
2609 Return the IP address (a string of the form '255.255.255.255') for a host.");
2612 /* Convenience function common to gethostbyname_ex and gethostbyaddr */
2614 static PyObject *
2615 gethost_common(struct hostent *h, struct sockaddr *addr, int alen, int af)
2617 char **pch;
2618 PyObject *rtn_tuple = (PyObject *)NULL;
2619 PyObject *name_list = (PyObject *)NULL;
2620 PyObject *addr_list = (PyObject *)NULL;
2621 PyObject *tmp;
2623 if (h == NULL) {
2624 /* Let's get real error message to return */
2625 #ifndef RISCOS
2626 set_herror(h_errno);
2627 #else
2628 PyErr_SetString(socket_error, "host not found");
2629 #endif
2630 return NULL;
2633 if (h->h_addrtype != af) {
2634 #ifdef HAVE_STRERROR
2635 /* Let's get real error message to return */
2636 PyErr_SetString(socket_error,
2637 (char *)strerror(EAFNOSUPPORT));
2638 #else
2639 PyErr_SetString(
2640 socket_error,
2641 "Address family not supported by protocol family");
2642 #endif
2643 return NULL;
2646 switch (af) {
2648 case AF_INET:
2649 if (alen < sizeof(struct sockaddr_in))
2650 return NULL;
2651 break;
2653 #ifdef ENABLE_IPV6
2654 case AF_INET6:
2655 if (alen < sizeof(struct sockaddr_in6))
2656 return NULL;
2657 break;
2658 #endif
2662 if ((name_list = PyList_New(0)) == NULL)
2663 goto err;
2665 if ((addr_list = PyList_New(0)) == NULL)
2666 goto err;
2668 for (pch = h->h_aliases; *pch != NULL; pch++) {
2669 int status;
2670 tmp = PyString_FromString(*pch);
2671 if (tmp == NULL)
2672 goto err;
2674 status = PyList_Append(name_list, tmp);
2675 Py_DECREF(tmp);
2677 if (status)
2678 goto err;
2681 for (pch = h->h_addr_list; *pch != NULL; pch++) {
2682 int status;
2684 switch (af) {
2686 case AF_INET:
2688 struct sockaddr_in sin;
2689 memset(&sin, 0, sizeof(sin));
2690 sin.sin_family = af;
2691 #ifdef HAVE_SOCKADDR_SA_LEN
2692 sin.sin_len = sizeof(sin);
2693 #endif
2694 memcpy(&sin.sin_addr, *pch, sizeof(sin.sin_addr));
2695 tmp = makeipaddr((struct sockaddr *)&sin, sizeof(sin));
2697 if (pch == h->h_addr_list && alen >= sizeof(sin))
2698 memcpy((char *) addr, &sin, sizeof(sin));
2699 break;
2702 #ifdef ENABLE_IPV6
2703 case AF_INET6:
2705 struct sockaddr_in6 sin6;
2706 memset(&sin6, 0, sizeof(sin6));
2707 sin6.sin6_family = af;
2708 #ifdef HAVE_SOCKADDR_SA_LEN
2709 sin6.sin6_len = sizeof(sin6);
2710 #endif
2711 memcpy(&sin6.sin6_addr, *pch, sizeof(sin6.sin6_addr));
2712 tmp = makeipaddr((struct sockaddr *)&sin6,
2713 sizeof(sin6));
2715 if (pch == h->h_addr_list && alen >= sizeof(sin6))
2716 memcpy((char *) addr, &sin6, sizeof(sin6));
2717 break;
2719 #endif
2721 default: /* can't happen */
2722 PyErr_SetString(socket_error,
2723 "unsupported address family");
2724 return NULL;
2727 if (tmp == NULL)
2728 goto err;
2730 status = PyList_Append(addr_list, tmp);
2731 Py_DECREF(tmp);
2733 if (status)
2734 goto err;
2737 rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list);
2739 err:
2740 Py_XDECREF(name_list);
2741 Py_XDECREF(addr_list);
2742 return rtn_tuple;
2746 /* Python interface to gethostbyname_ex(name). */
2748 /*ARGSUSED*/
2749 static PyObject *
2750 socket_gethostbyname_ex(PyObject *self, PyObject *args)
2752 char *name;
2753 struct hostent *h;
2754 #ifdef ENABLE_IPV6
2755 struct sockaddr_storage addr;
2756 #else
2757 struct sockaddr_in addr;
2758 #endif
2759 struct sockaddr *sa;
2760 PyObject *ret;
2761 #ifdef HAVE_GETHOSTBYNAME_R
2762 struct hostent hp_allocated;
2763 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
2764 struct hostent_data data;
2765 #else
2766 char buf[16384];
2767 int buf_len = (sizeof buf) - 1;
2768 int errnop;
2769 #endif
2770 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2771 int result;
2772 #endif
2773 #endif /* HAVE_GETHOSTBYNAME_R */
2775 if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name))
2776 return NULL;
2777 if (setipaddr(name, (struct sockaddr *)&addr, sizeof(addr), AF_INET) < 0)
2778 return NULL;
2779 Py_BEGIN_ALLOW_THREADS
2780 #ifdef HAVE_GETHOSTBYNAME_R
2781 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2782 result = gethostbyname_r(name, &hp_allocated, buf, buf_len,
2783 &h, &errnop);
2784 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
2785 h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
2786 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
2787 memset((void *) &data, '\0', sizeof(data));
2788 result = gethostbyname_r(name, &hp_allocated, &data);
2789 h = (result != 0) ? NULL : &hp_allocated;
2790 #endif
2791 #else /* not HAVE_GETHOSTBYNAME_R */
2792 #ifdef USE_GETHOSTBYNAME_LOCK
2793 PyThread_acquire_lock(netdb_lock, 1);
2794 #endif
2795 h = gethostbyname(name);
2796 #endif /* HAVE_GETHOSTBYNAME_R */
2797 Py_END_ALLOW_THREADS
2798 /* Some C libraries would require addr.__ss_family instead of
2799 addr.ss_family.
2800 Therefore, we cast the sockaddr_storage into sockaddr to
2801 access sa_family. */
2802 sa = (struct sockaddr*)&addr;
2803 ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr),
2804 sa->sa_family);
2805 #ifdef USE_GETHOSTBYNAME_LOCK
2806 PyThread_release_lock(netdb_lock);
2807 #endif
2808 return ret;
2811 PyDoc_STRVAR(ghbn_ex_doc,
2812 "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
2814 Return the true host name, a list of aliases, and a list of IP addresses,\n\
2815 for a host. The host argument is a string giving a host name or IP number.");
2818 /* Python interface to gethostbyaddr(IP). */
2820 /*ARGSUSED*/
2821 static PyObject *
2822 socket_gethostbyaddr(PyObject *self, PyObject *args)
2824 #ifdef ENABLE_IPV6
2825 struct sockaddr_storage addr;
2826 #else
2827 struct sockaddr_in addr;
2828 #endif
2829 struct sockaddr *sa = (struct sockaddr *)&addr;
2830 char *ip_num;
2831 struct hostent *h;
2832 PyObject *ret;
2833 #ifdef HAVE_GETHOSTBYNAME_R
2834 struct hostent hp_allocated;
2835 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
2836 struct hostent_data data;
2837 #else
2838 char buf[16384];
2839 int buf_len = (sizeof buf) - 1;
2840 int errnop;
2841 #endif
2842 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2843 int result;
2844 #endif
2845 #endif /* HAVE_GETHOSTBYNAME_R */
2846 char *ap;
2847 int al;
2848 int af;
2850 if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num))
2851 return NULL;
2852 af = AF_UNSPEC;
2853 if (setipaddr(ip_num, sa, sizeof(addr), af) < 0)
2854 return NULL;
2855 af = sa->sa_family;
2856 ap = NULL;
2857 al = 0;
2858 switch (af) {
2859 case AF_INET:
2860 ap = (char *)&((struct sockaddr_in *)sa)->sin_addr;
2861 al = sizeof(((struct sockaddr_in *)sa)->sin_addr);
2862 break;
2863 #ifdef ENABLE_IPV6
2864 case AF_INET6:
2865 ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr;
2866 al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr);
2867 break;
2868 #endif
2869 default:
2870 PyErr_SetString(socket_error, "unsupported address family");
2871 return NULL;
2873 Py_BEGIN_ALLOW_THREADS
2874 #ifdef HAVE_GETHOSTBYNAME_R
2875 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2876 result = gethostbyaddr_r(ap, al, af,
2877 &hp_allocated, buf, buf_len,
2878 &h, &errnop);
2879 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
2880 h = gethostbyaddr_r(ap, al, af,
2881 &hp_allocated, buf, buf_len, &errnop);
2882 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
2883 memset((void *) &data, '\0', sizeof(data));
2884 result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data);
2885 h = (result != 0) ? NULL : &hp_allocated;
2886 #endif
2887 #else /* not HAVE_GETHOSTBYNAME_R */
2888 #ifdef USE_GETHOSTBYNAME_LOCK
2889 PyThread_acquire_lock(netdb_lock, 1);
2890 #endif
2891 h = gethostbyaddr(ap, al, af);
2892 #endif /* HAVE_GETHOSTBYNAME_R */
2893 Py_END_ALLOW_THREADS
2894 ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), af);
2895 #ifdef USE_GETHOSTBYNAME_LOCK
2896 PyThread_release_lock(netdb_lock);
2897 #endif
2898 return ret;
2901 PyDoc_STRVAR(gethostbyaddr_doc,
2902 "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
2904 Return the true host name, a list of aliases, and a list of IP addresses,\n\
2905 for a host. The host argument is a string giving a host name or IP number.");
2908 /* Python interface to getservbyname(name).
2909 This only returns the port number, since the other info is already
2910 known or not useful (like the list of aliases). */
2912 /*ARGSUSED*/
2913 static PyObject *
2914 socket_getservbyname(PyObject *self, PyObject *args)
2916 char *name, *proto=NULL;
2917 struct servent *sp;
2918 if (!PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto))
2919 return NULL;
2920 Py_BEGIN_ALLOW_THREADS
2921 sp = getservbyname(name, proto);
2922 Py_END_ALLOW_THREADS
2923 if (sp == NULL) {
2924 PyErr_SetString(socket_error, "service/proto not found");
2925 return NULL;
2927 return PyInt_FromLong((long) ntohs(sp->s_port));
2930 PyDoc_STRVAR(getservbyname_doc,
2931 "getservbyname(servicename[, protocolname]) -> integer\n\
2933 Return a port number from a service name and protocol name.\n\
2934 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
2935 otherwise any protocol will match.");
2938 /* Python interface to getservbyport(port).
2939 This only returns the service name, since the other info is already
2940 known or not useful (like the list of aliases). */
2942 /*ARGSUSED*/
2943 static PyObject *
2944 socket_getservbyport(PyObject *self, PyObject *args)
2946 unsigned short port;
2947 char *proto=NULL;
2948 struct servent *sp;
2949 if (!PyArg_ParseTuple(args, "H|s:getservbyport", &port, &proto))
2950 return NULL;
2951 Py_BEGIN_ALLOW_THREADS
2952 sp = getservbyport(htons(port), proto);
2953 Py_END_ALLOW_THREADS
2954 if (sp == NULL) {
2955 PyErr_SetString(socket_error, "port/proto not found");
2956 return NULL;
2958 return PyString_FromString(sp->s_name);
2961 PyDoc_STRVAR(getservbyport_doc,
2962 "getservbyport(port[, protocolname]) -> string\n\
2964 Return the service name from a port number and protocol name.\n\
2965 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
2966 otherwise any protocol will match.");
2968 /* Python interface to getprotobyname(name).
2969 This only returns the protocol number, since the other info is
2970 already known or not useful (like the list of aliases). */
2972 /*ARGSUSED*/
2973 static PyObject *
2974 socket_getprotobyname(PyObject *self, PyObject *args)
2976 char *name;
2977 struct protoent *sp;
2978 #ifdef __BEOS__
2979 /* Not available in BeOS yet. - [cjh] */
2980 PyErr_SetString(socket_error, "getprotobyname not supported");
2981 return NULL;
2982 #else
2983 if (!PyArg_ParseTuple(args, "s:getprotobyname", &name))
2984 return NULL;
2985 Py_BEGIN_ALLOW_THREADS
2986 sp = getprotobyname(name);
2987 Py_END_ALLOW_THREADS
2988 if (sp == NULL) {
2989 PyErr_SetString(socket_error, "protocol not found");
2990 return NULL;
2992 return PyInt_FromLong((long) sp->p_proto);
2993 #endif
2996 PyDoc_STRVAR(getprotobyname_doc,
2997 "getprotobyname(name) -> integer\n\
2999 Return the protocol number for the named protocol. (Rarely used.)");
3002 #ifdef HAVE_SOCKETPAIR
3003 /* Create a pair of sockets using the socketpair() function.
3004 Arguments as for socket() except the default family is AF_UNIX if
3005 defined on the platform; otherwise, the default is AF_INET. */
3007 /*ARGSUSED*/
3008 static PyObject *
3009 socket_socketpair(PyObject *self, PyObject *args)
3011 PySocketSockObject *s0 = NULL, *s1 = NULL;
3012 SOCKET_T sv[2];
3013 int family, type = SOCK_STREAM, proto = 0;
3014 PyObject *res = NULL;
3016 #if defined(AF_UNIX)
3017 family = AF_UNIX;
3018 #else
3019 family = AF_INET;
3020 #endif
3021 if (!PyArg_ParseTuple(args, "|iii:socketpair",
3022 &family, &type, &proto))
3023 return NULL;
3024 /* Create a pair of socket fds */
3025 if (socketpair(family, type, proto, sv) < 0)
3026 return set_error();
3027 s0 = new_sockobject(sv[0], family, type, proto);
3028 if (s0 == NULL)
3029 goto finally;
3030 s1 = new_sockobject(sv[1], family, type, proto);
3031 if (s1 == NULL)
3032 goto finally;
3033 res = PyTuple_Pack(2, s0, s1);
3035 finally:
3036 if (res == NULL) {
3037 if (s0 == NULL)
3038 SOCKETCLOSE(sv[0]);
3039 if (s1 == NULL)
3040 SOCKETCLOSE(sv[1]);
3042 Py_XDECREF(s0);
3043 Py_XDECREF(s1);
3044 return res;
3047 PyDoc_STRVAR(socketpair_doc,
3048 "socketpair([family[, type[, proto]]]) -> (socket object, socket object)\n\
3050 Create a pair of socket objects from the sockets returned by the platform\n\
3051 socketpair() function.\n\
3052 The arguments are the same as for socket() except the default family is\n\
3053 AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");
3055 #endif /* HAVE_SOCKETPAIR */
3058 #ifndef NO_DUP
3059 /* Create a socket object from a numeric file description.
3060 Useful e.g. if stdin is a socket.
3061 Additional arguments as for socket(). */
3063 /*ARGSUSED*/
3064 static PyObject *
3065 socket_fromfd(PyObject *self, PyObject *args)
3067 PySocketSockObject *s;
3068 SOCKET_T fd;
3069 int family, type, proto = 0;
3070 if (!PyArg_ParseTuple(args, "iii|i:fromfd",
3071 &fd, &family, &type, &proto))
3072 return NULL;
3073 /* Dup the fd so it and the socket can be closed independently */
3074 fd = dup(fd);
3075 if (fd < 0)
3076 return set_error();
3077 s = new_sockobject(fd, family, type, proto);
3078 return (PyObject *) s;
3081 PyDoc_STRVAR(fromfd_doc,
3082 "fromfd(fd, family, type[, proto]) -> socket object\n\
3084 Create a socket object from the given file descriptor.\n\
3085 The remaining arguments are the same as for socket().");
3087 #endif /* NO_DUP */
3090 static PyObject *
3091 socket_ntohs(PyObject *self, PyObject *args)
3093 int x1, x2;
3095 if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) {
3096 return NULL;
3098 x2 = (int)ntohs((short)x1);
3099 return PyInt_FromLong(x2);
3102 PyDoc_STRVAR(ntohs_doc,
3103 "ntohs(integer) -> integer\n\
3105 Convert a 16-bit integer from network to host byte order.");
3108 static PyObject *
3109 socket_ntohl(PyObject *self, PyObject *arg)
3111 unsigned long x;
3113 if (PyInt_Check(arg)) {
3114 x = PyInt_AS_LONG(arg);
3115 if (x == (unsigned long) -1 && PyErr_Occurred())
3116 return NULL;
3118 else if (PyLong_Check(arg)) {
3119 x = PyLong_AsUnsignedLong(arg);
3120 if (x == (unsigned long) -1 && PyErr_Occurred())
3121 return NULL;
3122 #if SIZEOF_LONG > 4
3124 unsigned long y;
3125 /* only want the trailing 32 bits */
3126 y = x & 0xFFFFFFFFUL;
3127 if (y ^ x)
3128 return PyErr_Format(PyExc_OverflowError,
3129 "long int larger than 32 bits");
3130 x = y;
3132 #endif
3134 else
3135 return PyErr_Format(PyExc_TypeError,
3136 "expected int/long, %s found",
3137 arg->ob_type->tp_name);
3138 if (x == (unsigned long) -1 && PyErr_Occurred())
3139 return NULL;
3140 return PyInt_FromLong(ntohl(x));
3143 PyDoc_STRVAR(ntohl_doc,
3144 "ntohl(integer) -> integer\n\
3146 Convert a 32-bit integer from network to host byte order.");
3149 static PyObject *
3150 socket_htons(PyObject *self, PyObject *args)
3152 int x1, x2;
3154 if (!PyArg_ParseTuple(args, "i:htons", &x1)) {
3155 return NULL;
3157 x2 = (int)htons((short)x1);
3158 return PyInt_FromLong(x2);
3161 PyDoc_STRVAR(htons_doc,
3162 "htons(integer) -> integer\n\
3164 Convert a 16-bit integer from host to network byte order.");
3167 static PyObject *
3168 socket_htonl(PyObject *self, PyObject *arg)
3170 unsigned long x;
3172 if (PyInt_Check(arg)) {
3173 x = PyInt_AS_LONG(arg);
3174 if (x == (unsigned long) -1 && PyErr_Occurred())
3175 return NULL;
3177 else if (PyLong_Check(arg)) {
3178 x = PyLong_AsUnsignedLong(arg);
3179 if (x == (unsigned long) -1 && PyErr_Occurred())
3180 return NULL;
3181 #if SIZEOF_LONG > 4
3183 unsigned long y;
3184 /* only want the trailing 32 bits */
3185 y = x & 0xFFFFFFFFUL;
3186 if (y ^ x)
3187 return PyErr_Format(PyExc_OverflowError,
3188 "long int larger than 32 bits");
3189 x = y;
3191 #endif
3193 else
3194 return PyErr_Format(PyExc_TypeError,
3195 "expected int/long, %s found",
3196 arg->ob_type->tp_name);
3197 return PyInt_FromLong(htonl(x));
3200 PyDoc_STRVAR(htonl_doc,
3201 "htonl(integer) -> integer\n\
3203 Convert a 32-bit integer from host to network byte order.");
3205 /* socket.inet_aton() and socket.inet_ntoa() functions. */
3207 PyDoc_STRVAR(inet_aton_doc,
3208 "inet_aton(string) -> packed 32-bit IP representation\n\
3210 Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
3211 binary format used in low-level network functions.");
3213 static PyObject*
3214 socket_inet_aton(PyObject *self, PyObject *args)
3216 #ifndef INADDR_NONE
3217 #define INADDR_NONE (-1)
3218 #endif
3219 #ifdef HAVE_INET_ATON
3220 struct in_addr buf;
3221 #else
3222 /* Have to use inet_addr() instead */
3223 unsigned long packed_addr;
3224 #endif
3225 char *ip_addr;
3227 if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr))
3228 return NULL;
3231 #ifdef HAVE_INET_ATON
3232 if (inet_aton(ip_addr, &buf))
3233 return PyString_FromStringAndSize((char *)(&buf),
3234 sizeof(buf));
3236 PyErr_SetString(socket_error,
3237 "illegal IP address string passed to inet_aton");
3238 return NULL;
3240 #else /* ! HAVE_INET_ATON */
3241 /* XXX Problem here: inet_aton('255.255.255.255') raises
3242 an exception while it should be a valid address. */
3243 packed_addr = inet_addr(ip_addr);
3245 if (packed_addr == INADDR_NONE) { /* invalid address */
3246 PyErr_SetString(socket_error,
3247 "illegal IP address string passed to inet_aton");
3248 return NULL;
3250 return PyString_FromStringAndSize((char *) &packed_addr,
3251 sizeof(packed_addr));
3252 #endif
3255 PyDoc_STRVAR(inet_ntoa_doc,
3256 "inet_ntoa(packed_ip) -> ip_address_string\n\
3258 Convert an IP address from 32-bit packed binary format to string format");
3260 static PyObject*
3261 socket_inet_ntoa(PyObject *self, PyObject *args)
3263 char *packed_str;
3264 int addr_len;
3265 struct in_addr packed_addr;
3267 if (!PyArg_ParseTuple(args, "s#:inet_ntoa", &packed_str, &addr_len)) {
3268 return NULL;
3271 if (addr_len != sizeof(packed_addr)) {
3272 PyErr_SetString(socket_error,
3273 "packed IP wrong length for inet_ntoa");
3274 return NULL;
3277 memcpy(&packed_addr, packed_str, addr_len);
3279 return PyString_FromString(inet_ntoa(packed_addr));
3282 #ifdef HAVE_INET_PTON
3284 PyDoc_STRVAR(inet_pton_doc,
3285 "inet_pton(af, ip) -> packed IP address string\n\
3287 Convert an IP address from string format to a packed string suitable\n\
3288 for use with low-level network functions.");
3290 static PyObject *
3291 socket_inet_pton(PyObject *self, PyObject *args)
3293 int af;
3294 char* ip;
3295 int retval;
3296 #ifdef ENABLE_IPV6
3297 char packed[MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
3298 #else
3299 char packed[sizeof(struct in_addr)];
3300 #endif
3301 if (!PyArg_ParseTuple(args, "is:inet_pton", &af, &ip)) {
3302 return NULL;
3305 #if !defined(ENABLE_IPV6) && defined(AF_INET6)
3306 if(af == AF_INET6) {
3307 PyErr_SetString(socket_error,
3308 "can't use AF_INET6, IPv6 is disabled");
3309 return NULL;
3311 #endif
3313 retval = inet_pton(af, ip, packed);
3314 if (retval < 0) {
3315 PyErr_SetFromErrno(socket_error);
3316 return NULL;
3317 } else if (retval == 0) {
3318 PyErr_SetString(socket_error,
3319 "illegal IP address string passed to inet_pton");
3320 return NULL;
3321 } else if (af == AF_INET) {
3322 return PyString_FromStringAndSize(packed,
3323 sizeof(struct in_addr));
3324 #ifdef ENABLE_IPV6
3325 } else if (af == AF_INET6) {
3326 return PyString_FromStringAndSize(packed,
3327 sizeof(struct in6_addr));
3328 #endif
3329 } else {
3330 PyErr_SetString(socket_error, "unknown address family");
3331 return NULL;
3335 PyDoc_STRVAR(inet_ntop_doc,
3336 "inet_ntop(af, packed_ip) -> string formatted IP address\n\
3338 Convert a packed IP address of the given family to string format.");
3340 static PyObject *
3341 socket_inet_ntop(PyObject *self, PyObject *args)
3343 int af;
3344 char* packed;
3345 int len;
3346 const char* retval;
3347 #ifdef ENABLE_IPV6
3348 char ip[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) + 1];
3349 #else
3350 char ip[INET_ADDRSTRLEN + 1];
3351 #endif
3353 /* Guarantee NUL-termination for PyString_FromString() below */
3354 memset((void *) &ip[0], '\0', sizeof(ip));
3356 if (!PyArg_ParseTuple(args, "is#:inet_ntop", &af, &packed, &len)) {
3357 return NULL;
3360 if (af == AF_INET) {
3361 if (len != sizeof(struct in_addr)) {
3362 PyErr_SetString(PyExc_ValueError,
3363 "invalid length of packed IP address string");
3364 return NULL;
3366 #ifdef ENABLE_IPV6
3367 } else if (af == AF_INET6) {
3368 if (len != sizeof(struct in6_addr)) {
3369 PyErr_SetString(PyExc_ValueError,
3370 "invalid length of packed IP address string");
3371 return NULL;
3373 #endif
3374 } else {
3375 PyErr_Format(PyExc_ValueError,
3376 "unknown address family %d", af);
3377 return NULL;
3380 retval = inet_ntop(af, packed, ip, sizeof(ip));
3381 if (!retval) {
3382 PyErr_SetFromErrno(socket_error);
3383 return NULL;
3384 } else {
3385 return PyString_FromString(retval);
3388 /* NOTREACHED */
3389 PyErr_SetString(PyExc_RuntimeError, "invalid handling of inet_ntop");
3390 return NULL;
3393 #endif /* HAVE_INET_PTON */
3395 /* Python interface to getaddrinfo(host, port). */
3397 /*ARGSUSED*/
3398 static PyObject *
3399 socket_getaddrinfo(PyObject *self, PyObject *args)
3401 struct addrinfo hints, *res;
3402 struct addrinfo *res0 = NULL;
3403 PyObject *hobj = NULL;
3404 PyObject *pobj = (PyObject *)NULL;
3405 char pbuf[30];
3406 char *hptr, *pptr;
3407 int family, socktype, protocol, flags;
3408 int error;
3409 PyObject *all = (PyObject *)NULL;
3410 PyObject *single = (PyObject *)NULL;
3411 PyObject *idna = NULL;
3413 family = socktype = protocol = flags = 0;
3414 family = AF_UNSPEC;
3415 if (!PyArg_ParseTuple(args, "OO|iiii:getaddrinfo",
3416 &hobj, &pobj, &family, &socktype,
3417 &protocol, &flags)) {
3418 return NULL;
3420 if (hobj == Py_None) {
3421 hptr = NULL;
3422 } else if (PyUnicode_Check(hobj)) {
3423 idna = PyObject_CallMethod(hobj, "encode", "s", "idna");
3424 if (!idna)
3425 return NULL;
3426 hptr = PyString_AsString(idna);
3427 } else if (PyString_Check(hobj)) {
3428 hptr = PyString_AsString(hobj);
3429 } else {
3430 PyErr_SetString(PyExc_TypeError,
3431 "getaddrinfo() argument 1 must be string or None");
3432 return NULL;
3434 if (PyInt_Check(pobj)) {
3435 PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", PyInt_AsLong(pobj));
3436 pptr = pbuf;
3437 } else if (PyString_Check(pobj)) {
3438 pptr = PyString_AsString(pobj);
3439 } else if (pobj == Py_None) {
3440 pptr = (char *)NULL;
3441 } else {
3442 PyErr_SetString(socket_error, "Int or String expected");
3443 goto err;
3445 memset(&hints, 0, sizeof(hints));
3446 hints.ai_family = family;
3447 hints.ai_socktype = socktype;
3448 hints.ai_protocol = protocol;
3449 hints.ai_flags = flags;
3450 Py_BEGIN_ALLOW_THREADS
3451 ACQUIRE_GETADDRINFO_LOCK
3452 error = getaddrinfo(hptr, pptr, &hints, &res0);
3453 Py_END_ALLOW_THREADS
3454 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
3455 if (error) {
3456 set_gaierror(error);
3457 goto err;
3460 if ((all = PyList_New(0)) == NULL)
3461 goto err;
3462 for (res = res0; res; res = res->ai_next) {
3463 PyObject *addr =
3464 makesockaddr(-1, res->ai_addr, res->ai_addrlen, protocol);
3465 if (addr == NULL)
3466 goto err;
3467 single = Py_BuildValue("iiisO", res->ai_family,
3468 res->ai_socktype, res->ai_protocol,
3469 res->ai_canonname ? res->ai_canonname : "",
3470 addr);
3471 Py_DECREF(addr);
3472 if (single == NULL)
3473 goto err;
3475 if (PyList_Append(all, single))
3476 goto err;
3477 Py_XDECREF(single);
3479 Py_XDECREF(idna);
3480 if (res0)
3481 freeaddrinfo(res0);
3482 return all;
3483 err:
3484 Py_XDECREF(single);
3485 Py_XDECREF(all);
3486 Py_XDECREF(idna);
3487 if (res0)
3488 freeaddrinfo(res0);
3489 return (PyObject *)NULL;
3492 PyDoc_STRVAR(getaddrinfo_doc,
3493 "getaddrinfo(host, port [, family, socktype, proto, flags])\n\
3494 -> list of (family, socktype, proto, canonname, sockaddr)\n\
3496 Resolve host and port into addrinfo struct.");
3498 /* Python interface to getnameinfo(sa, flags). */
3500 /*ARGSUSED*/
3501 static PyObject *
3502 socket_getnameinfo(PyObject *self, PyObject *args)
3504 PyObject *sa = (PyObject *)NULL;
3505 int flags;
3506 char *hostp;
3507 int port, flowinfo, scope_id;
3508 char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
3509 struct addrinfo hints, *res = NULL;
3510 int error;
3511 PyObject *ret = (PyObject *)NULL;
3513 flags = flowinfo = scope_id = 0;
3514 if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags))
3515 return NULL;
3516 if (!PyArg_ParseTuple(sa, "si|ii",
3517 &hostp, &port, &flowinfo, &scope_id))
3518 return NULL;
3519 PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port);
3520 memset(&hints, 0, sizeof(hints));
3521 hints.ai_family = AF_UNSPEC;
3522 hints.ai_socktype = SOCK_DGRAM; /* make numeric port happy */
3523 Py_BEGIN_ALLOW_THREADS
3524 ACQUIRE_GETADDRINFO_LOCK
3525 error = getaddrinfo(hostp, pbuf, &hints, &res);
3526 Py_END_ALLOW_THREADS
3527 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
3528 if (error) {
3529 set_gaierror(error);
3530 goto fail;
3532 if (res->ai_next) {
3533 PyErr_SetString(socket_error,
3534 "sockaddr resolved to multiple addresses");
3535 goto fail;
3537 switch (res->ai_family) {
3538 case AF_INET:
3540 char *t1;
3541 int t2;
3542 if (PyArg_ParseTuple(sa, "si", &t1, &t2) == 0) {
3543 PyErr_SetString(socket_error,
3544 "IPv4 sockaddr must be 2 tuple");
3545 goto fail;
3547 break;
3549 #ifdef ENABLE_IPV6
3550 case AF_INET6:
3552 struct sockaddr_in6 *sin6;
3553 sin6 = (struct sockaddr_in6 *)res->ai_addr;
3554 sin6->sin6_flowinfo = flowinfo;
3555 sin6->sin6_scope_id = scope_id;
3556 break;
3558 #endif
3560 error = getnameinfo(res->ai_addr, res->ai_addrlen,
3561 hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags);
3562 if (error) {
3563 set_gaierror(error);
3564 goto fail;
3566 ret = Py_BuildValue("ss", hbuf, pbuf);
3568 fail:
3569 if (res)
3570 freeaddrinfo(res);
3571 return ret;
3574 PyDoc_STRVAR(getnameinfo_doc,
3575 "getnameinfo(sockaddr, flags) --> (host, port)\n\
3577 Get host and port for a sockaddr.");
3580 /* Python API to getting and setting the default timeout value. */
3582 static PyObject *
3583 socket_getdefaulttimeout(PyObject *self)
3585 if (defaulttimeout < 0.0) {
3586 Py_INCREF(Py_None);
3587 return Py_None;
3589 else
3590 return PyFloat_FromDouble(defaulttimeout);
3593 PyDoc_STRVAR(getdefaulttimeout_doc,
3594 "getdefaulttimeout() -> timeout\n\
3596 Returns the default timeout in floating seconds for new socket objects.\n\
3597 A value of None indicates that new socket objects have no timeout.\n\
3598 When the socket module is first imported, the default is None.");
3600 static PyObject *
3601 socket_setdefaulttimeout(PyObject *self, PyObject *arg)
3603 double timeout;
3605 if (arg == Py_None)
3606 timeout = -1.0;
3607 else {
3608 timeout = PyFloat_AsDouble(arg);
3609 if (timeout < 0.0) {
3610 if (!PyErr_Occurred())
3611 PyErr_SetString(PyExc_ValueError,
3612 "Timeout value out of range");
3613 return NULL;
3617 defaulttimeout = timeout;
3619 Py_INCREF(Py_None);
3620 return Py_None;
3623 PyDoc_STRVAR(setdefaulttimeout_doc,
3624 "setdefaulttimeout(timeout)\n\
3626 Set the default timeout in floating seconds for new socket objects.\n\
3627 A value of None indicates that new socket objects have no timeout.\n\
3628 When the socket module is first imported, the default is None.");
3631 /* List of functions exported by this module. */
3633 static PyMethodDef socket_methods[] = {
3634 {"gethostbyname", socket_gethostbyname,
3635 METH_VARARGS, gethostbyname_doc},
3636 {"gethostbyname_ex", socket_gethostbyname_ex,
3637 METH_VARARGS, ghbn_ex_doc},
3638 {"gethostbyaddr", socket_gethostbyaddr,
3639 METH_VARARGS, gethostbyaddr_doc},
3640 {"gethostname", socket_gethostname,
3641 METH_VARARGS, gethostname_doc},
3642 {"getservbyname", socket_getservbyname,
3643 METH_VARARGS, getservbyname_doc},
3644 {"getservbyport", socket_getservbyport,
3645 METH_VARARGS, getservbyport_doc},
3646 {"getprotobyname", socket_getprotobyname,
3647 METH_VARARGS,getprotobyname_doc},
3648 #ifndef NO_DUP
3649 {"fromfd", socket_fromfd,
3650 METH_VARARGS, fromfd_doc},
3651 #endif
3652 #ifdef HAVE_SOCKETPAIR
3653 {"socketpair", socket_socketpair,
3654 METH_VARARGS, socketpair_doc},
3655 #endif
3656 {"ntohs", socket_ntohs,
3657 METH_VARARGS, ntohs_doc},
3658 {"ntohl", socket_ntohl,
3659 METH_O, ntohl_doc},
3660 {"htons", socket_htons,
3661 METH_VARARGS, htons_doc},
3662 {"htonl", socket_htonl,
3663 METH_O, htonl_doc},
3664 {"inet_aton", socket_inet_aton,
3665 METH_VARARGS, inet_aton_doc},
3666 {"inet_ntoa", socket_inet_ntoa,
3667 METH_VARARGS, inet_ntoa_doc},
3668 #ifdef HAVE_INET_PTON
3669 {"inet_pton", socket_inet_pton,
3670 METH_VARARGS, inet_pton_doc},
3671 {"inet_ntop", socket_inet_ntop,
3672 METH_VARARGS, inet_ntop_doc},
3673 #endif
3674 {"getaddrinfo", socket_getaddrinfo,
3675 METH_VARARGS, getaddrinfo_doc},
3676 {"getnameinfo", socket_getnameinfo,
3677 METH_VARARGS, getnameinfo_doc},
3678 {"getdefaulttimeout", (PyCFunction)socket_getdefaulttimeout,
3679 METH_NOARGS, getdefaulttimeout_doc},
3680 {"setdefaulttimeout", socket_setdefaulttimeout,
3681 METH_O, setdefaulttimeout_doc},
3682 {NULL, NULL} /* Sentinel */
3686 #ifdef RISCOS
3687 #define OS_INIT_DEFINED
3689 static int
3690 os_init(void)
3692 _kernel_swi_regs r;
3694 r.r[0] = 0;
3695 _kernel_swi(0x43380, &r, &r);
3696 taskwindow = r.r[0];
3698 return 1;
3701 #endif /* RISCOS */
3704 #ifdef MS_WINDOWS
3705 #define OS_INIT_DEFINED
3707 /* Additional initialization and cleanup for Windows */
3709 static void
3710 os_cleanup(void)
3712 WSACleanup();
3715 static int
3716 os_init(void)
3718 WSADATA WSAData;
3719 int ret;
3720 char buf[100];
3721 ret = WSAStartup(0x0101, &WSAData);
3722 switch (ret) {
3723 case 0: /* No error */
3724 Py_AtExit(os_cleanup);
3725 return 1; /* Success */
3726 case WSASYSNOTREADY:
3727 PyErr_SetString(PyExc_ImportError,
3728 "WSAStartup failed: network not ready");
3729 break;
3730 case WSAVERNOTSUPPORTED:
3731 case WSAEINVAL:
3732 PyErr_SetString(
3733 PyExc_ImportError,
3734 "WSAStartup failed: requested version not supported");
3735 break;
3736 default:
3737 PyOS_snprintf(buf, sizeof(buf),
3738 "WSAStartup failed: error code %d", ret);
3739 PyErr_SetString(PyExc_ImportError, buf);
3740 break;
3742 return 0; /* Failure */
3745 #endif /* MS_WINDOWS */
3748 #ifdef PYOS_OS2
3749 #define OS_INIT_DEFINED
3751 /* Additional initialization for OS/2 */
3753 static int
3754 os_init(void)
3756 #ifndef PYCC_GCC
3757 char reason[64];
3758 int rc = sock_init();
3760 if (rc == 0) {
3761 return 1; /* Success */
3764 PyOS_snprintf(reason, sizeof(reason),
3765 "OS/2 TCP/IP Error# %d", sock_errno());
3766 PyErr_SetString(PyExc_ImportError, reason);
3768 return 0; /* Failure */
3769 #else
3770 /* No need to initialise sockets with GCC/EMX */
3771 return 1; /* Success */
3772 #endif
3775 #endif /* PYOS_OS2 */
3778 #ifndef OS_INIT_DEFINED
3779 static int
3780 os_init(void)
3782 return 1; /* Success */
3784 #endif
3787 /* C API table - always add new things to the end for binary
3788 compatibility. */
3789 static
3790 PySocketModule_APIObject PySocketModuleAPI =
3792 &sock_type,
3793 NULL
3797 /* Initialize the _socket module.
3799 This module is actually called "_socket", and there's a wrapper
3800 "socket.py" which implements some additional functionality. On some
3801 platforms (e.g. Windows and OS/2), socket.py also implements a
3802 wrapper for the socket type that provides missing functionality such
3803 as makefile(), dup() and fromfd(). The import of "_socket" may fail
3804 with an ImportError exception if os-specific initialization fails.
3805 On Windows, this does WINSOCK initialization. When WINSOCK is
3806 initialized succesfully, a call to WSACleanup() is scheduled to be
3807 made at exit time.
3810 PyDoc_STRVAR(socket_doc,
3811 "Implementation module for socket operations.\n\
3813 See the socket module for documentation.");
3815 PyMODINIT_FUNC
3816 init_socket(void)
3818 PyObject *m, *has_ipv6;
3820 if (!os_init())
3821 return;
3823 sock_type.ob_type = &PyType_Type;
3824 m = Py_InitModule3(PySocket_MODULE_NAME,
3825 socket_methods,
3826 socket_doc);
3828 socket_error = PyErr_NewException("socket.error", NULL, NULL);
3829 if (socket_error == NULL)
3830 return;
3831 PySocketModuleAPI.error = socket_error;
3832 Py_INCREF(socket_error);
3833 PyModule_AddObject(m, "error", socket_error);
3834 socket_herror = PyErr_NewException("socket.herror",
3835 socket_error, NULL);
3836 if (socket_herror == NULL)
3837 return;
3838 Py_INCREF(socket_herror);
3839 PyModule_AddObject(m, "herror", socket_herror);
3840 socket_gaierror = PyErr_NewException("socket.gaierror", socket_error,
3841 NULL);
3842 if (socket_gaierror == NULL)
3843 return;
3844 Py_INCREF(socket_gaierror);
3845 PyModule_AddObject(m, "gaierror", socket_gaierror);
3846 socket_timeout = PyErr_NewException("socket.timeout",
3847 socket_error, NULL);
3848 if (socket_timeout == NULL)
3849 return;
3850 Py_INCREF(socket_timeout);
3851 PyModule_AddObject(m, "timeout", socket_timeout);
3852 Py_INCREF((PyObject *)&sock_type);
3853 if (PyModule_AddObject(m, "SocketType",
3854 (PyObject *)&sock_type) != 0)
3855 return;
3856 Py_INCREF((PyObject *)&sock_type);
3857 if (PyModule_AddObject(m, "socket",
3858 (PyObject *)&sock_type) != 0)
3859 return;
3861 #ifdef ENABLE_IPV6
3862 has_ipv6 = Py_True;
3863 #else
3864 has_ipv6 = Py_False;
3865 #endif
3866 Py_INCREF(has_ipv6);
3867 PyModule_AddObject(m, "has_ipv6", has_ipv6);
3869 /* Export C API */
3870 if (PyModule_AddObject(m, PySocket_CAPI_NAME,
3871 PyCObject_FromVoidPtr((void *)&PySocketModuleAPI, NULL)
3872 ) != 0)
3873 return;
3875 /* Address families (we only support AF_INET and AF_UNIX) */
3876 #ifdef AF_UNSPEC
3877 PyModule_AddIntConstant(m, "AF_UNSPEC", AF_UNSPEC);
3878 #endif
3879 PyModule_AddIntConstant(m, "AF_INET", AF_INET);
3880 #ifdef AF_INET6
3881 PyModule_AddIntConstant(m, "AF_INET6", AF_INET6);
3882 #endif /* AF_INET6 */
3883 #if defined(AF_UNIX)
3884 PyModule_AddIntConstant(m, "AF_UNIX", AF_UNIX);
3885 #endif /* AF_UNIX */
3886 #ifdef AF_AX25
3887 /* Amateur Radio AX.25 */
3888 PyModule_AddIntConstant(m, "AF_AX25", AF_AX25);
3889 #endif
3890 #ifdef AF_IPX
3891 PyModule_AddIntConstant(m, "AF_IPX", AF_IPX); /* Novell IPX */
3892 #endif
3893 #ifdef AF_APPLETALK
3894 /* Appletalk DDP */
3895 PyModule_AddIntConstant(m, "AF_APPLETALK", AF_APPLETALK);
3896 #endif
3897 #ifdef AF_NETROM
3898 /* Amateur radio NetROM */
3899 PyModule_AddIntConstant(m, "AF_NETROM", AF_NETROM);
3900 #endif
3901 #ifdef AF_BRIDGE
3902 /* Multiprotocol bridge */
3903 PyModule_AddIntConstant(m, "AF_BRIDGE", AF_BRIDGE);
3904 #endif
3905 #ifdef AF_ATMPVC
3906 /* ATM PVCs */
3907 PyModule_AddIntConstant(m, "AF_ATMPVC", AF_ATMPVC);
3908 #endif
3909 #ifdef AF_AAL5
3910 /* Reserved for Werner's ATM */
3911 PyModule_AddIntConstant(m, "AF_AAL5", AF_AAL5);
3912 #endif
3913 #ifdef AF_X25
3914 /* Reserved for X.25 project */
3915 PyModule_AddIntConstant(m, "AF_X25", AF_X25);
3916 #endif
3917 #ifdef AF_INET6
3918 PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); /* IP version 6 */
3919 #endif
3920 #ifdef AF_ROSE
3921 /* Amateur Radio X.25 PLP */
3922 PyModule_AddIntConstant(m, "AF_ROSE", AF_ROSE);
3923 #endif
3924 #ifdef AF_DECnet
3925 /* Reserved for DECnet project */
3926 PyModule_AddIntConstant(m, "AF_DECnet", AF_DECnet);
3927 #endif
3928 #ifdef AF_NETBEUI
3929 /* Reserved for 802.2LLC project */
3930 PyModule_AddIntConstant(m, "AF_NETBEUI", AF_NETBEUI);
3931 #endif
3932 #ifdef AF_SECURITY
3933 /* Security callback pseudo AF */
3934 PyModule_AddIntConstant(m, "AF_SECURITY", AF_SECURITY);
3935 #endif
3936 #ifdef AF_KEY
3937 /* PF_KEY key management API */
3938 PyModule_AddIntConstant(m, "AF_KEY", AF_KEY);
3939 #endif
3940 #ifdef AF_NETLINK
3941 /* */
3942 PyModule_AddIntConstant(m, "AF_NETLINK", AF_NETLINK);
3943 #endif
3944 #ifdef AF_ROUTE
3945 /* Alias to emulate 4.4BSD */
3946 PyModule_AddIntConstant(m, "AF_ROUTE", AF_ROUTE);
3947 #endif
3948 #ifdef AF_ASH
3949 /* Ash */
3950 PyModule_AddIntConstant(m, "AF_ASH", AF_ASH);
3951 #endif
3952 #ifdef AF_ECONET
3953 /* Acorn Econet */
3954 PyModule_AddIntConstant(m, "AF_ECONET", AF_ECONET);
3955 #endif
3956 #ifdef AF_ATMSVC
3957 /* ATM SVCs */
3958 PyModule_AddIntConstant(m, "AF_ATMSVC", AF_ATMSVC);
3959 #endif
3960 #ifdef AF_SNA
3961 /* Linux SNA Project (nutters!) */
3962 PyModule_AddIntConstant(m, "AF_SNA", AF_SNA);
3963 #endif
3964 #ifdef AF_IRDA
3965 /* IRDA sockets */
3966 PyModule_AddIntConstant(m, "AF_IRDA", AF_IRDA);
3967 #endif
3968 #ifdef AF_PPPOX
3969 /* PPPoX sockets */
3970 PyModule_AddIntConstant(m, "AF_PPPOX", AF_PPPOX);
3971 #endif
3972 #ifdef AF_WANPIPE
3973 /* Wanpipe API Sockets */
3974 PyModule_AddIntConstant(m, "AF_WANPIPE", AF_WANPIPE);
3975 #endif
3976 #ifdef AF_LLC
3977 /* Linux LLC */
3978 PyModule_AddIntConstant(m, "AF_LLC", AF_LLC);
3979 #endif
3981 #ifdef USE_BLUETOOTH
3982 PyModule_AddIntConstant(m, "AF_BLUETOOTH", AF_BLUETOOTH);
3983 PyModule_AddIntConstant(m, "BTPROTO_L2CAP", BTPROTO_L2CAP);
3984 #if !defined(__FreeBSD__)
3985 PyModule_AddIntConstant(m, "BTPROTO_SCO", BTPROTO_SCO);
3986 #endif
3987 PyModule_AddIntConstant(m, "BTPROTO_RFCOMM", BTPROTO_RFCOMM);
3988 PyModule_AddObject(m, "BDADDR_ANY", Py_BuildValue("s", "00:00:00:00:00:00"));
3989 PyModule_AddObject(m, "BDADDR_LOCAL", Py_BuildValue("s", "00:00:00:FF:FF:FF"));
3990 #endif
3992 #ifdef HAVE_NETPACKET_PACKET_H
3993 PyModule_AddIntConstant(m, "AF_PACKET", AF_PACKET);
3994 PyModule_AddIntConstant(m, "PF_PACKET", PF_PACKET);
3995 PyModule_AddIntConstant(m, "PACKET_HOST", PACKET_HOST);
3996 PyModule_AddIntConstant(m, "PACKET_BROADCAST", PACKET_BROADCAST);
3997 PyModule_AddIntConstant(m, "PACKET_MULTICAST", PACKET_MULTICAST);
3998 PyModule_AddIntConstant(m, "PACKET_OTHERHOST", PACKET_OTHERHOST);
3999 PyModule_AddIntConstant(m, "PACKET_OUTGOING", PACKET_OUTGOING);
4000 PyModule_AddIntConstant(m, "PACKET_LOOPBACK", PACKET_LOOPBACK);
4001 PyModule_AddIntConstant(m, "PACKET_FASTROUTE", PACKET_FASTROUTE);
4002 #endif
4004 /* Socket types */
4005 PyModule_AddIntConstant(m, "SOCK_STREAM", SOCK_STREAM);
4006 PyModule_AddIntConstant(m, "SOCK_DGRAM", SOCK_DGRAM);
4007 #ifndef __BEOS__
4008 /* We have incomplete socket support. */
4009 PyModule_AddIntConstant(m, "SOCK_RAW", SOCK_RAW);
4010 PyModule_AddIntConstant(m, "SOCK_SEQPACKET", SOCK_SEQPACKET);
4011 #if defined(SOCK_RDM)
4012 PyModule_AddIntConstant(m, "SOCK_RDM", SOCK_RDM);
4013 #endif
4014 #endif
4016 #ifdef SO_DEBUG
4017 PyModule_AddIntConstant(m, "SO_DEBUG", SO_DEBUG);
4018 #endif
4019 #ifdef SO_ACCEPTCONN
4020 PyModule_AddIntConstant(m, "SO_ACCEPTCONN", SO_ACCEPTCONN);
4021 #endif
4022 #ifdef SO_REUSEADDR
4023 PyModule_AddIntConstant(m, "SO_REUSEADDR", SO_REUSEADDR);
4024 #endif
4025 #ifdef SO_EXCLUSIVEADDRUSE
4026 PyModule_AddIntConstant(m, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE);
4027 #endif
4029 #ifdef SO_KEEPALIVE
4030 PyModule_AddIntConstant(m, "SO_KEEPALIVE", SO_KEEPALIVE);
4031 #endif
4032 #ifdef SO_DONTROUTE
4033 PyModule_AddIntConstant(m, "SO_DONTROUTE", SO_DONTROUTE);
4034 #endif
4035 #ifdef SO_BROADCAST
4036 PyModule_AddIntConstant(m, "SO_BROADCAST", SO_BROADCAST);
4037 #endif
4038 #ifdef SO_USELOOPBACK
4039 PyModule_AddIntConstant(m, "SO_USELOOPBACK", SO_USELOOPBACK);
4040 #endif
4041 #ifdef SO_LINGER
4042 PyModule_AddIntConstant(m, "SO_LINGER", SO_LINGER);
4043 #endif
4044 #ifdef SO_OOBINLINE
4045 PyModule_AddIntConstant(m, "SO_OOBINLINE", SO_OOBINLINE);
4046 #endif
4047 #ifdef SO_REUSEPORT
4048 PyModule_AddIntConstant(m, "SO_REUSEPORT", SO_REUSEPORT);
4049 #endif
4050 #ifdef SO_SNDBUF
4051 PyModule_AddIntConstant(m, "SO_SNDBUF", SO_SNDBUF);
4052 #endif
4053 #ifdef SO_RCVBUF
4054 PyModule_AddIntConstant(m, "SO_RCVBUF", SO_RCVBUF);
4055 #endif
4056 #ifdef SO_SNDLOWAT
4057 PyModule_AddIntConstant(m, "SO_SNDLOWAT", SO_SNDLOWAT);
4058 #endif
4059 #ifdef SO_RCVLOWAT
4060 PyModule_AddIntConstant(m, "SO_RCVLOWAT", SO_RCVLOWAT);
4061 #endif
4062 #ifdef SO_SNDTIMEO
4063 PyModule_AddIntConstant(m, "SO_SNDTIMEO", SO_SNDTIMEO);
4064 #endif
4065 #ifdef SO_RCVTIMEO
4066 PyModule_AddIntConstant(m, "SO_RCVTIMEO", SO_RCVTIMEO);
4067 #endif
4068 #ifdef SO_ERROR
4069 PyModule_AddIntConstant(m, "SO_ERROR", SO_ERROR);
4070 #endif
4071 #ifdef SO_TYPE
4072 PyModule_AddIntConstant(m, "SO_TYPE", SO_TYPE);
4073 #endif
4075 /* Maximum number of connections for "listen" */
4076 #ifdef SOMAXCONN
4077 PyModule_AddIntConstant(m, "SOMAXCONN", SOMAXCONN);
4078 #else
4079 PyModule_AddIntConstant(m, "SOMAXCONN", 5); /* Common value */
4080 #endif
4082 /* Flags for send, recv */
4083 #ifdef MSG_OOB
4084 PyModule_AddIntConstant(m, "MSG_OOB", MSG_OOB);
4085 #endif
4086 #ifdef MSG_PEEK
4087 PyModule_AddIntConstant(m, "MSG_PEEK", MSG_PEEK);
4088 #endif
4089 #ifdef MSG_DONTROUTE
4090 PyModule_AddIntConstant(m, "MSG_DONTROUTE", MSG_DONTROUTE);
4091 #endif
4092 #ifdef MSG_DONTWAIT
4093 PyModule_AddIntConstant(m, "MSG_DONTWAIT", MSG_DONTWAIT);
4094 #endif
4095 #ifdef MSG_EOR
4096 PyModule_AddIntConstant(m, "MSG_EOR", MSG_EOR);
4097 #endif
4098 #ifdef MSG_TRUNC
4099 PyModule_AddIntConstant(m, "MSG_TRUNC", MSG_TRUNC);
4100 #endif
4101 #ifdef MSG_CTRUNC
4102 PyModule_AddIntConstant(m, "MSG_CTRUNC", MSG_CTRUNC);
4103 #endif
4104 #ifdef MSG_WAITALL
4105 PyModule_AddIntConstant(m, "MSG_WAITALL", MSG_WAITALL);
4106 #endif
4107 #ifdef MSG_BTAG
4108 PyModule_AddIntConstant(m, "MSG_BTAG", MSG_BTAG);
4109 #endif
4110 #ifdef MSG_ETAG
4111 PyModule_AddIntConstant(m, "MSG_ETAG", MSG_ETAG);
4112 #endif
4114 /* Protocol level and numbers, usable for [gs]etsockopt */
4115 #ifdef SOL_SOCKET
4116 PyModule_AddIntConstant(m, "SOL_SOCKET", SOL_SOCKET);
4117 #endif
4118 #ifdef SOL_IP
4119 PyModule_AddIntConstant(m, "SOL_IP", SOL_IP);
4120 #else
4121 PyModule_AddIntConstant(m, "SOL_IP", 0);
4122 #endif
4123 #ifdef SOL_IPX
4124 PyModule_AddIntConstant(m, "SOL_IPX", SOL_IPX);
4125 #endif
4126 #ifdef SOL_AX25
4127 PyModule_AddIntConstant(m, "SOL_AX25", SOL_AX25);
4128 #endif
4129 #ifdef SOL_ATALK
4130 PyModule_AddIntConstant(m, "SOL_ATALK", SOL_ATALK);
4131 #endif
4132 #ifdef SOL_NETROM
4133 PyModule_AddIntConstant(m, "SOL_NETROM", SOL_NETROM);
4134 #endif
4135 #ifdef SOL_ROSE
4136 PyModule_AddIntConstant(m, "SOL_ROSE", SOL_ROSE);
4137 #endif
4138 #ifdef SOL_TCP
4139 PyModule_AddIntConstant(m, "SOL_TCP", SOL_TCP);
4140 #else
4141 PyModule_AddIntConstant(m, "SOL_TCP", 6);
4142 #endif
4143 #ifdef SOL_UDP
4144 PyModule_AddIntConstant(m, "SOL_UDP", SOL_UDP);
4145 #else
4146 PyModule_AddIntConstant(m, "SOL_UDP", 17);
4147 #endif
4148 #ifdef IPPROTO_IP
4149 PyModule_AddIntConstant(m, "IPPROTO_IP", IPPROTO_IP);
4150 #else
4151 PyModule_AddIntConstant(m, "IPPROTO_IP", 0);
4152 #endif
4153 #ifdef IPPROTO_HOPOPTS
4154 PyModule_AddIntConstant(m, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS);
4155 #endif
4156 #ifdef IPPROTO_ICMP
4157 PyModule_AddIntConstant(m, "IPPROTO_ICMP", IPPROTO_ICMP);
4158 #else
4159 PyModule_AddIntConstant(m, "IPPROTO_ICMP", 1);
4160 #endif
4161 #ifdef IPPROTO_IGMP
4162 PyModule_AddIntConstant(m, "IPPROTO_IGMP", IPPROTO_IGMP);
4163 #endif
4164 #ifdef IPPROTO_GGP
4165 PyModule_AddIntConstant(m, "IPPROTO_GGP", IPPROTO_GGP);
4166 #endif
4167 #ifdef IPPROTO_IPV4
4168 PyModule_AddIntConstant(m, "IPPROTO_IPV4", IPPROTO_IPV4);
4169 #endif
4170 #ifdef IPPROTO_IPV6
4171 PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
4172 #endif
4173 #ifdef IPPROTO_IPIP
4174 PyModule_AddIntConstant(m, "IPPROTO_IPIP", IPPROTO_IPIP);
4175 #endif
4176 #ifdef IPPROTO_TCP
4177 PyModule_AddIntConstant(m, "IPPROTO_TCP", IPPROTO_TCP);
4178 #else
4179 PyModule_AddIntConstant(m, "IPPROTO_TCP", 6);
4180 #endif
4181 #ifdef IPPROTO_EGP
4182 PyModule_AddIntConstant(m, "IPPROTO_EGP", IPPROTO_EGP);
4183 #endif
4184 #ifdef IPPROTO_PUP
4185 PyModule_AddIntConstant(m, "IPPROTO_PUP", IPPROTO_PUP);
4186 #endif
4187 #ifdef IPPROTO_UDP
4188 PyModule_AddIntConstant(m, "IPPROTO_UDP", IPPROTO_UDP);
4189 #else
4190 PyModule_AddIntConstant(m, "IPPROTO_UDP", 17);
4191 #endif
4192 #ifdef IPPROTO_IDP
4193 PyModule_AddIntConstant(m, "IPPROTO_IDP", IPPROTO_IDP);
4194 #endif
4195 #ifdef IPPROTO_HELLO
4196 PyModule_AddIntConstant(m, "IPPROTO_HELLO", IPPROTO_HELLO);
4197 #endif
4198 #ifdef IPPROTO_ND
4199 PyModule_AddIntConstant(m, "IPPROTO_ND", IPPROTO_ND);
4200 #endif
4201 #ifdef IPPROTO_TP
4202 PyModule_AddIntConstant(m, "IPPROTO_TP", IPPROTO_TP);
4203 #endif
4204 #ifdef IPPROTO_IPV6
4205 PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
4206 #endif
4207 #ifdef IPPROTO_ROUTING
4208 PyModule_AddIntConstant(m, "IPPROTO_ROUTING", IPPROTO_ROUTING);
4209 #endif
4210 #ifdef IPPROTO_FRAGMENT
4211 PyModule_AddIntConstant(m, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT);
4212 #endif
4213 #ifdef IPPROTO_RSVP
4214 PyModule_AddIntConstant(m, "IPPROTO_RSVP", IPPROTO_RSVP);
4215 #endif
4216 #ifdef IPPROTO_GRE
4217 PyModule_AddIntConstant(m, "IPPROTO_GRE", IPPROTO_GRE);
4218 #endif
4219 #ifdef IPPROTO_ESP
4220 PyModule_AddIntConstant(m, "IPPROTO_ESP", IPPROTO_ESP);
4221 #endif
4222 #ifdef IPPROTO_AH
4223 PyModule_AddIntConstant(m, "IPPROTO_AH", IPPROTO_AH);
4224 #endif
4225 #ifdef IPPROTO_MOBILE
4226 PyModule_AddIntConstant(m, "IPPROTO_MOBILE", IPPROTO_MOBILE);
4227 #endif
4228 #ifdef IPPROTO_ICMPV6
4229 PyModule_AddIntConstant(m, "IPPROTO_ICMPV6", IPPROTO_ICMPV6);
4230 #endif
4231 #ifdef IPPROTO_NONE
4232 PyModule_AddIntConstant(m, "IPPROTO_NONE", IPPROTO_NONE);
4233 #endif
4234 #ifdef IPPROTO_DSTOPTS
4235 PyModule_AddIntConstant(m, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS);
4236 #endif
4237 #ifdef IPPROTO_XTP
4238 PyModule_AddIntConstant(m, "IPPROTO_XTP", IPPROTO_XTP);
4239 #endif
4240 #ifdef IPPROTO_EON
4241 PyModule_AddIntConstant(m, "IPPROTO_EON", IPPROTO_EON);
4242 #endif
4243 #ifdef IPPROTO_PIM
4244 PyModule_AddIntConstant(m, "IPPROTO_PIM", IPPROTO_PIM);
4245 #endif
4246 #ifdef IPPROTO_IPCOMP
4247 PyModule_AddIntConstant(m, "IPPROTO_IPCOMP", IPPROTO_IPCOMP);
4248 #endif
4249 #ifdef IPPROTO_VRRP
4250 PyModule_AddIntConstant(m, "IPPROTO_VRRP", IPPROTO_VRRP);
4251 #endif
4252 #ifdef IPPROTO_BIP
4253 PyModule_AddIntConstant(m, "IPPROTO_BIP", IPPROTO_BIP);
4254 #endif
4255 /**/
4256 #ifdef IPPROTO_RAW
4257 PyModule_AddIntConstant(m, "IPPROTO_RAW", IPPROTO_RAW);
4258 #else
4259 PyModule_AddIntConstant(m, "IPPROTO_RAW", 255);
4260 #endif
4261 #ifdef IPPROTO_MAX
4262 PyModule_AddIntConstant(m, "IPPROTO_MAX", IPPROTO_MAX);
4263 #endif
4265 /* Some port configuration */
4266 #ifdef IPPORT_RESERVED
4267 PyModule_AddIntConstant(m, "IPPORT_RESERVED", IPPORT_RESERVED);
4268 #else
4269 PyModule_AddIntConstant(m, "IPPORT_RESERVED", 1024);
4270 #endif
4271 #ifdef IPPORT_USERRESERVED
4272 PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", IPPORT_USERRESERVED);
4273 #else
4274 PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", 5000);
4275 #endif
4277 /* Some reserved IP v.4 addresses */
4278 #ifdef INADDR_ANY
4279 PyModule_AddIntConstant(m, "INADDR_ANY", INADDR_ANY);
4280 #else
4281 PyModule_AddIntConstant(m, "INADDR_ANY", 0x00000000);
4282 #endif
4283 #ifdef INADDR_BROADCAST
4284 PyModule_AddIntConstant(m, "INADDR_BROADCAST", INADDR_BROADCAST);
4285 #else
4286 PyModule_AddIntConstant(m, "INADDR_BROADCAST", 0xffffffff);
4287 #endif
4288 #ifdef INADDR_LOOPBACK
4289 PyModule_AddIntConstant(m, "INADDR_LOOPBACK", INADDR_LOOPBACK);
4290 #else
4291 PyModule_AddIntConstant(m, "INADDR_LOOPBACK", 0x7F000001);
4292 #endif
4293 #ifdef INADDR_UNSPEC_GROUP
4294 PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
4295 #else
4296 PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", 0xe0000000);
4297 #endif
4298 #ifdef INADDR_ALLHOSTS_GROUP
4299 PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP",
4300 INADDR_ALLHOSTS_GROUP);
4301 #else
4302 PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
4303 #endif
4304 #ifdef INADDR_MAX_LOCAL_GROUP
4305 PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP",
4306 INADDR_MAX_LOCAL_GROUP);
4307 #else
4308 PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
4309 #endif
4310 #ifdef INADDR_NONE
4311 PyModule_AddIntConstant(m, "INADDR_NONE", INADDR_NONE);
4312 #else
4313 PyModule_AddIntConstant(m, "INADDR_NONE", 0xffffffff);
4314 #endif
4316 /* IPv4 [gs]etsockopt options */
4317 #ifdef IP_OPTIONS
4318 PyModule_AddIntConstant(m, "IP_OPTIONS", IP_OPTIONS);
4319 #endif
4320 #ifdef IP_HDRINCL
4321 PyModule_AddIntConstant(m, "IP_HDRINCL", IP_HDRINCL);
4322 #endif
4323 #ifdef IP_TOS
4324 PyModule_AddIntConstant(m, "IP_TOS", IP_TOS);
4325 #endif
4326 #ifdef IP_TTL
4327 PyModule_AddIntConstant(m, "IP_TTL", IP_TTL);
4328 #endif
4329 #ifdef IP_RECVOPTS
4330 PyModule_AddIntConstant(m, "IP_RECVOPTS", IP_RECVOPTS);
4331 #endif
4332 #ifdef IP_RECVRETOPTS
4333 PyModule_AddIntConstant(m, "IP_RECVRETOPTS", IP_RECVRETOPTS);
4334 #endif
4335 #ifdef IP_RECVDSTADDR
4336 PyModule_AddIntConstant(m, "IP_RECVDSTADDR", IP_RECVDSTADDR);
4337 #endif
4338 #ifdef IP_RETOPTS
4339 PyModule_AddIntConstant(m, "IP_RETOPTS", IP_RETOPTS);
4340 #endif
4341 #ifdef IP_MULTICAST_IF
4342 PyModule_AddIntConstant(m, "IP_MULTICAST_IF", IP_MULTICAST_IF);
4343 #endif
4344 #ifdef IP_MULTICAST_TTL
4345 PyModule_AddIntConstant(m, "IP_MULTICAST_TTL", IP_MULTICAST_TTL);
4346 #endif
4347 #ifdef IP_MULTICAST_LOOP
4348 PyModule_AddIntConstant(m, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
4349 #endif
4350 #ifdef IP_ADD_MEMBERSHIP
4351 PyModule_AddIntConstant(m, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
4352 #endif
4353 #ifdef IP_DROP_MEMBERSHIP
4354 PyModule_AddIntConstant(m, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
4355 #endif
4356 #ifdef IP_DEFAULT_MULTICAST_TTL
4357 PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_TTL",
4358 IP_DEFAULT_MULTICAST_TTL);
4359 #endif
4360 #ifdef IP_DEFAULT_MULTICAST_LOOP
4361 PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_LOOP",
4362 IP_DEFAULT_MULTICAST_LOOP);
4363 #endif
4364 #ifdef IP_MAX_MEMBERSHIPS
4365 PyModule_AddIntConstant(m, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS);
4366 #endif
4368 /* IPv6 [gs]etsockopt options, defined in RFC2553 */
4369 #ifdef IPV6_JOIN_GROUP
4370 PyModule_AddIntConstant(m, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP);
4371 #endif
4372 #ifdef IPV6_LEAVE_GROUP
4373 PyModule_AddIntConstant(m, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP);
4374 #endif
4375 #ifdef IPV6_MULTICAST_HOPS
4376 PyModule_AddIntConstant(m, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS);
4377 #endif
4378 #ifdef IPV6_MULTICAST_IF
4379 PyModule_AddIntConstant(m, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF);
4380 #endif
4381 #ifdef IPV6_MULTICAST_LOOP
4382 PyModule_AddIntConstant(m, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP);
4383 #endif
4384 #ifdef IPV6_UNICAST_HOPS
4385 PyModule_AddIntConstant(m, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS);
4386 #endif
4387 /* Additional IPV6 socket options, defined in RFC 3493 */
4388 #ifdef IPV6_V6ONLY
4389 PyModule_AddIntConstant(m, "IPV6_V6ONLY", IPV6_V6ONLY);
4390 #endif
4391 /* Advanced IPV6 socket options, from RFC 3542 */
4392 #ifdef IPV6_CHECKSUM
4393 PyModule_AddIntConstant(m, "IPV6_CHECKSUM", IPV6_CHECKSUM);
4394 #endif
4395 #ifdef IPV6_DONTFRAG
4396 PyModule_AddIntConstant(m, "IPV6_DONTFRAG", IPV6_DONTFRAG);
4397 #endif
4398 #ifdef IPV6_DSTOPTS
4399 PyModule_AddIntConstant(m, "IPV6_DSTOPTS", IPV6_DSTOPTS);
4400 #endif
4401 #ifdef IPV6_HOPLIMIT
4402 PyModule_AddIntConstant(m, "IPV6_HOPLIMIT", IPV6_HOPLIMIT);
4403 #endif
4404 #ifdef IPV6_HOPOPTS
4405 PyModule_AddIntConstant(m, "IPV6_HOPOPTS", IPV6_HOPOPTS);
4406 #endif
4407 #ifdef IPV6_NEXTHOP
4408 PyModule_AddIntConstant(m, "IPV6_NEXTHOP", IPV6_NEXTHOP);
4409 #endif
4410 #ifdef IPV6_PATHMTU
4411 PyModule_AddIntConstant(m, "IPV6_PATHMTU", IPV6_PATHMTU);
4412 #endif
4413 #ifdef IPV6_PKTINFO
4414 PyModule_AddIntConstant(m, "IPV6_PKTINFO", IPV6_PKTINFO);
4415 #endif
4416 #ifdef IPV6_RECVDSTOPTS
4417 PyModule_AddIntConstant(m, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS);
4418 #endif
4419 #ifdef IPV6_RECVHOPLIMIT
4420 PyModule_AddIntConstant(m, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT);
4421 #endif
4422 #ifdef IPV6_RECVHOPOPTS
4423 PyModule_AddIntConstant(m, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS);
4424 #endif
4425 #ifdef IPV6_RECVPKTINFO
4426 PyModule_AddIntConstant(m, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO);
4427 #endif
4428 #ifdef IPV6_RECVRTHDR
4429 PyModule_AddIntConstant(m, "IPV6_RECVRTHDR", IPV6_RECVRTHDR);
4430 #endif
4431 #ifdef IPV6_RECVTCLASS
4432 PyModule_AddIntConstant(m, "IPV6_RECVTCLASS", IPV6_RECVTCLASS);
4433 #endif
4434 #ifdef IPV6_RTHDR
4435 PyModule_AddIntConstant(m, "IPV6_RTHDR", IPV6_RTHDR);
4436 #endif
4437 #ifdef IPV6_RTHDRDSTOPTS
4438 PyModule_AddIntConstant(m, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS);
4439 #endif
4440 #ifdef IPV6_RTHDR_TYPE_0
4441 PyModule_AddIntConstant(m, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0);
4442 #endif
4443 #ifdef IPV6_RECVPATHMTU
4444 PyModule_AddIntConstant(m, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU);
4445 #endif
4446 #ifdef IPV6_TCLASS
4447 PyModule_AddIntConstant(m, "IPV6_TCLASS", IPV6_TCLASS);
4448 #endif
4449 #ifdef IPV6_USE_MIN_MTU
4450 PyModule_AddIntConstant(m, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU);
4451 #endif
4453 /* TCP options */
4454 #ifdef TCP_NODELAY
4455 PyModule_AddIntConstant(m, "TCP_NODELAY", TCP_NODELAY);
4456 #endif
4457 #ifdef TCP_MAXSEG
4458 PyModule_AddIntConstant(m, "TCP_MAXSEG", TCP_MAXSEG);
4459 #endif
4460 #ifdef TCP_CORK
4461 PyModule_AddIntConstant(m, "TCP_CORK", TCP_CORK);
4462 #endif
4463 #ifdef TCP_KEEPIDLE
4464 PyModule_AddIntConstant(m, "TCP_KEEPIDLE", TCP_KEEPIDLE);
4465 #endif
4466 #ifdef TCP_KEEPINTVL
4467 PyModule_AddIntConstant(m, "TCP_KEEPINTVL", TCP_KEEPINTVL);
4468 #endif
4469 #ifdef TCP_KEEPCNT
4470 PyModule_AddIntConstant(m, "TCP_KEEPCNT", TCP_KEEPCNT);
4471 #endif
4472 #ifdef TCP_SYNCNT
4473 PyModule_AddIntConstant(m, "TCP_SYNCNT", TCP_SYNCNT);
4474 #endif
4475 #ifdef TCP_LINGER2
4476 PyModule_AddIntConstant(m, "TCP_LINGER2", TCP_LINGER2);
4477 #endif
4478 #ifdef TCP_DEFER_ACCEPT
4479 PyModule_AddIntConstant(m, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT);
4480 #endif
4481 #ifdef TCP_WINDOW_CLAMP
4482 PyModule_AddIntConstant(m, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP);
4483 #endif
4484 #ifdef TCP_INFO
4485 PyModule_AddIntConstant(m, "TCP_INFO", TCP_INFO);
4486 #endif
4487 #ifdef TCP_QUICKACK
4488 PyModule_AddIntConstant(m, "TCP_QUICKACK", TCP_QUICKACK);
4489 #endif
4492 /* IPX options */
4493 #ifdef IPX_TYPE
4494 PyModule_AddIntConstant(m, "IPX_TYPE", IPX_TYPE);
4495 #endif
4497 /* get{addr,name}info parameters */
4498 #ifdef EAI_ADDRFAMILY
4499 PyModule_AddIntConstant(m, "EAI_ADDRFAMILY", EAI_ADDRFAMILY);
4500 #endif
4501 #ifdef EAI_AGAIN
4502 PyModule_AddIntConstant(m, "EAI_AGAIN", EAI_AGAIN);
4503 #endif
4504 #ifdef EAI_BADFLAGS
4505 PyModule_AddIntConstant(m, "EAI_BADFLAGS", EAI_BADFLAGS);
4506 #endif
4507 #ifdef EAI_FAIL
4508 PyModule_AddIntConstant(m, "EAI_FAIL", EAI_FAIL);
4509 #endif
4510 #ifdef EAI_FAMILY
4511 PyModule_AddIntConstant(m, "EAI_FAMILY", EAI_FAMILY);
4512 #endif
4513 #ifdef EAI_MEMORY
4514 PyModule_AddIntConstant(m, "EAI_MEMORY", EAI_MEMORY);
4515 #endif
4516 #ifdef EAI_NODATA
4517 PyModule_AddIntConstant(m, "EAI_NODATA", EAI_NODATA);
4518 #endif
4519 #ifdef EAI_NONAME
4520 PyModule_AddIntConstant(m, "EAI_NONAME", EAI_NONAME);
4521 #endif
4522 #ifdef EAI_OVERFLOW
4523 PyModule_AddIntConstant(m, "EAI_OVERFLOW", EAI_OVERFLOW);
4524 #endif
4525 #ifdef EAI_SERVICE
4526 PyModule_AddIntConstant(m, "EAI_SERVICE", EAI_SERVICE);
4527 #endif
4528 #ifdef EAI_SOCKTYPE
4529 PyModule_AddIntConstant(m, "EAI_SOCKTYPE", EAI_SOCKTYPE);
4530 #endif
4531 #ifdef EAI_SYSTEM
4532 PyModule_AddIntConstant(m, "EAI_SYSTEM", EAI_SYSTEM);
4533 #endif
4534 #ifdef EAI_BADHINTS
4535 PyModule_AddIntConstant(m, "EAI_BADHINTS", EAI_BADHINTS);
4536 #endif
4537 #ifdef EAI_PROTOCOL
4538 PyModule_AddIntConstant(m, "EAI_PROTOCOL", EAI_PROTOCOL);
4539 #endif
4540 #ifdef EAI_MAX
4541 PyModule_AddIntConstant(m, "EAI_MAX", EAI_MAX);
4542 #endif
4543 #ifdef AI_PASSIVE
4544 PyModule_AddIntConstant(m, "AI_PASSIVE", AI_PASSIVE);
4545 #endif
4546 #ifdef AI_CANONNAME
4547 PyModule_AddIntConstant(m, "AI_CANONNAME", AI_CANONNAME);
4548 #endif
4549 #ifdef AI_NUMERICHOST
4550 PyModule_AddIntConstant(m, "AI_NUMERICHOST", AI_NUMERICHOST);
4551 #endif
4552 #ifdef AI_NUMERICSERV
4553 PyModule_AddIntConstant(m, "AI_NUMERICSERV", AI_NUMERICSERV);
4554 #endif
4555 #ifdef AI_MASK
4556 PyModule_AddIntConstant(m, "AI_MASK", AI_MASK);
4557 #endif
4558 #ifdef AI_ALL
4559 PyModule_AddIntConstant(m, "AI_ALL", AI_ALL);
4560 #endif
4561 #ifdef AI_V4MAPPED_CFG
4562 PyModule_AddIntConstant(m, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG);
4563 #endif
4564 #ifdef AI_ADDRCONFIG
4565 PyModule_AddIntConstant(m, "AI_ADDRCONFIG", AI_ADDRCONFIG);
4566 #endif
4567 #ifdef AI_V4MAPPED
4568 PyModule_AddIntConstant(m, "AI_V4MAPPED", AI_V4MAPPED);
4569 #endif
4570 #ifdef AI_DEFAULT
4571 PyModule_AddIntConstant(m, "AI_DEFAULT", AI_DEFAULT);
4572 #endif
4573 #ifdef NI_MAXHOST
4574 PyModule_AddIntConstant(m, "NI_MAXHOST", NI_MAXHOST);
4575 #endif
4576 #ifdef NI_MAXSERV
4577 PyModule_AddIntConstant(m, "NI_MAXSERV", NI_MAXSERV);
4578 #endif
4579 #ifdef NI_NOFQDN
4580 PyModule_AddIntConstant(m, "NI_NOFQDN", NI_NOFQDN);
4581 #endif
4582 #ifdef NI_NUMERICHOST
4583 PyModule_AddIntConstant(m, "NI_NUMERICHOST", NI_NUMERICHOST);
4584 #endif
4585 #ifdef NI_NAMEREQD
4586 PyModule_AddIntConstant(m, "NI_NAMEREQD", NI_NAMEREQD);
4587 #endif
4588 #ifdef NI_NUMERICSERV
4589 PyModule_AddIntConstant(m, "NI_NUMERICSERV", NI_NUMERICSERV);
4590 #endif
4591 #ifdef NI_DGRAM
4592 PyModule_AddIntConstant(m, "NI_DGRAM", NI_DGRAM);
4593 #endif
4595 /* shutdown() parameters */
4596 #ifdef SHUT_RD
4597 PyModule_AddIntConstant(m, "SHUT_RD", SHUT_RD);
4598 #elif defined(SD_RECEIVE)
4599 PyModule_AddIntConstant(m, "SHUT_RD", SD_RECEIVE);
4600 #else
4601 PyModule_AddIntConstant(m, "SHUT_RD", 0);
4602 #endif
4603 #ifdef SHUT_WR
4604 PyModule_AddIntConstant(m, "SHUT_WR", SHUT_WR);
4605 #elif defined(SD_SEND)
4606 PyModule_AddIntConstant(m, "SHUT_WR", SD_SEND);
4607 #else
4608 PyModule_AddIntConstant(m, "SHUT_WR", 1);
4609 #endif
4610 #ifdef SHUT_RDWR
4611 PyModule_AddIntConstant(m, "SHUT_RDWR", SHUT_RDWR);
4612 #elif defined(SD_BOTH)
4613 PyModule_AddIntConstant(m, "SHUT_RDWR", SD_BOTH);
4614 #else
4615 PyModule_AddIntConstant(m, "SHUT_RDWR", 2);
4616 #endif
4618 /* Initialize gethostbyname lock */
4619 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
4620 netdb_lock = PyThread_allocate_lock();
4621 #endif
4625 #ifndef HAVE_INET_PTON
4627 /* Simplistic emulation code for inet_pton that only works for IPv4 */
4628 /* These are not exposed because they do not set errno properly */
4631 inet_pton(int af, const char *src, void *dst)
4633 if (af == AF_INET) {
4634 long packed_addr;
4635 packed_addr = inet_addr(src);
4636 if (packed_addr == INADDR_NONE)
4637 return 0;
4638 memcpy(dst, &packed_addr, 4);
4639 return 1;
4641 /* Should set errno to EAFNOSUPPORT */
4642 return -1;
4645 const char *
4646 inet_ntop(int af, const void *src, char *dst, socklen_t size)
4648 if (af == AF_INET) {
4649 struct in_addr packed_addr;
4650 if (size < 16)
4651 /* Should set errno to ENOSPC. */
4652 return NULL;
4653 memcpy(&packed_addr, src, sizeof(packed_addr));
4654 return strncpy(dst, inet_ntoa(packed_addr), size);
4656 /* Should set errno to EAFNOSUPPORT */
4657 return NULL;
4660 #endif