Move setting of ioready 'wait' earlier in call chain, to
[python/dscho.git] / Modules / socketmodule.c
blob2b8e3ea51f89ba9b6769101d2493e1bcecff5177
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.socket([family[, type [, proto]]]) --> new socket object
30 - socket.ntohs(16 bit value) --> new int object
31 - socket.ntohl(32 bit value) --> new int object
32 - socket.htons(16 bit value) --> new int object
33 - socket.htonl(32 bit value) --> new int object
34 - socket.getaddrinfo(host, port [, family, socktype, proto, flags])
35 --> List of (family, socktype, proto, canonname, sockaddr)
36 - socket.getnameinfo(sockaddr, flags) --> (host, port)
37 - socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
38 - socket.inet_aton(IP address) -> 32-bit packed IP representation
39 - socket.inet_ntoa(packed IP) -> IP address string
40 - socket.getdefaulttimeout() -> None | float
41 - socket.setdefaulttimeout(None | float)
42 - an Internet socket address is a pair (hostname, port)
43 where hostname can be anything recognized by gethostbyname()
44 (including the dd.dd.dd.dd notation) and port is in host byte order
45 - where a hostname is returned, the dd.dd.dd.dd notation is used
46 - a UNIX domain socket address is a string specifying the pathname
47 - an AF_PACKET socket address is a tuple containing a string
48 specifying the ethernet interface and an integer specifying
49 the Ethernet protocol number to be received. For example:
50 ("eth0",0x1234). Optional 3rd,4th,5th elements in the tuple
51 specify packet-type and ha-type/addr -- these are ignored by
52 networking code, but accepted since they are returned by the
53 getsockname() method.
55 Local naming conventions:
57 - names starting with sock_ are socket object methods
58 - names starting with socket_ are module-level functions
59 - names starting with PySocket are exported through socketmodule.h
63 #include "Python.h"
65 /* Socket object documentation */
66 PyDoc_STRVAR(sock_doc,
67 "socket([family[, type[, proto]]]) -> socket object\n\
68 \n\
69 Open a socket of the given type. The family argument specifies the\n\
70 address family; it defaults to AF_INET. The type argument specifies\n\
71 whether this is a stream (SOCK_STREAM, this is the default)\n\
72 or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0,\n\
73 specifying the default protocol. Keyword arguments are accepted.\n\
74 \n\
75 A socket object represents one endpoint of a network connection.\n\
76 \n\
77 Methods of socket objects (keyword arguments not allowed):\n\
78 \n\
79 accept() -- accept a connection, returning new socket and client address\n\
80 bind(addr) -- bind the socket to a local address\n\
81 close() -- close the socket\n\
82 connect(addr) -- connect the socket to a remote address\n\
83 connect_ex(addr) -- connect, return an error code instead of an exception\n\
84 dup() -- return a new socket object identical to the current one [*]\n\
85 fileno() -- return underlying file descriptor\n\
86 getpeername() -- return remote address [*]\n\
87 getsockname() -- return local address\n\
88 getsockopt(level, optname[, buflen]) -- get socket options\n\
89 gettimeout() -- return timeout or None\n\
90 listen(n) -- start listening for incoming connections\n\
91 makefile([mode, [bufsize]]) -- return a file object for the socket [*]\n\
92 recv(buflen[, flags]) -- receive data\n\
93 recvfrom(buflen[, flags]) -- receive data and sender's address\n\
94 sendall(data[, flags]) -- send all data\n\
95 send(data[, flags]) -- send data, may not send all of it\n\
96 sendto(data[, flags], addr) -- send data to a given address\n\
97 setblocking(0 | 1) -- set or clear the blocking I/O flag\n\
98 setsockopt(level, optname, value) -- set socket options\n\
99 settimeout(None | float) -- set or clear the timeout\n\
100 shutdown(how) -- shut down traffic in one or both directions\n\
102 [*] not available on all platforms!");
104 /* XXX This is a terrible mess of of platform-dependent preprocessor hacks.
105 I hope some day someone can clean this up please... */
107 /* Hacks for gethostbyname_r(). On some non-Linux platforms, the configure
108 script doesn't get this right, so we hardcode some platform checks below.
109 On the other hand, not all Linux versions agree, so there the settings
110 computed by the configure script are needed! */
112 #ifndef linux
113 # undef HAVE_GETHOSTBYNAME_R_3_ARG
114 # undef HAVE_GETHOSTBYNAME_R_5_ARG
115 # undef HAVE_GETHOSTBYNAME_R_6_ARG
116 #endif
118 #ifndef WITH_THREAD
119 # undef HAVE_GETHOSTBYNAME_R
120 #endif
122 #ifdef HAVE_GETHOSTBYNAME_R
123 # if defined(_AIX) || defined(__osf__)
124 # define HAVE_GETHOSTBYNAME_R_3_ARG
125 # elif defined(__sun) || defined(__sgi)
126 # define HAVE_GETHOSTBYNAME_R_5_ARG
127 # elif defined(linux)
128 /* Rely on the configure script */
129 # else
130 # undef HAVE_GETHOSTBYNAME_R
131 # endif
132 #endif
134 #if !defined(HAVE_GETHOSTBYNAME_R) && defined(WITH_THREAD) && \
135 !defined(MS_WINDOWS)
136 # define USE_GETHOSTBYNAME_LOCK
137 #endif
139 #ifdef USE_GETHOSTBYNAME_LOCK
140 # include "pythread.h"
141 #endif
143 #if defined(PYCC_VACPP)
144 # include <types.h>
145 # include <io.h>
146 # include <sys/ioctl.h>
147 # include <utils.h>
148 # include <ctype.h>
149 #endif
151 #if defined(__VMS)
152 #if ! defined(_SOCKADDR_LEN)
153 # ifdef getaddrinfo
154 # undef getaddrinfo
155 # endif
156 # include "TCPIP_IOCTL_ROUTINE"
157 #else
158 # include <ioctl.h>
159 #endif
160 #endif
162 #if defined(PYOS_OS2)
163 # define INCL_DOS
164 # define INCL_DOSERRORS
165 # define INCL_NOPMAPI
166 # include <os2.h>
167 #endif
169 #if defined(__sgi)&&_COMPILER_VERSION>700 && !_SGIAPI
170 /* make sure that the reentrant (gethostbyaddr_r etc)
171 functions are declared correctly if compiling with
172 MIPSPro 7.x in ANSI C mode (default) */
173 #define _SGIAPI 1
174 #include "netdb.h"
175 #endif
177 /* Generic includes */
178 #include <sys/types.h>
179 #include <signal.h>
181 /* Generic socket object definitions and includes */
182 #define PySocket_BUILDING_SOCKET
183 #include "socketmodule.h"
185 /* Addressing includes */
187 #ifndef MS_WINDOWS
189 /* Non-MS WINDOWS includes */
190 # include <netdb.h>
192 /* Headers needed for inet_ntoa() and inet_addr() */
193 # ifdef __BEOS__
194 # include <net/netdb.h>
195 # elif defined(PYOS_OS2) && defined(PYCC_VACPP)
196 # include <netdb.h>
197 typedef size_t socklen_t;
198 # else
199 # include <arpa/inet.h>
200 # endif
202 # ifndef RISCOS
203 # include <fcntl.h>
204 # else
205 # include <sys/fcntl.h>
206 # define NO_DUP
207 int h_errno; /* not used */
208 # endif
210 #else
212 /* MS_WINDOWS includes */
213 # include <fcntl.h>
215 #endif
217 #ifdef HAVE_STDDEF_H
218 # include <stddef.h>
219 #endif
221 #ifndef offsetof
222 # define offsetof(type, member) ((size_t)(&((type *)0)->member))
223 #endif
225 #ifndef O_NONBLOCK
226 # define O_NONBLOCK O_NDELAY
227 #endif
229 #include "addrinfo.h"
231 #ifndef HAVE_INET_PTON
232 int inet_pton(int af, const char *src, void *dst);
233 const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
234 #endif
236 #ifdef __APPLE__
237 /* On OS X, getaddrinfo returns no error indication of lookup
238 failure, so we must use the emulation instead of the libinfo
239 implementation. Unfortunately, performing an autoconf test
240 for this bug would require DNS access for the machine performing
241 the configuration, which is not acceptable. Therefore, we
242 determine the bug just by checking for __APPLE__. If this bug
243 gets ever fixed, perhaps checking for sys/version.h would be
244 appropriate, which is 10/0 on the system with the bug. */
245 #ifndef HAVE_GETNAMEINFO
246 /* This bug seems to be fixed in Jaguar. Ths easiest way I could
247 Find to check for Jaguar is that it has getnameinfo(), which
248 older releases don't have */
249 #undef HAVE_GETADDRINFO
250 /* avoid clashes with the C library definition of the symbol. */
251 #define getaddrinfo fake_getaddrinfo
252 #endif
253 #endif
255 /* I know this is a bad practice, but it is the easiest... */
256 #if !defined(HAVE_GETADDRINFO)
257 #include "getaddrinfo.c"
258 #endif
259 #if !defined(HAVE_GETNAMEINFO)
260 #include "getnameinfo.c"
261 #endif
263 #if defined(MS_WINDOWS) || defined(__BEOS__)
264 /* BeOS suffers from the same socket dichotomy as Win32... - [cjh] */
265 /* seem to be a few differences in the API */
266 #define SOCKETCLOSE closesocket
267 #define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */
268 #endif
270 #ifdef MS_WIN32
271 #define EAFNOSUPPORT WSAEAFNOSUPPORT
272 #define snprintf _snprintf
273 #endif
275 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
276 #define SOCKETCLOSE soclose
277 #define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
278 #endif
280 #ifndef SOCKETCLOSE
281 #define SOCKETCLOSE close
282 #endif
284 #ifdef __VMS
285 /* TCP/IP Services for VMS uses a maximum send/revc buffer length of 65535 */
286 #define SEGMENT_SIZE 65535
287 #endif
289 /* XXX There's a problem here: *static* functions are not supposed to have
290 a Py prefix (or use CapitalizedWords). Later... */
292 /* Global variable holding the exception type for errors detected
293 by this module (but not argument type or memory errors, etc.). */
294 static PyObject *socket_error;
295 static PyObject *socket_herror;
296 static PyObject *socket_gaierror;
298 #ifdef RISCOS
299 /* Global variable which is !=0 if Python is running in a RISC OS taskwindow */
300 static int taskwindow;
301 #endif
303 /* A forward reference to the socket type object.
304 The sock_type variable contains pointers to various functions,
305 some of which call new_sockobject(), which uses sock_type, so
306 there has to be a circular reference. */
307 static PyTypeObject sock_type;
309 /* Convenience function to raise an error according to errno
310 and return a NULL pointer from a function. */
312 static PyObject *
313 set_error(void)
315 #ifdef MS_WINDOWS
316 int err_no = WSAGetLastError();
317 static struct {
318 int no;
319 const char *msg;
320 } *msgp, msgs[] = {
321 {WSAEINTR, "Interrupted system call"},
322 {WSAEBADF, "Bad file descriptor"},
323 {WSAEACCES, "Permission denied"},
324 {WSAEFAULT, "Bad address"},
325 {WSAEINVAL, "Invalid argument"},
326 {WSAEMFILE, "Too many open files"},
327 {WSAEWOULDBLOCK,
328 "The socket operation could not complete "
329 "without blocking"},
330 {WSAEINPROGRESS, "Operation now in progress"},
331 {WSAEALREADY, "Operation already in progress"},
332 {WSAENOTSOCK, "Socket operation on non-socket"},
333 {WSAEDESTADDRREQ, "Destination address required"},
334 {WSAEMSGSIZE, "Message too long"},
335 {WSAEPROTOTYPE, "Protocol wrong type for socket"},
336 {WSAENOPROTOOPT, "Protocol not available"},
337 {WSAEPROTONOSUPPORT, "Protocol not supported"},
338 {WSAESOCKTNOSUPPORT, "Socket type not supported"},
339 {WSAEOPNOTSUPP, "Operation not supported"},
340 {WSAEPFNOSUPPORT, "Protocol family not supported"},
341 {WSAEAFNOSUPPORT, "Address family not supported"},
342 {WSAEADDRINUSE, "Address already in use"},
343 {WSAEADDRNOTAVAIL, "Can't assign requested address"},
344 {WSAENETDOWN, "Network is down"},
345 {WSAENETUNREACH, "Network is unreachable"},
346 {WSAENETRESET, "Network dropped connection on reset"},
347 {WSAECONNABORTED, "Software caused connection abort"},
348 {WSAECONNRESET, "Connection reset by peer"},
349 {WSAENOBUFS, "No buffer space available"},
350 {WSAEISCONN, "Socket is already connected"},
351 {WSAENOTCONN, "Socket is not connected"},
352 {WSAESHUTDOWN, "Can't send after socket shutdown"},
353 {WSAETOOMANYREFS, "Too many references: can't splice"},
354 {WSAETIMEDOUT, "Operation timed out"},
355 {WSAECONNREFUSED, "Connection refused"},
356 {WSAELOOP, "Too many levels of symbolic links"},
357 {WSAENAMETOOLONG, "File name too long"},
358 {WSAEHOSTDOWN, "Host is down"},
359 {WSAEHOSTUNREACH, "No route to host"},
360 {WSAENOTEMPTY, "Directory not empty"},
361 {WSAEPROCLIM, "Too many processes"},
362 {WSAEUSERS, "Too many users"},
363 {WSAEDQUOT, "Disc quota exceeded"},
364 {WSAESTALE, "Stale NFS file handle"},
365 {WSAEREMOTE, "Too many levels of remote in path"},
366 {WSASYSNOTREADY, "Network subsystem is unvailable"},
367 {WSAVERNOTSUPPORTED, "WinSock version is not supported"},
368 {WSANOTINITIALISED,
369 "Successful WSAStartup() not yet performed"},
370 {WSAEDISCON, "Graceful shutdown in progress"},
371 /* Resolver errors */
372 {WSAHOST_NOT_FOUND, "No such host is known"},
373 {WSATRY_AGAIN, "Host not found, or server failed"},
374 {WSANO_RECOVERY, "Unexpected server error encountered"},
375 {WSANO_DATA, "Valid name without requested data"},
376 {WSANO_ADDRESS, "No address, look for MX record"},
377 {0, NULL}
379 if (err_no) {
380 PyObject *v;
381 const char *msg = "winsock error";
383 for (msgp = msgs; msgp->msg; msgp++) {
384 if (err_no == msgp->no) {
385 msg = msgp->msg;
386 break;
390 v = Py_BuildValue("(is)", err_no, msg);
391 if (v != NULL) {
392 PyErr_SetObject(socket_error, v);
393 Py_DECREF(v);
395 return NULL;
397 else
398 #endif
400 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
401 if (sock_errno() != NO_ERROR) {
402 APIRET rc;
403 ULONG msglen;
404 char outbuf[100];
405 int myerrorcode = sock_errno();
407 /* Retrieve socket-related error message from MPTN.MSG file */
408 rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf),
409 myerrorcode - SOCBASEERR + 26,
410 "mptn.msg",
411 &msglen);
412 if (rc == NO_ERROR) {
413 PyObject *v;
415 /* OS/2 doesn't guarantee a terminator */
416 outbuf[msglen] = '\0';
417 if (strlen(outbuf) > 0) {
418 /* If non-empty msg, trim CRLF */
419 char *lastc = &outbuf[ strlen(outbuf)-1 ];
420 while (lastc > outbuf && isspace(*lastc)) {
421 /* Trim trailing whitespace (CRLF) */
422 *lastc-- = '\0';
425 v = Py_BuildValue("(is)", myerrorcode, outbuf);
426 if (v != NULL) {
427 PyErr_SetObject(socket_error, v);
428 Py_DECREF(v);
430 return NULL;
433 #endif
435 return PyErr_SetFromErrno(socket_error);
439 static PyObject *
440 set_herror(int h_error)
442 PyObject *v;
444 #ifdef HAVE_HSTRERROR
445 v = Py_BuildValue("(is)", h_error, (char *)hstrerror(h_error));
446 #else
447 v = Py_BuildValue("(is)", h_error, "host not found");
448 #endif
449 if (v != NULL) {
450 PyErr_SetObject(socket_herror, v);
451 Py_DECREF(v);
454 return NULL;
458 static PyObject *
459 set_gaierror(int error)
461 PyObject *v;
463 #ifdef EAI_SYSTEM
464 /* EAI_SYSTEM is not available on Windows XP. */
465 if (error == EAI_SYSTEM)
466 return set_error();
467 #endif
469 #ifdef HAVE_GAI_STRERROR
470 v = Py_BuildValue("(is)", error, gai_strerror(error));
471 #else
472 v = Py_BuildValue("(is)", error, "getaddrinfo failed");
473 #endif
474 if (v != NULL) {
475 PyErr_SetObject(socket_gaierror, v);
476 Py_DECREF(v);
479 return NULL;
482 /* Function to perform the setting of socket blocking mode
483 internally. block = (1 | 0). */
484 static int
485 internal_setblocking(PySocketSockObject *s, int block)
487 #ifndef RISCOS
488 #ifndef MS_WINDOWS
489 int delay_flag;
490 #endif
491 #endif
493 Py_BEGIN_ALLOW_THREADS
494 #ifdef __BEOS__
495 block = !block;
496 setsockopt(s->sock_fd, SOL_SOCKET, SO_NONBLOCK,
497 (void *)(&block), sizeof(int));
498 #else
499 #ifndef RISCOS
500 #ifndef MS_WINDOWS
501 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
502 block = !block;
503 ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block));
504 #elif defined(__VMS)
505 block = !block;
506 ioctl(s->sock_fd, FIONBIO, (char *)&block);
507 #else /* !PYOS_OS2 && !_VMS */
508 delay_flag = fcntl(s->sock_fd, F_GETFL, 0);
509 if (block)
510 delay_flag &= (~O_NONBLOCK);
511 else
512 delay_flag |= O_NONBLOCK;
513 fcntl(s->sock_fd, F_SETFL, delay_flag);
514 #endif /* !PYOS_OS2 */
515 #else /* MS_WINDOWS */
516 block = !block;
517 ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
518 #endif /* MS_WINDOWS */
519 #endif /* __BEOS__ */
520 #endif /* RISCOS */
521 Py_END_ALLOW_THREADS
523 /* Since these don't return anything */
524 return 1;
527 /* Do a select() on the socket, if necessary (sock_timeout > 0).
528 The argument writing indicates the direction.
529 This does not raise an exception or return a success indicator;
530 we'll let the actual socket call do that. */
531 static void
532 internal_select(PySocketSockObject *s, int writing)
534 fd_set fds;
535 struct timeval tv;
537 /* Nothing to do unless we're in timeout mode (not non-blocking) */
538 if (s->sock_timeout <= 0.0)
539 return;
541 /* Guard against closed socket */
542 if (s->sock_fd < 0)
543 return;
545 /* Construct the arguments to select */
546 tv.tv_sec = (int)s->sock_timeout;
547 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
548 FD_ZERO(&fds);
549 FD_SET(s->sock_fd, &fds);
551 /* See if the socket is ready */
552 if (writing)
553 select(s->sock_fd+1, NULL, &fds, NULL, &tv);
554 else
555 select(s->sock_fd+1, &fds, NULL, NULL, &tv);
558 /* Initialize a new socket object. */
560 static double defaulttimeout = -1.0; /* Default timeout for new sockets */
562 PyMODINIT_FUNC
563 init_sockobject(PySocketSockObject *s,
564 SOCKET_T fd, int family, int type, int proto)
566 #ifdef RISCOS
567 int block = 1;
568 #endif
569 s->sock_fd = fd;
570 s->sock_family = family;
571 s->sock_type = type;
572 s->sock_proto = proto;
573 s->sock_timeout = defaulttimeout;
575 s->errorhandler = &set_error;
577 if (defaulttimeout >= 0.0)
578 internal_setblocking(s, 0);
580 #ifdef RISCOS
581 if (taskwindow)
582 socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
583 #endif
587 /* Create a new socket object.
588 This just creates the object and initializes it.
589 If the creation fails, return NULL and set an exception (implicit
590 in NEWOBJ()). */
592 static PySocketSockObject *
593 new_sockobject(SOCKET_T fd, int family, int type, int proto)
595 PySocketSockObject *s;
596 s = (PySocketSockObject *)
597 PyType_GenericNew(&sock_type, NULL, NULL);
598 if (s != NULL)
599 init_sockobject(s, fd, family, type, proto);
600 return s;
604 /* Lock to allow python interpreter to continue, but only allow one
605 thread to be in gethostbyname */
606 #ifdef USE_GETHOSTBYNAME_LOCK
607 PyThread_type_lock gethostbyname_lock;
608 #endif
611 /* Convert a string specifying a host name or one of a few symbolic
612 names to a numeric IP address. This usually calls gethostbyname()
613 to do the work; the names "" and "<broadcast>" are special.
614 Return the length (IPv4 should be 4 bytes), or negative if
615 an error occurred; then an exception is raised. */
617 static int
618 setipaddr(char *name, struct sockaddr *addr_ret, size_t addr_ret_size, int af)
620 struct addrinfo hints, *res;
621 int error;
623 memset((void *) addr_ret, '\0', sizeof(*addr_ret));
624 if (name[0] == '\0') {
625 int siz;
626 memset(&hints, 0, sizeof(hints));
627 hints.ai_family = af;
628 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
629 hints.ai_flags = AI_PASSIVE;
630 error = getaddrinfo(NULL, "0", &hints, &res);
631 if (error) {
632 set_gaierror(error);
633 return -1;
635 switch (res->ai_family) {
636 case AF_INET:
637 siz = 4;
638 break;
639 #ifdef ENABLE_IPV6
640 case AF_INET6:
641 siz = 16;
642 break;
643 #endif
644 default:
645 freeaddrinfo(res);
646 PyErr_SetString(socket_error,
647 "unsupported address family");
648 return -1;
650 if (res->ai_next) {
651 freeaddrinfo(res);
652 PyErr_SetString(socket_error,
653 "wildcard resolved to multiple address");
654 return -1;
656 if (res->ai_addrlen < addr_ret_size)
657 addr_ret_size = res->ai_addrlen;
658 memcpy(addr_ret, res->ai_addr, addr_ret_size);
659 freeaddrinfo(res);
660 return siz;
662 if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
663 struct sockaddr_in *sin;
664 if (af != AF_INET && af != AF_UNSPEC) {
665 PyErr_SetString(socket_error,
666 "address family mismatched");
667 return -1;
669 sin = (struct sockaddr_in *)addr_ret;
670 memset((void *) sin, '\0', sizeof(*sin));
671 sin->sin_family = AF_INET;
672 #ifdef HAVE_SOCKADDR_SA_LEN
673 sin->sin_len = sizeof(*sin);
674 #endif
675 sin->sin_addr.s_addr = INADDR_BROADCAST;
676 return sizeof(sin->sin_addr);
678 memset(&hints, 0, sizeof(hints));
679 hints.ai_family = af;
680 error = getaddrinfo(name, NULL, &hints, &res);
681 #if defined(__digital__) && defined(__unix__)
682 if (error == EAI_NONAME && af == AF_UNSPEC) {
683 /* On Tru64 V5.1, numeric-to-addr conversion fails
684 if no address family is given. Assume IPv4 for now.*/
685 hints.ai_family = AF_INET;
686 error = getaddrinfo(name, NULL, &hints, &res);
688 #endif
689 if (error) {
690 set_gaierror(error);
691 return -1;
693 if (res->ai_addrlen < addr_ret_size)
694 addr_ret_size = res->ai_addrlen;
695 memcpy((char *) addr_ret, res->ai_addr, addr_ret_size);
696 freeaddrinfo(res);
697 switch (addr_ret->sa_family) {
698 case AF_INET:
699 return 4;
700 #ifdef ENABLE_IPV6
701 case AF_INET6:
702 return 16;
703 #endif
704 default:
705 PyErr_SetString(socket_error, "unknown address family");
706 return -1;
711 /* Create a string object representing an IP address.
712 This is always a string of the form 'dd.dd.dd.dd' (with variable
713 size numbers). */
715 static PyObject *
716 makeipaddr(struct sockaddr *addr, int addrlen)
718 char buf[NI_MAXHOST];
719 int error;
721 error = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0,
722 NI_NUMERICHOST);
723 if (error) {
724 set_gaierror(error);
725 return NULL;
727 return PyString_FromString(buf);
731 /* Create an object representing the given socket address,
732 suitable for passing it back to bind(), connect() etc.
733 The family field of the sockaddr structure is inspected
734 to determine what kind of address it really is. */
736 /*ARGSUSED*/
737 static PyObject *
738 makesockaddr(int sockfd, struct sockaddr *addr, int addrlen)
740 if (addrlen == 0) {
741 /* No address -- may be recvfrom() from known socket */
742 Py_INCREF(Py_None);
743 return Py_None;
746 #ifdef __BEOS__
747 /* XXX: BeOS version of accept() doesn't set family correctly */
748 addr->sa_family = AF_INET;
749 #endif
751 switch (addr->sa_family) {
753 case AF_INET:
755 struct sockaddr_in *a;
756 PyObject *addrobj = makeipaddr(addr, sizeof(*a));
757 PyObject *ret = NULL;
758 if (addrobj) {
759 a = (struct sockaddr_in *)addr;
760 ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
761 Py_DECREF(addrobj);
763 return ret;
766 #if defined(AF_UNIX) && !defined(PYOS_OS2)
767 case AF_UNIX:
769 struct sockaddr_un *a = (struct sockaddr_un *) addr;
770 return PyString_FromString(a->sun_path);
772 #endif /* AF_UNIX */
774 #ifdef ENABLE_IPV6
775 case AF_INET6:
777 struct sockaddr_in6 *a;
778 PyObject *addrobj = makeipaddr(addr, sizeof(*a));
779 PyObject *ret = NULL;
780 if (addrobj) {
781 a = (struct sockaddr_in6 *)addr;
782 ret = Py_BuildValue("Oiii",
783 addrobj,
784 ntohs(a->sin6_port),
785 a->sin6_flowinfo,
786 a->sin6_scope_id);
787 Py_DECREF(addrobj);
789 return ret;
791 #endif
793 #ifdef HAVE_NETPACKET_PACKET_H
794 case AF_PACKET:
796 struct sockaddr_ll *a = (struct sockaddr_ll *)addr;
797 char *ifname = "";
798 struct ifreq ifr;
799 /* need to look up interface name give index */
800 if (a->sll_ifindex) {
801 ifr.ifr_ifindex = a->sll_ifindex;
802 if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0)
803 ifname = ifr.ifr_name;
805 return Py_BuildValue("shbhs#",
806 ifname,
807 ntohs(a->sll_protocol),
808 a->sll_pkttype,
809 a->sll_hatype,
810 a->sll_addr,
811 a->sll_halen);
813 #endif
815 /* More cases here... */
817 default:
818 /* If we don't know the address family, don't raise an
819 exception -- return it as a tuple. */
820 return Py_BuildValue("is#",
821 addr->sa_family,
822 addr->sa_data,
823 sizeof(addr->sa_data));
829 /* Parse a socket address argument according to the socket object's
830 address family. Return 1 if the address was in the proper format,
831 0 of not. The address is returned through addr_ret, its length
832 through len_ret. */
834 static int
835 getsockaddrarg(PySocketSockObject *s, PyObject *args,
836 struct sockaddr **addr_ret, int *len_ret)
838 switch (s->sock_family) {
840 #if defined(AF_UNIX) && !defined(PYOS_OS2)
841 case AF_UNIX:
843 struct sockaddr_un* addr;
844 char *path;
845 int len;
846 addr = (struct sockaddr_un*)&(s->sock_addr).un;
847 if (!PyArg_Parse(args, "t#", &path, &len))
848 return 0;
849 if (len > sizeof addr->sun_path) {
850 PyErr_SetString(socket_error,
851 "AF_UNIX path too long");
852 return 0;
854 addr->sun_family = s->sock_family;
855 memcpy(addr->sun_path, path, len);
856 addr->sun_path[len] = 0;
857 *addr_ret = (struct sockaddr *) addr;
858 *len_ret = len + sizeof(*addr) - sizeof(addr->sun_path);
859 return 1;
861 #endif /* AF_UNIX */
863 case AF_INET:
865 struct sockaddr_in* addr;
866 char *host;
867 int port;
868 addr=(struct sockaddr_in*)&(s->sock_addr).in;
869 if (!PyTuple_Check(args)) {
870 PyErr_Format(
871 PyExc_TypeError,
872 "getsockaddrarg: "
873 "AF_INET address must be tuple, not %.500s",
874 args->ob_type->tp_name);
875 return 0;
877 if (!PyArg_ParseTuple(args, "si:getsockaddrarg", &host, &port))
878 return 0;
879 if (setipaddr(host, (struct sockaddr *)addr, sizeof(*addr), AF_INET) < 0)
880 return 0;
881 addr->sin_family = AF_INET;
882 addr->sin_port = htons((short)port);
883 *addr_ret = (struct sockaddr *) addr;
884 *len_ret = sizeof *addr;
885 return 1;
888 #ifdef ENABLE_IPV6
889 case AF_INET6:
891 struct sockaddr_in6* addr;
892 char *host;
893 int port, flowinfo, scope_id;
894 addr = (struct sockaddr_in6*)&(s->sock_addr).in6;
895 flowinfo = scope_id = 0;
896 if (!PyArg_ParseTuple(args, "si|ii", &host, &port, &flowinfo,
897 &scope_id)) {
898 return 0;
900 if (setipaddr(host, (struct sockaddr *)addr, sizeof(*addr), AF_INET6) < 0)
901 return 0;
902 addr->sin6_family = s->sock_family;
903 addr->sin6_port = htons((short)port);
904 addr->sin6_flowinfo = flowinfo;
905 addr->sin6_scope_id = scope_id;
906 *addr_ret = (struct sockaddr *) addr;
907 *len_ret = sizeof *addr;
908 return 1;
910 #endif
912 #ifdef HAVE_NETPACKET_PACKET_H
913 case AF_PACKET:
915 struct sockaddr_ll* addr;
916 struct ifreq ifr;
917 char *interfaceName;
918 int protoNumber;
919 int hatype = 0;
920 int pkttype = 0;
921 char *haddr;
923 if (!PyArg_ParseTuple(args, "si|iis", &interfaceName,
924 &protoNumber, &pkttype, &hatype, &haddr))
925 return 0;
926 strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name));
927 ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
928 if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
929 s->errorhandler();
930 return 0;
932 addr = &(s->sock_addr.ll);
933 addr->sll_family = AF_PACKET;
934 addr->sll_protocol = htons((short)protoNumber);
935 addr->sll_ifindex = ifr.ifr_ifindex;
936 addr->sll_pkttype = pkttype;
937 addr->sll_hatype = hatype;
938 *addr_ret = (struct sockaddr *) addr;
939 *len_ret = sizeof *addr;
940 return 1;
942 #endif
944 /* More cases here... */
946 default:
947 PyErr_SetString(socket_error, "getsockaddrarg: bad family");
948 return 0;
954 /* Get the address length according to the socket object's address family.
955 Return 1 if the family is known, 0 otherwise. The length is returned
956 through len_ret. */
958 static int
959 getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
961 switch (s->sock_family) {
963 #if defined(AF_UNIX) && !defined(PYOS_OS2)
964 case AF_UNIX:
966 *len_ret = sizeof (struct sockaddr_un);
967 return 1;
969 #endif /* AF_UNIX */
971 case AF_INET:
973 *len_ret = sizeof (struct sockaddr_in);
974 return 1;
977 #ifdef ENABLE_IPV6
978 case AF_INET6:
980 *len_ret = sizeof (struct sockaddr_in6);
981 return 1;
983 #endif
985 #ifdef HAVE_NETPACKET_PACKET_H
986 case AF_PACKET:
988 *len_ret = sizeof (struct sockaddr_ll);
989 return 1;
991 #endif
993 /* More cases here... */
995 default:
996 PyErr_SetString(socket_error, "getsockaddrlen: bad family");
997 return 0;
1003 /* s.accept() method */
1005 static PyObject *
1006 sock_accept(PySocketSockObject *s)
1008 char addrbuf[256];
1009 SOCKET_T newfd;
1010 socklen_t addrlen;
1011 PyObject *sock = NULL;
1012 PyObject *addr = NULL;
1013 PyObject *res = NULL;
1015 if (!getsockaddrlen(s, &addrlen))
1016 return NULL;
1017 memset(addrbuf, 0, addrlen);
1019 Py_BEGIN_ALLOW_THREADS
1020 internal_select(s, 0);
1021 newfd = accept(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
1022 Py_END_ALLOW_THREADS
1024 #ifdef MS_WINDOWS
1025 if (newfd == INVALID_SOCKET)
1026 #else
1027 if (newfd < 0)
1028 #endif
1029 return s->errorhandler();
1031 /* Create the new object with unspecified family,
1032 to avoid calls to bind() etc. on it. */
1033 sock = (PyObject *) new_sockobject(newfd,
1034 s->sock_family,
1035 s->sock_type,
1036 s->sock_proto);
1038 if (sock == NULL) {
1039 SOCKETCLOSE(newfd);
1040 goto finally;
1042 addr = makesockaddr(s->sock_fd, (struct sockaddr *)addrbuf,
1043 addrlen);
1044 if (addr == NULL)
1045 goto finally;
1047 res = Py_BuildValue("OO", sock, addr);
1049 finally:
1050 Py_XDECREF(sock);
1051 Py_XDECREF(addr);
1052 return res;
1055 PyDoc_STRVAR(accept_doc,
1056 "accept() -> (socket object, address info)\n\
1058 Wait for an incoming connection. Return a new socket representing the\n\
1059 connection, and the address of the client. For IP sockets, the address\n\
1060 info is a pair (hostaddr, port).");
1062 /* s.setblocking(flag) method. Argument:
1063 False -- non-blocking mode; same as settimeout(0)
1064 True -- blocking mode; same as settimeout(None)
1067 static PyObject *
1068 sock_setblocking(PySocketSockObject *s, PyObject *arg)
1070 int block;
1072 block = PyInt_AsLong(arg);
1073 if (block == -1 && PyErr_Occurred())
1074 return NULL;
1076 s->sock_timeout = block ? -1.0 : 0.0;
1077 internal_setblocking(s, block);
1079 Py_INCREF(Py_None);
1080 return Py_None;
1083 PyDoc_STRVAR(setblocking_doc,
1084 "setblocking(flag)\n\
1086 Set the socket to blocking (flag is true) or non-blocking (false).\n\
1087 setblocking(True) is equivalent to settimeout(None);\n\
1088 setblocking(False) is equivalent to settimeout(0.0).");
1090 /* s.settimeout(timeout) method. Argument:
1091 None -- no timeout, blocking mode; same as setblocking(True)
1092 0.0 -- non-blocking mode; same as setblocking(False)
1093 > 0 -- timeout mode; operations time out after timeout seconds
1094 < 0 -- illegal; raises an exception
1096 static PyObject *
1097 sock_settimeout(PySocketSockObject *s, PyObject *arg)
1099 double timeout;
1101 if (arg == Py_None)
1102 timeout = -1.0;
1103 else {
1104 timeout = PyFloat_AsDouble(arg);
1105 if (timeout < 0.0) {
1106 if (!PyErr_Occurred())
1107 PyErr_SetString(PyExc_ValueError,
1108 "Timeout value out of range");
1109 return NULL;
1113 s->sock_timeout = timeout;
1114 internal_setblocking(s, timeout < 0.0);
1116 Py_INCREF(Py_None);
1117 return Py_None;
1120 PyDoc_STRVAR(settimeout_doc,
1121 "settimeout(timeout)\n\
1123 Set a timeout on socket operations. 'timeout' can be a float,\n\
1124 giving in seconds, or None. Setting a timeout of None disables\n\
1125 the timeout feature and is equivalent to setblocking(1).\n\
1126 Setting a timeout of zero is the same as setblocking(0).");
1128 /* s.gettimeout() method.
1129 Returns the timeout associated with a socket. */
1130 static PyObject *
1131 sock_gettimeout(PySocketSockObject *s)
1133 if (s->sock_timeout < 0.0) {
1134 Py_INCREF(Py_None);
1135 return Py_None;
1137 else
1138 return PyFloat_FromDouble(s->sock_timeout);
1141 PyDoc_STRVAR(gettimeout_doc,
1142 "gettimeout() -> timeout\n\
1144 Returns the timeout in floating seconds associated with socket \n\
1145 operations. A timeout of None indicates that timeouts on socket \n\
1146 operations are disabled.");
1148 #ifdef RISCOS
1149 /* s.sleeptaskw(1 | 0) method */
1151 static PyObject *
1152 sock_sleeptaskw(PySocketSockObject *s,PyObject *args)
1154 int block;
1155 int delay_flag;
1156 if (!PyArg_Parse(args, "i", &block))
1157 return NULL;
1158 Py_BEGIN_ALLOW_THREADS
1159 socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
1160 Py_END_ALLOW_THREADS
1162 Py_INCREF(Py_None);
1163 return Py_None;
1165 PyDoc_STRVAR(sleeptaskw_doc,
1166 "sleeptaskw(flag)\n\
1168 Allow sleeps in taskwindows.");
1169 #endif
1172 /* s.setsockopt() method.
1173 With an integer third argument, sets an integer option.
1174 With a string third argument, sets an option from a buffer;
1175 use optional built-in module 'struct' to encode the string. */
1177 static PyObject *
1178 sock_setsockopt(PySocketSockObject *s, PyObject *args)
1180 int level;
1181 int optname;
1182 int res;
1183 char *buf;
1184 int buflen;
1185 int flag;
1187 if (PyArg_ParseTuple(args, "iii:setsockopt",
1188 &level, &optname, &flag)) {
1189 buf = (char *) &flag;
1190 buflen = sizeof flag;
1192 else {
1193 PyErr_Clear();
1194 if (!PyArg_ParseTuple(args, "iis#:setsockopt",
1195 &level, &optname, &buf, &buflen))
1196 return NULL;
1198 res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen);
1199 if (res < 0)
1200 return s->errorhandler();
1201 Py_INCREF(Py_None);
1202 return Py_None;
1205 PyDoc_STRVAR(setsockopt_doc,
1206 "setsockopt(level, option, value)\n\
1208 Set a socket option. See the Unix manual for level and option.\n\
1209 The value argument can either be an integer or a string.");
1212 /* s.getsockopt() method.
1213 With two arguments, retrieves an integer option.
1214 With a third integer argument, retrieves a string buffer of that size;
1215 use optional built-in module 'struct' to decode the string. */
1217 static PyObject *
1218 sock_getsockopt(PySocketSockObject *s, PyObject *args)
1220 int level;
1221 int optname;
1222 int res;
1223 PyObject *buf;
1224 socklen_t buflen = 0;
1226 #ifdef __BEOS__
1227 /* We have incomplete socket support. */
1228 PyErr_SetString(socket_error, "getsockopt not supported");
1229 return NULL;
1230 #else
1232 if (!PyArg_ParseTuple(args, "ii|i:getsockopt",
1233 &level, &optname, &buflen))
1234 return NULL;
1236 if (buflen == 0) {
1237 int flag = 0;
1238 socklen_t flagsize = sizeof flag;
1239 res = getsockopt(s->sock_fd, level, optname,
1240 (void *)&flag, &flagsize);
1241 if (res < 0)
1242 return s->errorhandler();
1243 return PyInt_FromLong(flag);
1245 #ifdef __VMS
1246 if (buflen > 1024) {
1247 #else
1248 if (buflen <= 0 || buflen > 1024) {
1249 #endif
1250 PyErr_SetString(socket_error,
1251 "getsockopt buflen out of range");
1252 return NULL;
1254 buf = PyString_FromStringAndSize((char *)NULL, buflen);
1255 if (buf == NULL)
1256 return NULL;
1257 res = getsockopt(s->sock_fd, level, optname,
1258 (void *)PyString_AS_STRING(buf), &buflen);
1259 if (res < 0) {
1260 Py_DECREF(buf);
1261 return s->errorhandler();
1263 _PyString_Resize(&buf, buflen);
1264 return buf;
1265 #endif /* __BEOS__ */
1268 PyDoc_STRVAR(getsockopt_doc,
1269 "getsockopt(level, option[, buffersize]) -> value\n\
1271 Get a socket option. See the Unix manual for level and option.\n\
1272 If a nonzero buffersize argument is given, the return value is a\n\
1273 string of that length; otherwise it is an integer.");
1276 /* s.bind(sockaddr) method */
1278 static PyObject *
1279 sock_bind(PySocketSockObject *s, PyObject *addro)
1281 struct sockaddr *addr;
1282 int addrlen;
1283 int res;
1285 if (!getsockaddrarg(s, addro, &addr, &addrlen))
1286 return NULL;
1287 Py_BEGIN_ALLOW_THREADS
1288 res = bind(s->sock_fd, addr, addrlen);
1289 Py_END_ALLOW_THREADS
1290 if (res < 0)
1291 return s->errorhandler();
1292 Py_INCREF(Py_None);
1293 return Py_None;
1296 PyDoc_STRVAR(bind_doc,
1297 "bind(address)\n\
1299 Bind the socket to a local address. For IP sockets, the address is a\n\
1300 pair (host, port); the host must refer to the local host. For raw packet\n\
1301 sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");
1304 /* s.close() method.
1305 Set the file descriptor to -1 so operations tried subsequently
1306 will surely fail. */
1308 static PyObject *
1309 sock_close(PySocketSockObject *s)
1311 SOCKET_T fd;
1313 if ((fd = s->sock_fd) != -1) {
1314 s->sock_fd = -1;
1315 Py_BEGIN_ALLOW_THREADS
1316 (void) SOCKETCLOSE(fd);
1317 Py_END_ALLOW_THREADS
1319 Py_INCREF(Py_None);
1320 return Py_None;
1323 PyDoc_STRVAR(close_doc,
1324 "close()\n\
1326 Close the socket. It cannot be used after this call.");
1328 static int
1329 internal_connect(PySocketSockObject *s, struct sockaddr *addr, int addrlen)
1331 int res;
1333 res = connect(s->sock_fd, addr, addrlen);
1335 #ifdef MS_WINDOWS
1337 if (s->sock_timeout > 0.0) {
1338 if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK) {
1339 /* This is a mess. Best solution: trust select */
1340 fd_set fds;
1341 struct timeval tv;
1342 tv.tv_sec = (int)s->sock_timeout;
1343 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1344 FD_ZERO(&fds);
1345 FD_SET(s->sock_fd, &fds);
1346 res = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1347 if (res == 0)
1348 res = WSAEWOULDBLOCK;
1349 else if (res > 0)
1350 res = 0;
1351 /* else if (res < 0) an error occurred */
1355 if (res < 0)
1356 res = WSAGetLastError();
1358 #else
1360 if (s->sock_timeout > 0.0) {
1361 if (res < 0 && errno == EINPROGRESS) {
1362 internal_select(s, 1);
1363 res = connect(s->sock_fd, addr, addrlen);
1364 if (res < 0 && errno == EISCONN)
1365 res = 0;
1369 if (res < 0)
1370 res = errno;
1372 #endif
1374 return res;
1377 /* s.connect(sockaddr) method */
1379 static PyObject *
1380 sock_connect(PySocketSockObject *s, PyObject *addro)
1382 struct sockaddr *addr;
1383 int addrlen;
1384 int res;
1386 if (!getsockaddrarg(s, addro, &addr, &addrlen))
1387 return NULL;
1389 Py_BEGIN_ALLOW_THREADS
1390 res = internal_connect(s, addr, addrlen);
1391 Py_END_ALLOW_THREADS
1393 if (res != 0)
1394 return s->errorhandler();
1395 Py_INCREF(Py_None);
1396 return Py_None;
1399 PyDoc_STRVAR(connect_doc,
1400 "connect(address)\n\
1402 Connect the socket to a remote address. For IP sockets, the address\n\
1403 is a pair (host, port).");
1406 /* s.connect_ex(sockaddr) method */
1408 static PyObject *
1409 sock_connect_ex(PySocketSockObject *s, PyObject *addro)
1411 struct sockaddr *addr;
1412 int addrlen;
1413 int res;
1415 if (!getsockaddrarg(s, addro, &addr, &addrlen))
1416 return NULL;
1418 Py_BEGIN_ALLOW_THREADS
1419 res = internal_connect(s, addr, addrlen);
1420 Py_END_ALLOW_THREADS
1422 return PyInt_FromLong((long) res);
1425 PyDoc_STRVAR(connect_ex_doc,
1426 "connect_ex(address) -> errno\n\
1428 This is like connect(address), but returns an error code (the errno value)\n\
1429 instead of raising an exception when an error occurs.");
1432 /* s.fileno() method */
1434 static PyObject *
1435 sock_fileno(PySocketSockObject *s)
1437 #if SIZEOF_SOCKET_T <= SIZEOF_LONG
1438 return PyInt_FromLong((long) s->sock_fd);
1439 #else
1440 return PyLong_FromLongLong((LONG_LONG)s->sock_fd);
1441 #endif
1444 PyDoc_STRVAR(fileno_doc,
1445 "fileno() -> integer\n\
1447 Return the integer file descriptor of the socket.");
1450 #ifndef NO_DUP
1451 /* s.dup() method */
1453 static PyObject *
1454 sock_dup(PySocketSockObject *s)
1456 SOCKET_T newfd;
1457 PyObject *sock;
1459 newfd = dup(s->sock_fd);
1460 if (newfd < 0)
1461 return s->errorhandler();
1462 sock = (PyObject *) new_sockobject(newfd,
1463 s->sock_family,
1464 s->sock_type,
1465 s->sock_proto);
1466 if (sock == NULL)
1467 SOCKETCLOSE(newfd);
1468 return sock;
1471 PyDoc_STRVAR(dup_doc,
1472 "dup() -> socket object\n\
1474 Return a new socket object connected to the same system resource.");
1476 #endif
1479 /* s.getsockname() method */
1481 static PyObject *
1482 sock_getsockname(PySocketSockObject *s)
1484 char addrbuf[256];
1485 int res;
1486 socklen_t addrlen;
1488 if (!getsockaddrlen(s, &addrlen))
1489 return NULL;
1490 memset(addrbuf, 0, addrlen);
1491 Py_BEGIN_ALLOW_THREADS
1492 res = getsockname(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
1493 Py_END_ALLOW_THREADS
1494 if (res < 0)
1495 return s->errorhandler();
1496 return makesockaddr(s->sock_fd, (struct sockaddr *) addrbuf, addrlen);
1499 PyDoc_STRVAR(getsockname_doc,
1500 "getsockname() -> address info\n\
1502 Return the address of the local endpoint. For IP sockets, the address\n\
1503 info is a pair (hostaddr, port).");
1506 #ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
1507 /* s.getpeername() method */
1509 static PyObject *
1510 sock_getpeername(PySocketSockObject *s)
1512 char addrbuf[256];
1513 int res;
1514 socklen_t addrlen;
1516 if (!getsockaddrlen(s, &addrlen))
1517 return NULL;
1518 memset(addrbuf, 0, addrlen);
1519 Py_BEGIN_ALLOW_THREADS
1520 res = getpeername(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
1521 Py_END_ALLOW_THREADS
1522 if (res < 0)
1523 return s->errorhandler();
1524 return makesockaddr(s->sock_fd, (struct sockaddr *) addrbuf, addrlen);
1527 PyDoc_STRVAR(getpeername_doc,
1528 "getpeername() -> address info\n\
1530 Return the address of the remote endpoint. For IP sockets, the address\n\
1531 info is a pair (hostaddr, port).");
1533 #endif /* HAVE_GETPEERNAME */
1536 /* s.listen(n) method */
1538 static PyObject *
1539 sock_listen(PySocketSockObject *s, PyObject *arg)
1541 int backlog;
1542 int res;
1544 backlog = PyInt_AsLong(arg);
1545 if (backlog == -1 && PyErr_Occurred())
1546 return NULL;
1547 Py_BEGIN_ALLOW_THREADS
1548 if (backlog < 1)
1549 backlog = 1;
1550 res = listen(s->sock_fd, backlog);
1551 Py_END_ALLOW_THREADS
1552 if (res < 0)
1553 return s->errorhandler();
1554 Py_INCREF(Py_None);
1555 return Py_None;
1558 PyDoc_STRVAR(listen_doc,
1559 "listen(backlog)\n\
1561 Enable a server to accept connections. The backlog argument must be at\n\
1562 least 1; it specifies the number of unaccepted connection that the system\n\
1563 will allow before refusing new connections.");
1566 #ifndef NO_DUP
1567 /* s.makefile(mode) method.
1568 Create a new open file object referring to a dupped version of
1569 the socket's file descriptor. (The dup() call is necessary so
1570 that the open file and socket objects may be closed independent
1571 of each other.)
1572 The mode argument specifies 'r' or 'w' passed to fdopen(). */
1574 static PyObject *
1575 sock_makefile(PySocketSockObject *s, PyObject *args)
1577 extern int fclose(FILE *);
1578 char *mode = "r";
1579 int bufsize = -1;
1580 #ifdef MS_WIN32
1581 Py_intptr_t fd;
1582 #else
1583 int fd;
1584 #endif
1585 FILE *fp;
1586 PyObject *f;
1587 #ifdef __VMS
1588 char *mode_r = "r";
1589 char *mode_w = "w";
1590 #endif
1592 if (!PyArg_ParseTuple(args, "|si:makefile", &mode, &bufsize))
1593 return NULL;
1594 #ifdef __VMS
1595 if (strcmp(mode,"rb") == 0) {
1596 mode = mode_r;
1598 else {
1599 if (strcmp(mode,"wb") == 0) {
1600 mode = mode_w;
1603 #endif
1604 #ifdef MS_WIN32
1605 if (((fd = _open_osfhandle(s->sock_fd, _O_BINARY)) < 0) ||
1606 ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL))
1607 #else
1608 if ((fd = dup(s->sock_fd)) < 0 || (fp = fdopen(fd, mode)) == NULL)
1609 #endif
1611 if (fd >= 0)
1612 SOCKETCLOSE(fd);
1613 return s->errorhandler();
1615 #ifdef USE_GUSI2
1616 /* Workaround for bug in Metrowerks MSL vs. GUSI I/O library */
1617 if (strchr(mode, 'b') != NULL)
1618 bufsize = 0;
1619 #endif
1620 f = PyFile_FromFile(fp, "<socket>", mode, fclose);
1621 if (f != NULL)
1622 PyFile_SetBufSize(f, bufsize);
1623 return f;
1626 PyDoc_STRVAR(makefile_doc,
1627 "makefile([mode[, buffersize]]) -> file object\n\
1629 Return a regular file object corresponding to the socket.\n\
1630 The mode and buffersize arguments are as for the built-in open() function.");
1632 #endif /* NO_DUP */
1635 /* s.recv(nbytes [,flags]) method */
1637 static PyObject *
1638 sock_recv(PySocketSockObject *s, PyObject *args)
1640 int len, n, flags = 0;
1641 PyObject *buf;
1642 #ifdef __VMS
1643 int read_length;
1644 char *read_buf;
1645 #endif
1647 if (!PyArg_ParseTuple(args, "i|i:recv", &len, &flags))
1648 return NULL;
1650 if (len < 0) {
1651 PyErr_SetString(PyExc_ValueError,
1652 "negative buffersize in recv");
1653 return NULL;
1656 buf = PyString_FromStringAndSize((char *) 0, len);
1657 if (buf == NULL)
1658 return NULL;
1660 #ifndef __VMS
1661 Py_BEGIN_ALLOW_THREADS
1662 internal_select(s, 0);
1663 n = recv(s->sock_fd, PyString_AS_STRING(buf), len, flags);
1664 Py_END_ALLOW_THREADS
1666 if (n < 0) {
1667 Py_DECREF(buf);
1668 return s->errorhandler();
1670 if (n != len)
1671 _PyString_Resize(&buf, n);
1672 #else
1673 read_buf = PyString_AsString(buf);
1674 read_length = len;
1675 while (read_length != 0) {
1676 unsigned int segment;
1678 segment = read_length /SEGMENT_SIZE;
1679 if (segment != 0) {
1680 segment = SEGMENT_SIZE;
1682 else {
1683 segment = read_length;
1686 Py_BEGIN_ALLOW_THREADS
1687 internal_select(s, 0);
1688 n = recv(s->sock_fd, read_buf, segment, flags);
1689 Py_END_ALLOW_THREADS
1691 if (n < 0) {
1692 Py_DECREF(buf);
1693 return s->errorhandler();
1695 if (n != read_length) {
1696 read_buf += n;
1697 break;
1700 read_length -= segment;
1701 read_buf += segment;
1703 if (_PyString_Resize(&buf, (read_buf - PyString_AsString(buf))) < 0)
1705 return NULL;
1707 #endif /* !__VMS */
1708 return buf;
1711 PyDoc_STRVAR(recv_doc,
1712 "recv(buffersize[, flags]) -> data\n\
1714 Receive up to buffersize bytes from the socket. For the optional flags\n\
1715 argument, see the Unix manual. When no data is available, block until\n\
1716 at least one byte is available or until the remote end is closed. When\n\
1717 the remote end is closed and all data is read, return the empty string.");
1720 /* s.recvfrom(nbytes [,flags]) method */
1722 static PyObject *
1723 sock_recvfrom(PySocketSockObject *s, PyObject *args)
1725 char addrbuf[256];
1726 PyObject *buf = NULL;
1727 PyObject *addr = NULL;
1728 PyObject *ret = NULL;
1729 int len, n, flags = 0;
1730 socklen_t addrlen;
1732 if (!PyArg_ParseTuple(args, "i|i:recvfrom", &len, &flags))
1733 return NULL;
1735 if (!getsockaddrlen(s, &addrlen))
1736 return NULL;
1737 buf = PyString_FromStringAndSize((char *) 0, len);
1738 if (buf == NULL)
1739 return NULL;
1741 Py_BEGIN_ALLOW_THREADS
1742 memset(addrbuf, 0, addrlen);
1743 internal_select(s, 0);
1744 n = recvfrom(s->sock_fd, PyString_AS_STRING(buf), len, flags,
1745 #ifndef MS_WINDOWS
1746 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
1747 (struct sockaddr *)addrbuf, &addrlen
1748 #else
1749 (void *)addrbuf, &addrlen
1750 #endif
1751 #else
1752 (struct sockaddr *)addrbuf, &addrlen
1753 #endif
1755 Py_END_ALLOW_THREADS
1757 if (n < 0) {
1758 Py_DECREF(buf);
1759 return s->errorhandler();
1762 if (n != len && _PyString_Resize(&buf, n) < 0)
1763 return NULL;
1765 if (!(addr = makesockaddr(s->sock_fd, (struct sockaddr *)addrbuf,
1766 addrlen)))
1767 goto finally;
1769 ret = Py_BuildValue("OO", buf, addr);
1771 finally:
1772 Py_XDECREF(addr);
1773 Py_XDECREF(buf);
1774 return ret;
1777 PyDoc_STRVAR(recvfrom_doc,
1778 "recvfrom(buffersize[, flags]) -> (data, address info)\n\
1780 Like recv(buffersize, flags) but also return the sender's address info.");
1782 /* s.send(data [,flags]) method */
1784 static PyObject *
1785 sock_send(PySocketSockObject *s, PyObject *args)
1787 char *buf;
1788 int len, n, flags = 0;
1789 #ifdef __VMS
1790 int send_length;
1791 #endif
1793 if (!PyArg_ParseTuple(args, "s#|i:send", &buf, &len, &flags))
1794 return NULL;
1796 #ifndef __VMS
1797 Py_BEGIN_ALLOW_THREADS
1798 internal_select(s, 1);
1799 n = send(s->sock_fd, buf, len, flags);
1800 Py_END_ALLOW_THREADS
1802 if (n < 0)
1803 return s->errorhandler();
1804 #else
1805 /* Divide packet into smaller segments for */
1806 /* TCP/IP Services for OpenVMS */
1807 send_length = len;
1808 while (send_length != 0) {
1809 unsigned int segment;
1811 segment = send_length / SEGMENT_SIZE;
1812 if (segment != 0) {
1813 segment = SEGMENT_SIZE;
1815 else {
1816 segment = send_length;
1818 Py_BEGIN_ALLOW_THREADS
1819 internal_select(s, 1);
1820 n = send(s->sock_fd, buf, segment, flags);
1821 Py_END_ALLOW_THREADS
1822 if (n < 0) {
1823 return s->errorhandler();
1825 send_length -= segment;
1826 buf += segment;
1827 } /* end while */
1828 #endif /* !__VMS */
1829 return PyInt_FromLong((long)n);
1832 PyDoc_STRVAR(send_doc,
1833 "send(data[, flags]) -> count\n\
1835 Send a data string to the socket. For the optional flags\n\
1836 argument, see the Unix manual. Return the number of bytes\n\
1837 sent; this may be less than len(data) if the network is busy.");
1840 /* s.sendall(data [,flags]) method */
1842 static PyObject *
1843 sock_sendall(PySocketSockObject *s, PyObject *args)
1845 char *buf;
1846 int len, n, flags = 0;
1848 if (!PyArg_ParseTuple(args, "s#|i:sendall", &buf, &len, &flags))
1849 return NULL;
1851 Py_BEGIN_ALLOW_THREADS
1852 do {
1853 internal_select(s, 1);
1854 n = send(s->sock_fd, buf, len, flags);
1855 if (n < 0)
1856 break;
1857 buf += n;
1858 len -= n;
1859 } while (len > 0);
1860 Py_END_ALLOW_THREADS
1862 if (n < 0)
1863 return s->errorhandler();
1865 Py_INCREF(Py_None);
1866 return Py_None;
1869 PyDoc_STRVAR(sendall_doc,
1870 "sendall(data[, flags])\n\
1872 Send a data string to the socket. For the optional flags\n\
1873 argument, see the Unix manual. This calls send() repeatedly\n\
1874 until all data is sent. If an error occurs, it's impossible\n\
1875 to tell how much data has been sent.");
1878 /* s.sendto(data, [flags,] sockaddr) method */
1880 static PyObject *
1881 sock_sendto(PySocketSockObject *s, PyObject *args)
1883 PyObject *addro;
1884 char *buf;
1885 struct sockaddr *addr;
1886 int addrlen, len, n, flags;
1888 flags = 0;
1889 if (!PyArg_ParseTuple(args, "s#O:sendto", &buf, &len, &addro)) {
1890 PyErr_Clear();
1891 if (!PyArg_ParseTuple(args, "s#iO:sendto",
1892 &buf, &len, &flags, &addro))
1893 return NULL;
1896 if (!getsockaddrarg(s, addro, &addr, &addrlen))
1897 return NULL;
1899 Py_BEGIN_ALLOW_THREADS
1900 internal_select(s, 1);
1901 n = sendto(s->sock_fd, buf, len, flags, addr, addrlen);
1902 Py_END_ALLOW_THREADS
1904 if (n < 0)
1905 return s->errorhandler();
1906 return PyInt_FromLong((long)n);
1909 PyDoc_STRVAR(sendto_doc,
1910 "sendto(data[, flags], address) -> count\n\
1912 Like send(data, flags) but allows specifying the destination address.\n\
1913 For IP sockets, the address is a pair (hostaddr, port).");
1916 /* s.shutdown(how) method */
1918 static PyObject *
1919 sock_shutdown(PySocketSockObject *s, PyObject *arg)
1921 int how;
1922 int res;
1924 how = PyInt_AsLong(arg);
1925 if (how == -1 && PyErr_Occurred())
1926 return NULL;
1927 Py_BEGIN_ALLOW_THREADS
1928 res = shutdown(s->sock_fd, how);
1929 Py_END_ALLOW_THREADS
1930 if (res < 0)
1931 return s->errorhandler();
1932 Py_INCREF(Py_None);
1933 return Py_None;
1936 PyDoc_STRVAR(shutdown_doc,
1937 "shutdown(flag)\n\
1939 Shut down the reading side of the socket (flag == 0), the writing side\n\
1940 of the socket (flag == 1), or both ends (flag == 2).");
1943 /* List of methods for socket objects */
1945 static PyMethodDef sock_methods[] = {
1946 {"accept", (PyCFunction)sock_accept, METH_NOARGS,
1947 accept_doc},
1948 {"bind", (PyCFunction)sock_bind, METH_O,
1949 bind_doc},
1950 {"close", (PyCFunction)sock_close, METH_NOARGS,
1951 close_doc},
1952 {"connect", (PyCFunction)sock_connect, METH_O,
1953 connect_doc},
1954 {"connect_ex", (PyCFunction)sock_connect_ex, METH_O,
1955 connect_ex_doc},
1956 #ifndef NO_DUP
1957 {"dup", (PyCFunction)sock_dup, METH_NOARGS,
1958 dup_doc},
1959 #endif
1960 {"fileno", (PyCFunction)sock_fileno, METH_NOARGS,
1961 fileno_doc},
1962 #ifdef HAVE_GETPEERNAME
1963 {"getpeername", (PyCFunction)sock_getpeername,
1964 METH_NOARGS, getpeername_doc},
1965 #endif
1966 {"getsockname", (PyCFunction)sock_getsockname,
1967 METH_NOARGS, getsockname_doc},
1968 {"getsockopt", (PyCFunction)sock_getsockopt, METH_VARARGS,
1969 getsockopt_doc},
1970 {"listen", (PyCFunction)sock_listen, METH_O,
1971 listen_doc},
1972 #ifndef NO_DUP
1973 {"makefile", (PyCFunction)sock_makefile, METH_VARARGS,
1974 makefile_doc},
1975 #endif
1976 {"recv", (PyCFunction)sock_recv, METH_VARARGS,
1977 recv_doc},
1978 {"recvfrom", (PyCFunction)sock_recvfrom, METH_VARARGS,
1979 recvfrom_doc},
1980 {"send", (PyCFunction)sock_send, METH_VARARGS,
1981 send_doc},
1982 {"sendall", (PyCFunction)sock_sendall, METH_VARARGS,
1983 sendall_doc},
1984 {"sendto", (PyCFunction)sock_sendto, METH_VARARGS,
1985 sendto_doc},
1986 {"setblocking", (PyCFunction)sock_setblocking, METH_O,
1987 setblocking_doc},
1988 {"settimeout", (PyCFunction)sock_settimeout, METH_O,
1989 settimeout_doc},
1990 {"gettimeout", (PyCFunction)sock_gettimeout, METH_NOARGS,
1991 gettimeout_doc},
1992 {"setsockopt", (PyCFunction)sock_setsockopt, METH_VARARGS,
1993 setsockopt_doc},
1994 {"shutdown", (PyCFunction)sock_shutdown, METH_O,
1995 shutdown_doc},
1996 #ifdef RISCOS
1997 {"sleeptaskw", (PyCFunction)sock_sleeptaskw, METH_VARARGS,
1998 sleeptaskw_doc},
1999 #endif
2000 {NULL, NULL} /* sentinel */
2004 /* Deallocate a socket object in response to the last Py_DECREF().
2005 First close the file description. */
2007 static void
2008 sock_dealloc(PySocketSockObject *s)
2010 if (s->sock_fd != -1)
2011 (void) SOCKETCLOSE(s->sock_fd);
2012 s->ob_type->tp_free((PyObject *)s);
2016 static PyObject *
2017 sock_repr(PySocketSockObject *s)
2019 char buf[512];
2020 #if SIZEOF_SOCKET_T > SIZEOF_LONG
2021 if (s->sock_fd > LONG_MAX) {
2022 /* this can occur on Win64, and actually there is a special
2023 ugly printf formatter for decimal pointer length integer
2024 printing, only bother if necessary*/
2025 PyErr_SetString(PyExc_OverflowError,
2026 "no printf formatter to display "
2027 "the socket descriptor in decimal");
2028 return NULL;
2030 #endif
2031 PyOS_snprintf(
2032 buf, sizeof(buf),
2033 "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
2034 (long)s->sock_fd, s->sock_family,
2035 s->sock_type,
2036 s->sock_proto);
2037 return PyString_FromString(buf);
2041 /* Create a new, uninitialized socket object. */
2043 static PyObject *
2044 sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2046 PyObject *new;
2048 new = type->tp_alloc(type, 0);
2049 if (new != NULL) {
2050 ((PySocketSockObject *)new)->sock_fd = -1;
2051 ((PySocketSockObject *)new)->sock_timeout = -1.0;
2052 ((PySocketSockObject *)new)->errorhandler = &set_error;
2054 return new;
2058 /* Initialize a new socket object. */
2060 /*ARGSUSED*/
2061 static int
2062 sock_initobj(PyObject *self, PyObject *args, PyObject *kwds)
2064 PySocketSockObject *s = (PySocketSockObject *)self;
2065 SOCKET_T fd;
2066 int family = AF_INET, type = SOCK_STREAM, proto = 0;
2067 static char *keywords[] = {"family", "type", "proto", 0};
2069 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2070 "|iii:socket", keywords,
2071 &family, &type, &proto))
2072 return -1;
2074 Py_BEGIN_ALLOW_THREADS
2075 fd = socket(family, type, proto);
2076 Py_END_ALLOW_THREADS
2078 #ifdef MS_WINDOWS
2079 if (fd == INVALID_SOCKET)
2080 #else
2081 if (fd < 0)
2082 #endif
2084 set_error();
2085 return -1;
2087 init_sockobject(s, fd, family, type, proto);
2088 /* From now on, ignore SIGPIPE and let the error checking
2089 do the work. */
2090 #ifdef SIGPIPE
2091 (void) signal(SIGPIPE, SIG_IGN);
2092 #endif
2094 return 0;
2099 /* Type object for socket objects. */
2101 static PyTypeObject sock_type = {
2102 PyObject_HEAD_INIT(0) /* Must fill in type value later */
2103 0, /* ob_size */
2104 "_socket.socket", /* tp_name */
2105 sizeof(PySocketSockObject), /* tp_basicsize */
2106 0, /* tp_itemsize */
2107 (destructor)sock_dealloc, /* tp_dealloc */
2108 0, /* tp_print */
2109 0, /* tp_getattr */
2110 0, /* tp_setattr */
2111 0, /* tp_compare */
2112 (reprfunc)sock_repr, /* tp_repr */
2113 0, /* tp_as_number */
2114 0, /* tp_as_sequence */
2115 0, /* tp_as_mapping */
2116 0, /* tp_hash */
2117 0, /* tp_call */
2118 0, /* tp_str */
2119 PyObject_GenericGetAttr, /* tp_getattro */
2120 0, /* tp_setattro */
2121 0, /* tp_as_buffer */
2122 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2123 sock_doc, /* tp_doc */
2124 0, /* tp_traverse */
2125 0, /* tp_clear */
2126 0, /* tp_richcompare */
2127 0, /* tp_weaklistoffset */
2128 0, /* tp_iter */
2129 0, /* tp_iternext */
2130 sock_methods, /* tp_methods */
2131 0, /* tp_members */
2132 0, /* tp_getset */
2133 0, /* tp_base */
2134 0, /* tp_dict */
2135 0, /* tp_descr_get */
2136 0, /* tp_descr_set */
2137 0, /* tp_dictoffset */
2138 sock_initobj, /* tp_init */
2139 PyType_GenericAlloc, /* tp_alloc */
2140 sock_new, /* tp_new */
2141 PyObject_Del, /* tp_free */
2145 /* Python interface to gethostname(). */
2147 /*ARGSUSED*/
2148 static PyObject *
2149 socket_gethostname(PyObject *self, PyObject *args)
2151 char buf[1024];
2152 int res;
2153 if (!PyArg_ParseTuple(args, ":gethostname"))
2154 return NULL;
2155 Py_BEGIN_ALLOW_THREADS
2156 res = gethostname(buf, (int) sizeof buf - 1);
2157 Py_END_ALLOW_THREADS
2158 if (res < 0)
2159 return set_error();
2160 buf[sizeof buf - 1] = '\0';
2161 return PyString_FromString(buf);
2164 PyDoc_STRVAR(gethostname_doc,
2165 "gethostname() -> string\n\
2167 Return the current host name.");
2170 /* Python interface to gethostbyname(name). */
2172 /*ARGSUSED*/
2173 static PyObject *
2174 socket_gethostbyname(PyObject *self, PyObject *args)
2176 char *name;
2177 struct sockaddr_storage addrbuf;
2179 if (!PyArg_ParseTuple(args, "s:gethostbyname", &name))
2180 return NULL;
2181 if (setipaddr(name, (struct sockaddr *)&addrbuf, sizeof(addrbuf), AF_INET) < 0)
2182 return NULL;
2183 return makeipaddr((struct sockaddr *)&addrbuf,
2184 sizeof(struct sockaddr_in));
2187 PyDoc_STRVAR(gethostbyname_doc,
2188 "gethostbyname(host) -> address\n\
2190 Return the IP address (a string of the form '255.255.255.255') for a host.");
2193 /* Convenience function common to gethostbyname_ex and gethostbyaddr */
2195 static PyObject *
2196 gethost_common(struct hostent *h, struct sockaddr *addr, int alen, int af)
2198 char **pch;
2199 PyObject *rtn_tuple = (PyObject *)NULL;
2200 PyObject *name_list = (PyObject *)NULL;
2201 PyObject *addr_list = (PyObject *)NULL;
2202 PyObject *tmp;
2204 if (h == NULL) {
2205 /* Let's get real error message to return */
2206 #ifndef RISCOS
2207 set_herror(h_errno);
2208 #else
2209 PyErr_SetString(socket_error, "host not found");
2210 #endif
2211 return NULL;
2214 if (h->h_addrtype != af) {
2215 #ifdef HAVE_STRERROR
2216 /* Let's get real error message to return */
2217 PyErr_SetString(socket_error,
2218 (char *)strerror(EAFNOSUPPORT));
2219 #else
2220 PyErr_SetString(
2221 socket_error,
2222 "Address family not supported by protocol family");
2223 #endif
2224 return NULL;
2227 switch (af) {
2229 case AF_INET:
2230 if (alen < sizeof(struct sockaddr_in))
2231 return NULL;
2232 break;
2234 #ifdef ENABLE_IPV6
2235 case AF_INET6:
2236 if (alen < sizeof(struct sockaddr_in6))
2237 return NULL;
2238 break;
2239 #endif
2243 if ((name_list = PyList_New(0)) == NULL)
2244 goto err;
2246 if ((addr_list = PyList_New(0)) == NULL)
2247 goto err;
2249 for (pch = h->h_aliases; *pch != NULL; pch++) {
2250 int status;
2251 tmp = PyString_FromString(*pch);
2252 if (tmp == NULL)
2253 goto err;
2255 status = PyList_Append(name_list, tmp);
2256 Py_DECREF(tmp);
2258 if (status)
2259 goto err;
2262 for (pch = h->h_addr_list; *pch != NULL; pch++) {
2263 int status;
2265 switch (af) {
2267 case AF_INET:
2269 struct sockaddr_in sin;
2270 memset(&sin, 0, sizeof(sin));
2271 sin.sin_family = af;
2272 #ifdef HAVE_SOCKADDR_SA_LEN
2273 sin.sin_len = sizeof(sin);
2274 #endif
2275 memcpy(&sin.sin_addr, *pch, sizeof(sin.sin_addr));
2276 tmp = makeipaddr((struct sockaddr *)&sin, sizeof(sin));
2278 if (pch == h->h_addr_list && alen >= sizeof(sin))
2279 memcpy((char *) addr, &sin, sizeof(sin));
2280 break;
2283 #ifdef ENABLE_IPV6
2284 case AF_INET6:
2286 struct sockaddr_in6 sin6;
2287 memset(&sin6, 0, sizeof(sin6));
2288 sin6.sin6_family = af;
2289 #ifdef HAVE_SOCKADDR_SA_LEN
2290 sin6.sin6_len = sizeof(sin6);
2291 #endif
2292 memcpy(&sin6.sin6_addr, *pch, sizeof(sin6.sin6_addr));
2293 tmp = makeipaddr((struct sockaddr *)&sin6,
2294 sizeof(sin6));
2296 if (pch == h->h_addr_list && alen >= sizeof(sin6))
2297 memcpy((char *) addr, &sin6, sizeof(sin6));
2298 break;
2300 #endif
2302 default: /* can't happen */
2303 PyErr_SetString(socket_error,
2304 "unsupported address family");
2305 return NULL;
2308 if (tmp == NULL)
2309 goto err;
2311 status = PyList_Append(addr_list, tmp);
2312 Py_DECREF(tmp);
2314 if (status)
2315 goto err;
2318 rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list);
2320 err:
2321 Py_XDECREF(name_list);
2322 Py_XDECREF(addr_list);
2323 return rtn_tuple;
2327 /* Python interface to gethostbyname_ex(name). */
2329 /*ARGSUSED*/
2330 static PyObject *
2331 socket_gethostbyname_ex(PyObject *self, PyObject *args)
2333 char *name;
2334 struct hostent *h;
2335 struct sockaddr_storage addr;
2336 struct sockaddr *sa;
2337 PyObject *ret;
2338 #ifdef HAVE_GETHOSTBYNAME_R
2339 struct hostent hp_allocated;
2340 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
2341 struct hostent_data data;
2342 #else
2343 char buf[16384];
2344 int buf_len = (sizeof buf) - 1;
2345 int errnop;
2346 #endif
2347 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2348 int result;
2349 #endif
2350 #endif /* HAVE_GETHOSTBYNAME_R */
2352 if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name))
2353 return NULL;
2354 if (setipaddr(name, (struct sockaddr *)&addr, sizeof(addr), AF_INET) < 0)
2355 return NULL;
2356 Py_BEGIN_ALLOW_THREADS
2357 #ifdef HAVE_GETHOSTBYNAME_R
2358 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2359 result = gethostbyname_r(name, &hp_allocated, buf, buf_len,
2360 &h, &errnop);
2361 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
2362 h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
2363 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
2364 memset((void *) &data, '\0', sizeof(data));
2365 result = gethostbyname_r(name, &hp_allocated, &data);
2366 h = (result != 0) ? NULL : &hp_allocated;
2367 #endif
2368 #else /* not HAVE_GETHOSTBYNAME_R */
2369 #ifdef USE_GETHOSTBYNAME_LOCK
2370 PyThread_acquire_lock(gethostbyname_lock, 1);
2371 #endif
2372 h = gethostbyname(name);
2373 #endif /* HAVE_GETHOSTBYNAME_R */
2374 Py_END_ALLOW_THREADS
2375 /* Some C libraries would require addr.__ss_family instead of
2376 addr.ss_family.
2377 Therefore, we cast the sockaddr_storage into sockaddr to
2378 access sa_family. */
2379 sa = (struct sockaddr*)&addr;
2380 ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr),
2381 sa->sa_family);
2382 #ifdef USE_GETHOSTBYNAME_LOCK
2383 PyThread_release_lock(gethostbyname_lock);
2384 #endif
2385 return ret;
2388 PyDoc_STRVAR(ghbn_ex_doc,
2389 "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
2391 Return the true host name, a list of aliases, and a list of IP addresses,\n\
2392 for a host. The host argument is a string giving a host name or IP number.");
2395 /* Python interface to gethostbyaddr(IP). */
2397 /*ARGSUSED*/
2398 static PyObject *
2399 socket_gethostbyaddr(PyObject *self, PyObject *args)
2401 #ifdef ENABLE_IPV6
2402 struct sockaddr_storage addr;
2403 #else
2404 struct sockaddr_in addr;
2405 #endif
2406 struct sockaddr *sa = (struct sockaddr *)&addr;
2407 char *ip_num;
2408 struct hostent *h;
2409 PyObject *ret;
2410 #ifdef HAVE_GETHOSTBYNAME_R
2411 struct hostent hp_allocated;
2412 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
2413 struct hostent_data data;
2414 #else
2415 char buf[16384];
2416 int buf_len = (sizeof buf) - 1;
2417 int errnop;
2418 #endif
2419 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2420 int result;
2421 #endif
2422 #endif /* HAVE_GETHOSTBYNAME_R */
2423 char *ap;
2424 int al;
2425 int af;
2427 if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num))
2428 return NULL;
2429 af = AF_UNSPEC;
2430 if (setipaddr(ip_num, sa, sizeof(addr), af) < 0)
2431 return NULL;
2432 af = sa->sa_family;
2433 ap = NULL;
2434 al = 0;
2435 switch (af) {
2436 case AF_INET:
2437 ap = (char *)&((struct sockaddr_in *)sa)->sin_addr;
2438 al = sizeof(((struct sockaddr_in *)sa)->sin_addr);
2439 break;
2440 #ifdef ENABLE_IPV6
2441 case AF_INET6:
2442 ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr;
2443 al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr);
2444 break;
2445 #endif
2446 default:
2447 PyErr_SetString(socket_error, "unsupported address family");
2448 return NULL;
2450 Py_BEGIN_ALLOW_THREADS
2451 #ifdef HAVE_GETHOSTBYNAME_R
2452 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2453 result = gethostbyaddr_r(ap, al, af,
2454 &hp_allocated, buf, buf_len,
2455 &h, &errnop);
2456 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
2457 h = gethostbyaddr_r(ap, al, af,
2458 &hp_allocated, buf, buf_len, &errnop);
2459 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
2460 memset((void *) &data, '\0', sizeof(data));
2461 result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data);
2462 h = (result != 0) ? NULL : &hp_allocated;
2463 #endif
2464 #else /* not HAVE_GETHOSTBYNAME_R */
2465 #ifdef USE_GETHOSTBYNAME_LOCK
2466 PyThread_acquire_lock(gethostbyname_lock, 1);
2467 #endif
2468 h = gethostbyaddr(ap, al, af);
2469 #endif /* HAVE_GETHOSTBYNAME_R */
2470 Py_END_ALLOW_THREADS
2471 ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), af);
2472 #ifdef USE_GETHOSTBYNAME_LOCK
2473 PyThread_release_lock(gethostbyname_lock);
2474 #endif
2475 return ret;
2478 PyDoc_STRVAR(gethostbyaddr_doc,
2479 "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
2481 Return the true host name, a list of aliases, and a list of IP addresses,\n\
2482 for a host. The host argument is a string giving a host name or IP number.");
2485 /* Python interface to getservbyname(name).
2486 This only returns the port number, since the other info is already
2487 known or not useful (like the list of aliases). */
2489 /*ARGSUSED*/
2490 static PyObject *
2491 socket_getservbyname(PyObject *self, PyObject *args)
2493 char *name, *proto;
2494 struct servent *sp;
2495 if (!PyArg_ParseTuple(args, "ss:getservbyname", &name, &proto))
2496 return NULL;
2497 Py_BEGIN_ALLOW_THREADS
2498 sp = getservbyname(name, proto);
2499 Py_END_ALLOW_THREADS
2500 if (sp == NULL) {
2501 PyErr_SetString(socket_error, "service/proto not found");
2502 return NULL;
2504 return PyInt_FromLong((long) ntohs(sp->s_port));
2507 PyDoc_STRVAR(getservbyname_doc,
2508 "getservbyname(servicename, protocolname) -> integer\n\
2510 Return a port number from a service name and protocol name.\n\
2511 The protocol name should be 'tcp' or 'udp'.");
2514 /* Python interface to getprotobyname(name).
2515 This only returns the protocol number, since the other info is
2516 already known or not useful (like the list of aliases). */
2518 /*ARGSUSED*/
2519 static PyObject *
2520 socket_getprotobyname(PyObject *self, PyObject *args)
2522 char *name;
2523 struct protoent *sp;
2524 #ifdef __BEOS__
2525 /* Not available in BeOS yet. - [cjh] */
2526 PyErr_SetString(socket_error, "getprotobyname not supported");
2527 return NULL;
2528 #else
2529 if (!PyArg_ParseTuple(args, "s:getprotobyname", &name))
2530 return NULL;
2531 Py_BEGIN_ALLOW_THREADS
2532 sp = getprotobyname(name);
2533 Py_END_ALLOW_THREADS
2534 if (sp == NULL) {
2535 PyErr_SetString(socket_error, "protocol not found");
2536 return NULL;
2538 return PyInt_FromLong((long) sp->p_proto);
2539 #endif
2542 PyDoc_STRVAR(getprotobyname_doc,
2543 "getprotobyname(name) -> integer\n\
2545 Return the protocol number for the named protocol. (Rarely used.)");
2548 #ifndef NO_DUP
2549 /* Create a socket object from a numeric file description.
2550 Useful e.g. if stdin is a socket.
2551 Additional arguments as for socket(). */
2553 /*ARGSUSED*/
2554 static PyObject *
2555 socket_fromfd(PyObject *self, PyObject *args)
2557 PySocketSockObject *s;
2558 SOCKET_T fd;
2559 int family, type, proto = 0;
2560 if (!PyArg_ParseTuple(args, "iii|i:fromfd",
2561 &fd, &family, &type, &proto))
2562 return NULL;
2563 /* Dup the fd so it and the socket can be closed independently */
2564 fd = dup(fd);
2565 if (fd < 0)
2566 return set_error();
2567 s = new_sockobject(fd, family, type, proto);
2568 /* From now on, ignore SIGPIPE and let the error checking
2569 do the work. */
2570 #ifdef SIGPIPE
2571 (void) signal(SIGPIPE, SIG_IGN);
2572 #endif
2573 return (PyObject *) s;
2576 PyDoc_STRVAR(fromfd_doc,
2577 "fromfd(fd, family, type[, proto]) -> socket object\n\
2579 Create a socket object from the given file descriptor.\n\
2580 The remaining arguments are the same as for socket().");
2582 #endif /* NO_DUP */
2585 static PyObject *
2586 socket_ntohs(PyObject *self, PyObject *args)
2588 int x1, x2;
2590 if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) {
2591 return NULL;
2593 x2 = (int)ntohs((short)x1);
2594 return PyInt_FromLong(x2);
2597 PyDoc_STRVAR(ntohs_doc,
2598 "ntohs(integer) -> integer\n\
2600 Convert a 16-bit integer from network to host byte order.");
2603 static PyObject *
2604 socket_ntohl(PyObject *self, PyObject *arg)
2606 unsigned long x;
2608 if (PyInt_Check(arg)) {
2609 x = PyInt_AS_LONG(arg);
2610 if (x == (unsigned long) -1 && PyErr_Occurred())
2611 return NULL;
2613 else if (PyLong_Check(arg)) {
2614 x = PyLong_AsUnsignedLong(arg);
2615 if (x == (unsigned long) -1 && PyErr_Occurred())
2616 return NULL;
2617 #if SIZEOF_LONG > 4
2619 unsigned long y;
2620 /* only want the trailing 32 bits */
2621 y = x & 0xFFFFFFFFUL;
2622 if (y ^ x)
2623 return PyErr_Format(PyExc_OverflowError,
2624 "long int larger than 32 bits");
2625 x = y;
2627 #endif
2629 else
2630 return PyErr_Format(PyExc_TypeError,
2631 "expected int/long, %s found",
2632 arg->ob_type->tp_name);
2633 if (x == (unsigned long) -1 && PyErr_Occurred())
2634 return NULL;
2635 return PyInt_FromLong(ntohl(x));
2638 PyDoc_STRVAR(ntohl_doc,
2639 "ntohl(integer) -> integer\n\
2641 Convert a 32-bit integer from network to host byte order.");
2644 static PyObject *
2645 socket_htons(PyObject *self, PyObject *args)
2647 unsigned long x1, x2;
2649 if (!PyArg_ParseTuple(args, "i:htons", &x1)) {
2650 return NULL;
2652 x2 = (int)htons((short)x1);
2653 return PyInt_FromLong(x2);
2656 PyDoc_STRVAR(htons_doc,
2657 "htons(integer) -> integer\n\
2659 Convert a 16-bit integer from host to network byte order.");
2662 static PyObject *
2663 socket_htonl(PyObject *self, PyObject *arg)
2665 unsigned long x;
2667 if (PyInt_Check(arg)) {
2668 x = PyInt_AS_LONG(arg);
2669 if (x == (unsigned long) -1 && PyErr_Occurred())
2670 return NULL;
2672 else if (PyLong_Check(arg)) {
2673 x = PyLong_AsUnsignedLong(arg);
2674 if (x == (unsigned long) -1 && PyErr_Occurred())
2675 return NULL;
2676 #if SIZEOF_LONG > 4
2678 unsigned long y;
2679 /* only want the trailing 32 bits */
2680 y = x & 0xFFFFFFFFUL;
2681 if (y ^ x)
2682 return PyErr_Format(PyExc_OverflowError,
2683 "long int larger than 32 bits");
2684 x = y;
2686 #endif
2688 else
2689 return PyErr_Format(PyExc_TypeError,
2690 "expected int/long, %s found",
2691 arg->ob_type->tp_name);
2692 return PyInt_FromLong(htonl(x));
2695 PyDoc_STRVAR(htonl_doc,
2696 "htonl(integer) -> integer\n\
2698 Convert a 32-bit integer from host to network byte order.");
2700 /* socket.inet_aton() and socket.inet_ntoa() functions. */
2702 PyDoc_STRVAR(inet_aton_doc,
2703 "inet_aton(string) -> packed 32-bit IP representation\n\
2705 Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
2706 binary format used in low-level network functions.");
2708 static PyObject*
2709 socket_inet_aton(PyObject *self, PyObject *args)
2711 #ifndef INADDR_NONE
2712 #define INADDR_NONE (-1)
2713 #endif
2714 #ifdef HAVE_INET_ATON
2715 struct in_addr buf;
2716 #else
2717 /* Have to use inet_addr() instead */
2718 unsigned long packed_addr;
2719 #endif
2720 char *ip_addr;
2722 if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr))
2723 return NULL;
2726 #ifdef HAVE_INET_ATON
2727 if (inet_aton(ip_addr, &buf))
2728 return PyString_FromStringAndSize((char *)(&buf),
2729 sizeof(buf));
2731 PyErr_SetString(socket_error,
2732 "illegal IP address string passed to inet_aton");
2733 return NULL;
2735 #else /* ! HAVE_INET_ATON */
2736 /* XXX Problem here: inet_aton('255.255.255.255') raises
2737 an exception while it should be a valid address. */
2738 packed_addr = inet_addr(ip_addr);
2740 if (packed_addr == INADDR_NONE) { /* invalid address */
2741 PyErr_SetString(socket_error,
2742 "illegal IP address string passed to inet_aton");
2743 return NULL;
2745 return PyString_FromStringAndSize((char *) &packed_addr,
2746 sizeof(packed_addr));
2747 #endif
2750 PyDoc_STRVAR(inet_ntoa_doc,
2751 "inet_ntoa(packed_ip) -> ip_address_string\n\
2753 Convert an IP address from 32-bit packed binary format to string format");
2755 static PyObject*
2756 socket_inet_ntoa(PyObject *self, PyObject *args)
2758 char *packed_str;
2759 int addr_len;
2760 struct in_addr packed_addr;
2762 if (!PyArg_ParseTuple(args, "s#:inet_ntoa", &packed_str, &addr_len)) {
2763 return NULL;
2766 if (addr_len != sizeof(packed_addr)) {
2767 PyErr_SetString(socket_error,
2768 "packed IP wrong length for inet_ntoa");
2769 return NULL;
2772 memcpy(&packed_addr, packed_str, addr_len);
2774 return PyString_FromString(inet_ntoa(packed_addr));
2777 /* Python interface to getaddrinfo(host, port). */
2779 /*ARGSUSED*/
2780 static PyObject *
2781 socket_getaddrinfo(PyObject *self, PyObject *args)
2783 struct addrinfo hints, *res;
2784 struct addrinfo *res0 = NULL;
2785 PyObject *pobj = (PyObject *)NULL;
2786 char pbuf[30];
2787 char *hptr, *pptr;
2788 int family, socktype, protocol, flags;
2789 int error;
2790 PyObject *all = (PyObject *)NULL;
2791 PyObject *single = (PyObject *)NULL;
2793 family = socktype = protocol = flags = 0;
2794 family = AF_UNSPEC;
2795 if (!PyArg_ParseTuple(args, "zO|iiii:getaddrinfo",
2796 &hptr, &pobj, &family, &socktype,
2797 &protocol, &flags)) {
2798 return NULL;
2800 if (PyInt_Check(pobj)) {
2801 PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", PyInt_AsLong(pobj));
2802 pptr = pbuf;
2803 } else if (PyString_Check(pobj)) {
2804 pptr = PyString_AsString(pobj);
2805 } else if (pobj == Py_None) {
2806 pptr = (char *)NULL;
2807 } else {
2808 PyErr_SetString(socket_error, "Int or String expected");
2809 return NULL;
2811 memset(&hints, 0, sizeof(hints));
2812 hints.ai_family = family;
2813 hints.ai_socktype = socktype;
2814 hints.ai_protocol = protocol;
2815 hints.ai_flags = flags;
2816 error = getaddrinfo(hptr, pptr, &hints, &res0);
2817 if (error) {
2818 set_gaierror(error);
2819 return NULL;
2822 if ((all = PyList_New(0)) == NULL)
2823 goto err;
2824 for (res = res0; res; res = res->ai_next) {
2825 PyObject *addr =
2826 makesockaddr(-1, res->ai_addr, res->ai_addrlen);
2827 if (addr == NULL)
2828 goto err;
2829 single = Py_BuildValue("iiisO", res->ai_family,
2830 res->ai_socktype, res->ai_protocol,
2831 res->ai_canonname ? res->ai_canonname : "",
2832 addr);
2833 Py_DECREF(addr);
2834 if (single == NULL)
2835 goto err;
2837 if (PyList_Append(all, single))
2838 goto err;
2839 Py_XDECREF(single);
2841 if (res0)
2842 freeaddrinfo(res0);
2843 return all;
2844 err:
2845 Py_XDECREF(single);
2846 Py_XDECREF(all);
2847 if (res0)
2848 freeaddrinfo(res0);
2849 return (PyObject *)NULL;
2852 PyDoc_STRVAR(getaddrinfo_doc,
2853 "getaddrinfo(host, port [, family, socktype, proto, flags])\n\
2854 -> list of (family, socktype, proto, canonname, sockaddr)\n\
2856 Resolve host and port into addrinfo struct.");
2858 /* Python interface to getnameinfo(sa, flags). */
2860 /*ARGSUSED*/
2861 static PyObject *
2862 socket_getnameinfo(PyObject *self, PyObject *args)
2864 PyObject *sa = (PyObject *)NULL;
2865 int flags;
2866 char *hostp;
2867 int port, flowinfo, scope_id;
2868 char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
2869 struct addrinfo hints, *res = NULL;
2870 int error;
2871 PyObject *ret = (PyObject *)NULL;
2873 flags = flowinfo = scope_id = 0;
2874 if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags))
2875 return NULL;
2876 if (!PyArg_ParseTuple(sa, "si|ii",
2877 &hostp, &port, &flowinfo, &scope_id))
2878 return NULL;
2879 PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port);
2880 memset(&hints, 0, sizeof(hints));
2881 hints.ai_family = AF_UNSPEC;
2882 hints.ai_socktype = SOCK_DGRAM; /* make numeric port happy */
2883 error = getaddrinfo(hostp, pbuf, &hints, &res);
2884 if (error) {
2885 set_gaierror(error);
2886 goto fail;
2888 if (res->ai_next) {
2889 PyErr_SetString(socket_error,
2890 "sockaddr resolved to multiple addresses");
2891 goto fail;
2893 switch (res->ai_family) {
2894 case AF_INET:
2896 char *t1;
2897 int t2;
2898 if (PyArg_ParseTuple(sa, "si", &t1, &t2) == 0) {
2899 PyErr_SetString(socket_error,
2900 "IPv4 sockaddr must be 2 tuple");
2901 goto fail;
2903 break;
2905 #ifdef ENABLE_IPV6
2906 case AF_INET6:
2908 struct sockaddr_in6 *sin6;
2909 sin6 = (struct sockaddr_in6 *)res->ai_addr;
2910 sin6->sin6_flowinfo = flowinfo;
2911 sin6->sin6_scope_id = scope_id;
2912 break;
2914 #endif
2916 error = getnameinfo(res->ai_addr, res->ai_addrlen,
2917 hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags);
2918 if (error) {
2919 set_gaierror(error);
2920 goto fail;
2922 ret = Py_BuildValue("ss", hbuf, pbuf);
2924 fail:
2925 if (res)
2926 freeaddrinfo(res);
2927 return ret;
2930 PyDoc_STRVAR(getnameinfo_doc,
2931 "getnameinfo(sockaddr, flags) --> (host, port)\n\
2933 Get host and port for a sockaddr.");
2936 /* Python API to getting and setting the default timeout value. */
2938 static PyObject *
2939 socket_getdefaulttimeout(PyObject *self)
2941 if (defaulttimeout < 0.0) {
2942 Py_INCREF(Py_None);
2943 return Py_None;
2945 else
2946 return PyFloat_FromDouble(defaulttimeout);
2949 PyDoc_STRVAR(getdefaulttimeout_doc,
2950 "getdefaulttimeout() -> timeout\n\
2952 Returns the default timeout in floating seconds for new socket objects.\n\
2953 A value of None indicates that new socket objects have no timeout.\n\
2954 When the socket module is first imported, the default is None.");
2956 static PyObject *
2957 socket_setdefaulttimeout(PyObject *self, PyObject *arg)
2959 double timeout;
2961 if (arg == Py_None)
2962 timeout = -1.0;
2963 else {
2964 timeout = PyFloat_AsDouble(arg);
2965 if (timeout < 0.0) {
2966 if (!PyErr_Occurred())
2967 PyErr_SetString(PyExc_ValueError,
2968 "Timeout value out of range");
2969 return NULL;
2973 defaulttimeout = timeout;
2975 Py_INCREF(Py_None);
2976 return Py_None;
2979 PyDoc_STRVAR(setdefaulttimeout_doc,
2980 "setdefaulttimeout(timeout)\n\
2982 Set the default timeout in floating seconds for new socket objects.\n\
2983 A value of None indicates that new socket objects have no timeout.\n\
2984 When the socket module is first imported, the default is None.");
2987 /* List of functions exported by this module. */
2989 static PyMethodDef socket_methods[] = {
2990 {"gethostbyname", socket_gethostbyname,
2991 METH_VARARGS, gethostbyname_doc},
2992 {"gethostbyname_ex", socket_gethostbyname_ex,
2993 METH_VARARGS, ghbn_ex_doc},
2994 {"gethostbyaddr", socket_gethostbyaddr,
2995 METH_VARARGS, gethostbyaddr_doc},
2996 {"gethostname", socket_gethostname,
2997 METH_VARARGS, gethostname_doc},
2998 {"getservbyname", socket_getservbyname,
2999 METH_VARARGS, getservbyname_doc},
3000 {"getprotobyname", socket_getprotobyname,
3001 METH_VARARGS,getprotobyname_doc},
3002 #ifndef NO_DUP
3003 {"fromfd", socket_fromfd,
3004 METH_VARARGS, fromfd_doc},
3005 #endif
3006 {"ntohs", socket_ntohs,
3007 METH_VARARGS, ntohs_doc},
3008 {"ntohl", socket_ntohl,
3009 METH_O, ntohl_doc},
3010 {"htons", socket_htons,
3011 METH_VARARGS, htons_doc},
3012 {"htonl", socket_htonl,
3013 METH_O, htonl_doc},
3014 {"inet_aton", socket_inet_aton,
3015 METH_VARARGS, inet_aton_doc},
3016 {"inet_ntoa", socket_inet_ntoa,
3017 METH_VARARGS, inet_ntoa_doc},
3018 {"getaddrinfo", socket_getaddrinfo,
3019 METH_VARARGS, getaddrinfo_doc},
3020 {"getnameinfo", socket_getnameinfo,
3021 METH_VARARGS, getnameinfo_doc},
3022 {"getdefaulttimeout", (PyCFunction)socket_getdefaulttimeout,
3023 METH_NOARGS, getdefaulttimeout_doc},
3024 {"setdefaulttimeout", socket_setdefaulttimeout,
3025 METH_O, setdefaulttimeout_doc},
3026 {NULL, NULL} /* Sentinel */
3030 #ifdef RISCOS
3031 #define OS_INIT_DEFINED
3033 static int
3034 os_init(void)
3036 _kernel_swi_regs r;
3038 r.r[0] = 0;
3039 _kernel_swi(0x43380, &r, &r);
3040 taskwindow = r.r[0];
3042 return 0;
3045 #endif /* RISCOS */
3048 #ifdef MS_WINDOWS
3049 #define OS_INIT_DEFINED
3051 /* Additional initialization and cleanup for Windows */
3053 static void
3054 os_cleanup(void)
3056 WSACleanup();
3059 static int
3060 os_init(void)
3062 WSADATA WSAData;
3063 int ret;
3064 char buf[100];
3065 ret = WSAStartup(0x0101, &WSAData);
3066 switch (ret) {
3067 case 0: /* No error */
3068 atexit(os_cleanup);
3069 return 1; /* Success */
3070 case WSASYSNOTREADY:
3071 PyErr_SetString(PyExc_ImportError,
3072 "WSAStartup failed: network not ready");
3073 break;
3074 case WSAVERNOTSUPPORTED:
3075 case WSAEINVAL:
3076 PyErr_SetString(
3077 PyExc_ImportError,
3078 "WSAStartup failed: requested version not supported");
3079 break;
3080 default:
3081 PyOS_snprintf(buf, sizeof(buf),
3082 "WSAStartup failed: error code %d", ret);
3083 PyErr_SetString(PyExc_ImportError, buf);
3084 break;
3086 return 0; /* Failure */
3089 #endif /* MS_WINDOWS */
3092 #ifdef PYOS_OS2
3093 #define OS_INIT_DEFINED
3095 /* Additional initialization for OS/2 */
3097 static int
3098 os_init(void)
3100 #ifndef PYCC_GCC
3101 char reason[64];
3102 int rc = sock_init();
3104 if (rc == 0) {
3105 return 1; /* Success */
3108 PyOS_snprintf(reason, sizeof(reason),
3109 "OS/2 TCP/IP Error# %d", sock_errno());
3110 PyErr_SetString(PyExc_ImportError, reason);
3112 return 0; /* Failure */
3113 #else
3114 /* No need to initialise sockets with GCC/EMX */
3115 return 1; /* Success */
3116 #endif
3119 #endif /* PYOS_OS2 */
3122 #ifndef OS_INIT_DEFINED
3123 static int
3124 os_init(void)
3126 return 1; /* Success */
3128 #endif
3131 /* C API table - always add new things to the end for binary
3132 compatibility. */
3133 static
3134 PySocketModule_APIObject PySocketModuleAPI =
3136 &sock_type,
3140 /* Initialize the _socket module.
3142 This module is actually called "_socket", and there's a wrapper
3143 "socket.py" which implements some additional functionality. On some
3144 platforms (e.g. Windows and OS/2), socket.py also implements a
3145 wrapper for the socket type that provides missing functionality such
3146 as makefile(), dup() and fromfd(). The import of "_socket" may fail
3147 with an ImportError exception if os-specific initialization fails.
3148 On Windows, this does WINSOCK initialization. When WINSOCK is
3149 initialized succesfully, a call to WSACleanup() is scheduled to be
3150 made at exit time.
3153 PyDoc_STRVAR(socket_doc,
3154 "Implementation module for socket operations.\n\
3156 See the socket module for documentation.");
3158 PyMODINIT_FUNC
3159 init_socket(void)
3161 PyObject *m;
3163 if (!os_init())
3164 return;
3166 sock_type.ob_type = &PyType_Type;
3167 m = Py_InitModule3(PySocket_MODULE_NAME,
3168 socket_methods,
3169 socket_doc);
3171 socket_error = PyErr_NewException("socket.error", NULL, NULL);
3172 if (socket_error == NULL)
3173 return;
3174 Py_INCREF(socket_error);
3175 PyModule_AddObject(m, "error", socket_error);
3176 socket_herror = PyErr_NewException("socket.herror",
3177 socket_error, NULL);
3178 if (socket_herror == NULL)
3179 return;
3180 Py_INCREF(socket_herror);
3181 PyModule_AddObject(m, "herror", socket_herror);
3182 socket_gaierror = PyErr_NewException("socket.gaierror", socket_error,
3183 NULL);
3184 if (socket_gaierror == NULL)
3185 return;
3186 Py_INCREF(socket_gaierror);
3187 PyModule_AddObject(m, "gaierror", socket_gaierror);
3188 Py_INCREF((PyObject *)&sock_type);
3189 if (PyModule_AddObject(m, "SocketType",
3190 (PyObject *)&sock_type) != 0)
3191 return;
3192 Py_INCREF((PyObject *)&sock_type);
3193 if (PyModule_AddObject(m, "socket",
3194 (PyObject *)&sock_type) != 0)
3195 return;
3197 /* Export C API */
3198 if (PyModule_AddObject(m, PySocket_CAPI_NAME,
3199 PyCObject_FromVoidPtr((void *)&PySocketModuleAPI, NULL)
3200 ) != 0)
3201 return;
3203 /* Address families (we only support AF_INET and AF_UNIX) */
3204 #ifdef AF_UNSPEC
3205 PyModule_AddIntConstant(m, "AF_UNSPEC", AF_UNSPEC);
3206 #endif
3207 PyModule_AddIntConstant(m, "AF_INET", AF_INET);
3208 #ifdef AF_INET6
3209 PyModule_AddIntConstant(m, "AF_INET6", AF_INET6);
3210 #endif /* AF_INET6 */
3211 #if defined(AF_UNIX) && !defined(PYOS_OS2)
3212 PyModule_AddIntConstant(m, "AF_UNIX", AF_UNIX);
3213 #endif /* AF_UNIX */
3214 #ifdef AF_AX25
3215 /* Amateur Radio AX.25 */
3216 PyModule_AddIntConstant(m, "AF_AX25", AF_AX25);
3217 #endif
3218 #ifdef AF_IPX
3219 PyModule_AddIntConstant(m, "AF_IPX", AF_IPX); /* Novell IPX */
3220 #endif
3221 #ifdef AF_APPLETALK
3222 /* Appletalk DDP */
3223 PyModule_AddIntConstant(m, "AF_APPLETALK", AF_APPLETALK);
3224 #endif
3225 #ifdef AF_NETROM
3226 /* Amateur radio NetROM */
3227 PyModule_AddIntConstant(m, "AF_NETROM", AF_NETROM);
3228 #endif
3229 #ifdef AF_BRIDGE
3230 /* Multiprotocol bridge */
3231 PyModule_AddIntConstant(m, "AF_BRIDGE", AF_BRIDGE);
3232 #endif
3233 #ifdef AF_AAL5
3234 /* Reserved for Werner's ATM */
3235 PyModule_AddIntConstant(m, "AF_AAL5", AF_AAL5);
3236 #endif
3237 #ifdef AF_X25
3238 /* Reserved for X.25 project */
3239 PyModule_AddIntConstant(m, "AF_X25", AF_X25);
3240 #endif
3241 #ifdef AF_INET6
3242 PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); /* IP version 6 */
3243 #endif
3244 #ifdef AF_ROSE
3245 /* Amateur Radio X.25 PLP */
3246 PyModule_AddIntConstant(m, "AF_ROSE", AF_ROSE);
3247 #endif
3248 #ifdef HAVE_NETPACKET_PACKET_H
3249 PyModule_AddIntConstant(m, "AF_PACKET", AF_PACKET);
3250 PyModule_AddIntConstant(m, "PF_PACKET", PF_PACKET);
3251 PyModule_AddIntConstant(m, "PACKET_HOST", PACKET_HOST);
3252 PyModule_AddIntConstant(m, "PACKET_BROADCAST", PACKET_BROADCAST);
3253 PyModule_AddIntConstant(m, "PACKET_MULTICAST", PACKET_MULTICAST);
3254 PyModule_AddIntConstant(m, "PACKET_OTHERHOST", PACKET_OTHERHOST);
3255 PyModule_AddIntConstant(m, "PACKET_OUTGOING", PACKET_OUTGOING);
3256 PyModule_AddIntConstant(m, "PACKET_LOOPBACK", PACKET_LOOPBACK);
3257 PyModule_AddIntConstant(m, "PACKET_FASTROUTE", PACKET_FASTROUTE);
3258 #endif
3260 /* Socket types */
3261 PyModule_AddIntConstant(m, "SOCK_STREAM", SOCK_STREAM);
3262 PyModule_AddIntConstant(m, "SOCK_DGRAM", SOCK_DGRAM);
3263 #ifndef __BEOS__
3264 /* We have incomplete socket support. */
3265 PyModule_AddIntConstant(m, "SOCK_RAW", SOCK_RAW);
3266 PyModule_AddIntConstant(m, "SOCK_SEQPACKET", SOCK_SEQPACKET);
3267 #if defined(SOCK_RDM)
3268 PyModule_AddIntConstant(m, "SOCK_RDM", SOCK_RDM);
3269 #endif
3270 #endif
3272 #ifdef SO_DEBUG
3273 PyModule_AddIntConstant(m, "SO_DEBUG", SO_DEBUG);
3274 #endif
3275 #ifdef SO_ACCEPTCONN
3276 PyModule_AddIntConstant(m, "SO_ACCEPTCONN", SO_ACCEPTCONN);
3277 #endif
3278 #ifdef SO_REUSEADDR
3279 PyModule_AddIntConstant(m, "SO_REUSEADDR", SO_REUSEADDR);
3280 #endif
3281 #ifdef SO_KEEPALIVE
3282 PyModule_AddIntConstant(m, "SO_KEEPALIVE", SO_KEEPALIVE);
3283 #endif
3284 #ifdef SO_DONTROUTE
3285 PyModule_AddIntConstant(m, "SO_DONTROUTE", SO_DONTROUTE);
3286 #endif
3287 #ifdef SO_BROADCAST
3288 PyModule_AddIntConstant(m, "SO_BROADCAST", SO_BROADCAST);
3289 #endif
3290 #ifdef SO_USELOOPBACK
3291 PyModule_AddIntConstant(m, "SO_USELOOPBACK", SO_USELOOPBACK);
3292 #endif
3293 #ifdef SO_LINGER
3294 PyModule_AddIntConstant(m, "SO_LINGER", SO_LINGER);
3295 #endif
3296 #ifdef SO_OOBINLINE
3297 PyModule_AddIntConstant(m, "SO_OOBINLINE", SO_OOBINLINE);
3298 #endif
3299 #ifdef SO_REUSEPORT
3300 PyModule_AddIntConstant(m, "SO_REUSEPORT", SO_REUSEPORT);
3301 #endif
3302 #ifdef SO_SNDBUF
3303 PyModule_AddIntConstant(m, "SO_SNDBUF", SO_SNDBUF);
3304 #endif
3305 #ifdef SO_RCVBUF
3306 PyModule_AddIntConstant(m, "SO_RCVBUF", SO_RCVBUF);
3307 #endif
3308 #ifdef SO_SNDLOWAT
3309 PyModule_AddIntConstant(m, "SO_SNDLOWAT", SO_SNDLOWAT);
3310 #endif
3311 #ifdef SO_RCVLOWAT
3312 PyModule_AddIntConstant(m, "SO_RCVLOWAT", SO_RCVLOWAT);
3313 #endif
3314 #ifdef SO_SNDTIMEO
3315 PyModule_AddIntConstant(m, "SO_SNDTIMEO", SO_SNDTIMEO);
3316 #endif
3317 #ifdef SO_RCVTIMEO
3318 PyModule_AddIntConstant(m, "SO_RCVTIMEO", SO_RCVTIMEO);
3319 #endif
3320 #ifdef SO_ERROR
3321 PyModule_AddIntConstant(m, "SO_ERROR", SO_ERROR);
3322 #endif
3323 #ifdef SO_TYPE
3324 PyModule_AddIntConstant(m, "SO_TYPE", SO_TYPE);
3325 #endif
3327 /* Maximum number of connections for "listen" */
3328 #ifdef SOMAXCONN
3329 PyModule_AddIntConstant(m, "SOMAXCONN", SOMAXCONN);
3330 #else
3331 PyModule_AddIntConstant(m, "SOMAXCONN", 5); /* Common value */
3332 #endif
3334 /* Flags for send, recv */
3335 #ifdef MSG_OOB
3336 PyModule_AddIntConstant(m, "MSG_OOB", MSG_OOB);
3337 #endif
3338 #ifdef MSG_PEEK
3339 PyModule_AddIntConstant(m, "MSG_PEEK", MSG_PEEK);
3340 #endif
3341 #ifdef MSG_DONTROUTE
3342 PyModule_AddIntConstant(m, "MSG_DONTROUTE", MSG_DONTROUTE);
3343 #endif
3344 #ifdef MSG_DONTWAIT
3345 PyModule_AddIntConstant(m, "MSG_DONTWAIT", MSG_DONTWAIT);
3346 #endif
3347 #ifdef MSG_EOR
3348 PyModule_AddIntConstant(m, "MSG_EOR", MSG_EOR);
3349 #endif
3350 #ifdef MSG_TRUNC
3351 PyModule_AddIntConstant(m, "MSG_TRUNC", MSG_TRUNC);
3352 #endif
3353 #ifdef MSG_CTRUNC
3354 PyModule_AddIntConstant(m, "MSG_CTRUNC", MSG_CTRUNC);
3355 #endif
3356 #ifdef MSG_WAITALL
3357 PyModule_AddIntConstant(m, "MSG_WAITALL", MSG_WAITALL);
3358 #endif
3359 #ifdef MSG_BTAG
3360 PyModule_AddIntConstant(m, "MSG_BTAG", MSG_BTAG);
3361 #endif
3362 #ifdef MSG_ETAG
3363 PyModule_AddIntConstant(m, "MSG_ETAG", MSG_ETAG);
3364 #endif
3366 /* Protocol level and numbers, usable for [gs]etsockopt */
3367 #ifdef SOL_SOCKET
3368 PyModule_AddIntConstant(m, "SOL_SOCKET", SOL_SOCKET);
3369 #endif
3370 #ifdef SOL_IP
3371 PyModule_AddIntConstant(m, "SOL_IP", SOL_IP);
3372 #else
3373 PyModule_AddIntConstant(m, "SOL_IP", 0);
3374 #endif
3375 #ifdef SOL_IPX
3376 PyModule_AddIntConstant(m, "SOL_IPX", SOL_IPX);
3377 #endif
3378 #ifdef SOL_AX25
3379 PyModule_AddIntConstant(m, "SOL_AX25", SOL_AX25);
3380 #endif
3381 #ifdef SOL_ATALK
3382 PyModule_AddIntConstant(m, "SOL_ATALK", SOL_ATALK);
3383 #endif
3384 #ifdef SOL_NETROM
3385 PyModule_AddIntConstant(m, "SOL_NETROM", SOL_NETROM);
3386 #endif
3387 #ifdef SOL_ROSE
3388 PyModule_AddIntConstant(m, "SOL_ROSE", SOL_ROSE);
3389 #endif
3390 #ifdef SOL_TCP
3391 PyModule_AddIntConstant(m, "SOL_TCP", SOL_TCP);
3392 #else
3393 PyModule_AddIntConstant(m, "SOL_TCP", 6);
3394 #endif
3395 #ifdef SOL_UDP
3396 PyModule_AddIntConstant(m, "SOL_UDP", SOL_UDP);
3397 #else
3398 PyModule_AddIntConstant(m, "SOL_UDP", 17);
3399 #endif
3400 #ifdef IPPROTO_IP
3401 PyModule_AddIntConstant(m, "IPPROTO_IP", IPPROTO_IP);
3402 #else
3403 PyModule_AddIntConstant(m, "IPPROTO_IP", 0);
3404 #endif
3405 #ifdef IPPROTO_HOPOPTS
3406 PyModule_AddIntConstant(m, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS);
3407 #endif
3408 #ifdef IPPROTO_ICMP
3409 PyModule_AddIntConstant(m, "IPPROTO_ICMP", IPPROTO_ICMP);
3410 #else
3411 PyModule_AddIntConstant(m, "IPPROTO_ICMP", 1);
3412 #endif
3413 #ifdef IPPROTO_IGMP
3414 PyModule_AddIntConstant(m, "IPPROTO_IGMP", IPPROTO_IGMP);
3415 #endif
3416 #ifdef IPPROTO_GGP
3417 PyModule_AddIntConstant(m, "IPPROTO_GGP", IPPROTO_GGP);
3418 #endif
3419 #ifdef IPPROTO_IPV4
3420 PyModule_AddIntConstant(m, "IPPROTO_IPV4", IPPROTO_IPV4);
3421 #endif
3422 #ifdef IPPROTO_IPIP
3423 PyModule_AddIntConstant(m, "IPPROTO_IPIP", IPPROTO_IPIP);
3424 #endif
3425 #ifdef IPPROTO_TCP
3426 PyModule_AddIntConstant(m, "IPPROTO_TCP", IPPROTO_TCP);
3427 #else
3428 PyModule_AddIntConstant(m, "IPPROTO_TCP", 6);
3429 #endif
3430 #ifdef IPPROTO_EGP
3431 PyModule_AddIntConstant(m, "IPPROTO_EGP", IPPROTO_EGP);
3432 #endif
3433 #ifdef IPPROTO_PUP
3434 PyModule_AddIntConstant(m, "IPPROTO_PUP", IPPROTO_PUP);
3435 #endif
3436 #ifdef IPPROTO_UDP
3437 PyModule_AddIntConstant(m, "IPPROTO_UDP", IPPROTO_UDP);
3438 #else
3439 PyModule_AddIntConstant(m, "IPPROTO_UDP", 17);
3440 #endif
3441 #ifdef IPPROTO_IDP
3442 PyModule_AddIntConstant(m, "IPPROTO_IDP", IPPROTO_IDP);
3443 #endif
3444 #ifdef IPPROTO_HELLO
3445 PyModule_AddIntConstant(m, "IPPROTO_HELLO", IPPROTO_HELLO);
3446 #endif
3447 #ifdef IPPROTO_ND
3448 PyModule_AddIntConstant(m, "IPPROTO_ND", IPPROTO_ND);
3449 #endif
3450 #ifdef IPPROTO_TP
3451 PyModule_AddIntConstant(m, "IPPROTO_TP", IPPROTO_TP);
3452 #endif
3453 #ifdef IPPROTO_IPV6
3454 PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
3455 #endif
3456 #ifdef IPPROTO_ROUTING
3457 PyModule_AddIntConstant(m, "IPPROTO_ROUTING", IPPROTO_ROUTING);
3458 #endif
3459 #ifdef IPPROTO_FRAGMENT
3460 PyModule_AddIntConstant(m, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT);
3461 #endif
3462 #ifdef IPPROTO_RSVP
3463 PyModule_AddIntConstant(m, "IPPROTO_RSVP", IPPROTO_RSVP);
3464 #endif
3465 #ifdef IPPROTO_GRE
3466 PyModule_AddIntConstant(m, "IPPROTO_GRE", IPPROTO_GRE);
3467 #endif
3468 #ifdef IPPROTO_ESP
3469 PyModule_AddIntConstant(m, "IPPROTO_ESP", IPPROTO_ESP);
3470 #endif
3471 #ifdef IPPROTO_AH
3472 PyModule_AddIntConstant(m, "IPPROTO_AH", IPPROTO_AH);
3473 #endif
3474 #ifdef IPPROTO_MOBILE
3475 PyModule_AddIntConstant(m, "IPPROTO_MOBILE", IPPROTO_MOBILE);
3476 #endif
3477 #ifdef IPPROTO_ICMPV6
3478 PyModule_AddIntConstant(m, "IPPROTO_ICMPV6", IPPROTO_ICMPV6);
3479 #endif
3480 #ifdef IPPROTO_NONE
3481 PyModule_AddIntConstant(m, "IPPROTO_NONE", IPPROTO_NONE);
3482 #endif
3483 #ifdef IPPROTO_DSTOPTS
3484 PyModule_AddIntConstant(m, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS);
3485 #endif
3486 #ifdef IPPROTO_XTP
3487 PyModule_AddIntConstant(m, "IPPROTO_XTP", IPPROTO_XTP);
3488 #endif
3489 #ifdef IPPROTO_EON
3490 PyModule_AddIntConstant(m, "IPPROTO_EON", IPPROTO_EON);
3491 #endif
3492 #ifdef IPPROTO_PIM
3493 PyModule_AddIntConstant(m, "IPPROTO_PIM", IPPROTO_PIM);
3494 #endif
3495 #ifdef IPPROTO_IPCOMP
3496 PyModule_AddIntConstant(m, "IPPROTO_IPCOMP", IPPROTO_IPCOMP);
3497 #endif
3498 #ifdef IPPROTO_VRRP
3499 PyModule_AddIntConstant(m, "IPPROTO_VRRP", IPPROTO_VRRP);
3500 #endif
3501 #ifdef IPPROTO_BIP
3502 PyModule_AddIntConstant(m, "IPPROTO_BIP", IPPROTO_BIP);
3503 #endif
3504 /**/
3505 #ifdef IPPROTO_RAW
3506 PyModule_AddIntConstant(m, "IPPROTO_RAW", IPPROTO_RAW);
3507 #else
3508 PyModule_AddIntConstant(m, "IPPROTO_RAW", 255);
3509 #endif
3510 #ifdef IPPROTO_MAX
3511 PyModule_AddIntConstant(m, "IPPROTO_MAX", IPPROTO_MAX);
3512 #endif
3514 /* Some port configuration */
3515 #ifdef IPPORT_RESERVED
3516 PyModule_AddIntConstant(m, "IPPORT_RESERVED", IPPORT_RESERVED);
3517 #else
3518 PyModule_AddIntConstant(m, "IPPORT_RESERVED", 1024);
3519 #endif
3520 #ifdef IPPORT_USERRESERVED
3521 PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", IPPORT_USERRESERVED);
3522 #else
3523 PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", 5000);
3524 #endif
3526 /* Some reserved IP v.4 addresses */
3527 #ifdef INADDR_ANY
3528 PyModule_AddIntConstant(m, "INADDR_ANY", INADDR_ANY);
3529 #else
3530 PyModule_AddIntConstant(m, "INADDR_ANY", 0x00000000);
3531 #endif
3532 #ifdef INADDR_BROADCAST
3533 PyModule_AddIntConstant(m, "INADDR_BROADCAST", INADDR_BROADCAST);
3534 #else
3535 PyModule_AddIntConstant(m, "INADDR_BROADCAST", 0xffffffff);
3536 #endif
3537 #ifdef INADDR_LOOPBACK
3538 PyModule_AddIntConstant(m, "INADDR_LOOPBACK", INADDR_LOOPBACK);
3539 #else
3540 PyModule_AddIntConstant(m, "INADDR_LOOPBACK", 0x7F000001);
3541 #endif
3542 #ifdef INADDR_UNSPEC_GROUP
3543 PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
3544 #else
3545 PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", 0xe0000000);
3546 #endif
3547 #ifdef INADDR_ALLHOSTS_GROUP
3548 PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP",
3549 INADDR_ALLHOSTS_GROUP);
3550 #else
3551 PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
3552 #endif
3553 #ifdef INADDR_MAX_LOCAL_GROUP
3554 PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP",
3555 INADDR_MAX_LOCAL_GROUP);
3556 #else
3557 PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
3558 #endif
3559 #ifdef INADDR_NONE
3560 PyModule_AddIntConstant(m, "INADDR_NONE", INADDR_NONE);
3561 #else
3562 PyModule_AddIntConstant(m, "INADDR_NONE", 0xffffffff);
3563 #endif
3565 /* IPv4 [gs]etsockopt options */
3566 #ifdef IP_OPTIONS
3567 PyModule_AddIntConstant(m, "IP_OPTIONS", IP_OPTIONS);
3568 #endif
3569 #ifdef IP_HDRINCL
3570 PyModule_AddIntConstant(m, "IP_HDRINCL", IP_HDRINCL);
3571 #endif
3572 #ifdef IP_TOS
3573 PyModule_AddIntConstant(m, "IP_TOS", IP_TOS);
3574 #endif
3575 #ifdef IP_TTL
3576 PyModule_AddIntConstant(m, "IP_TTL", IP_TTL);
3577 #endif
3578 #ifdef IP_RECVOPTS
3579 PyModule_AddIntConstant(m, "IP_RECVOPTS", IP_RECVOPTS);
3580 #endif
3581 #ifdef IP_RECVRETOPTS
3582 PyModule_AddIntConstant(m, "IP_RECVRETOPTS", IP_RECVRETOPTS);
3583 #endif
3584 #ifdef IP_RECVDSTADDR
3585 PyModule_AddIntConstant(m, "IP_RECVDSTADDR", IP_RECVDSTADDR);
3586 #endif
3587 #ifdef IP_RETOPTS
3588 PyModule_AddIntConstant(m, "IP_RETOPTS", IP_RETOPTS);
3589 #endif
3590 #ifdef IP_MULTICAST_IF
3591 PyModule_AddIntConstant(m, "IP_MULTICAST_IF", IP_MULTICAST_IF);
3592 #endif
3593 #ifdef IP_MULTICAST_TTL
3594 PyModule_AddIntConstant(m, "IP_MULTICAST_TTL", IP_MULTICAST_TTL);
3595 #endif
3596 #ifdef IP_MULTICAST_LOOP
3597 PyModule_AddIntConstant(m, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
3598 #endif
3599 #ifdef IP_ADD_MEMBERSHIP
3600 PyModule_AddIntConstant(m, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
3601 #endif
3602 #ifdef IP_DROP_MEMBERSHIP
3603 PyModule_AddIntConstant(m, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
3604 #endif
3605 #ifdef IP_DEFAULT_MULTICAST_TTL
3606 PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_TTL",
3607 IP_DEFAULT_MULTICAST_TTL);
3608 #endif
3609 #ifdef IP_DEFAULT_MULTICAST_LOOP
3610 PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_LOOP",
3611 IP_DEFAULT_MULTICAST_LOOP);
3612 #endif
3613 #ifdef IP_MAX_MEMBERSHIPS
3614 PyModule_AddIntConstant(m, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS);
3615 #endif
3617 /* IPv6 [gs]etsockopt options, defined in RFC2553 */
3618 #ifdef IPV6_JOIN_GROUP
3619 PyModule_AddIntConstant(m, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP);
3620 #endif
3621 #ifdef IPV6_LEAVE_GROUP
3622 PyModule_AddIntConstant(m, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP);
3623 #endif
3624 #ifdef IPV6_MULTICAST_HOPS
3625 PyModule_AddIntConstant(m, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS);
3626 #endif
3627 #ifdef IPV6_MULTICAST_IF
3628 PyModule_AddIntConstant(m, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF);
3629 #endif
3630 #ifdef IPV6_MULTICAST_LOOP
3631 PyModule_AddIntConstant(m, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP);
3632 #endif
3633 #ifdef IPV6_UNICAST_HOPS
3634 PyModule_AddIntConstant(m, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS);
3635 #endif
3637 /* TCP options */
3638 #ifdef TCP_NODELAY
3639 PyModule_AddIntConstant(m, "TCP_NODELAY", TCP_NODELAY);
3640 #endif
3641 #ifdef TCP_MAXSEG
3642 PyModule_AddIntConstant(m, "TCP_MAXSEG", TCP_MAXSEG);
3643 #endif
3644 #ifdef TCP_CORK
3645 PyModule_AddIntConstant(m, "TCP_CORK", TCP_CORK);
3646 #endif
3647 #ifdef TCP_KEEPIDLE
3648 PyModule_AddIntConstant(m, "TCP_KEEPIDLE", TCP_KEEPIDLE);
3649 #endif
3650 #ifdef TCP_KEEPINTVL
3651 PyModule_AddIntConstant(m, "TCP_KEEPINTVL", TCP_KEEPINTVL);
3652 #endif
3653 #ifdef TCP_KEEPCNT
3654 PyModule_AddIntConstant(m, "TCP_KEEPCNT", TCP_KEEPCNT);
3655 #endif
3656 #ifdef TCP_SYNCNT
3657 PyModule_AddIntConstant(m, "TCP_SYNCNT", TCP_SYNCNT);
3658 #endif
3659 #ifdef TCP_LINGER2
3660 PyModule_AddIntConstant(m, "TCP_LINGER2", TCP_LINGER2);
3661 #endif
3662 #ifdef TCP_DEFER_ACCEPT
3663 PyModule_AddIntConstant(m, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT);
3664 #endif
3665 #ifdef TCP_WINDOW_CLAMP
3666 PyModule_AddIntConstant(m, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP);
3667 #endif
3668 #ifdef TCP_INFO
3669 PyModule_AddIntConstant(m, "TCP_INFO", TCP_INFO);
3670 #endif
3671 #ifdef TCP_QUICKACK
3672 PyModule_AddIntConstant(m, "TCP_QUICKACK", TCP_QUICKACK);
3673 #endif
3676 /* IPX options */
3677 #ifdef IPX_TYPE
3678 PyModule_AddIntConstant(m, "IPX_TYPE", IPX_TYPE);
3679 #endif
3681 /* get{addr,name}info parameters */
3682 #ifdef EAI_ADDRFAMILY
3683 PyModule_AddIntConstant(m, "EAI_ADDRFAMILY", EAI_ADDRFAMILY);
3684 #endif
3685 #ifdef EAI_AGAIN
3686 PyModule_AddIntConstant(m, "EAI_AGAIN", EAI_AGAIN);
3687 #endif
3688 #ifdef EAI_BADFLAGS
3689 PyModule_AddIntConstant(m, "EAI_BADFLAGS", EAI_BADFLAGS);
3690 #endif
3691 #ifdef EAI_FAIL
3692 PyModule_AddIntConstant(m, "EAI_FAIL", EAI_FAIL);
3693 #endif
3694 #ifdef EAI_FAMILY
3695 PyModule_AddIntConstant(m, "EAI_FAMILY", EAI_FAMILY);
3696 #endif
3697 #ifdef EAI_MEMORY
3698 PyModule_AddIntConstant(m, "EAI_MEMORY", EAI_MEMORY);
3699 #endif
3700 #ifdef EAI_NODATA
3701 PyModule_AddIntConstant(m, "EAI_NODATA", EAI_NODATA);
3702 #endif
3703 #ifdef EAI_NONAME
3704 PyModule_AddIntConstant(m, "EAI_NONAME", EAI_NONAME);
3705 #endif
3706 #ifdef EAI_SERVICE
3707 PyModule_AddIntConstant(m, "EAI_SERVICE", EAI_SERVICE);
3708 #endif
3709 #ifdef EAI_SOCKTYPE
3710 PyModule_AddIntConstant(m, "EAI_SOCKTYPE", EAI_SOCKTYPE);
3711 #endif
3712 #ifdef EAI_SYSTEM
3713 PyModule_AddIntConstant(m, "EAI_SYSTEM", EAI_SYSTEM);
3714 #endif
3715 #ifdef EAI_BADHINTS
3716 PyModule_AddIntConstant(m, "EAI_BADHINTS", EAI_BADHINTS);
3717 #endif
3718 #ifdef EAI_PROTOCOL
3719 PyModule_AddIntConstant(m, "EAI_PROTOCOL", EAI_PROTOCOL);
3720 #endif
3721 #ifdef EAI_MAX
3722 PyModule_AddIntConstant(m, "EAI_MAX", EAI_MAX);
3723 #endif
3724 #ifdef AI_PASSIVE
3725 PyModule_AddIntConstant(m, "AI_PASSIVE", AI_PASSIVE);
3726 #endif
3727 #ifdef AI_CANONNAME
3728 PyModule_AddIntConstant(m, "AI_CANONNAME", AI_CANONNAME);
3729 #endif
3730 #ifdef AI_NUMERICHOST
3731 PyModule_AddIntConstant(m, "AI_NUMERICHOST", AI_NUMERICHOST);
3732 #endif
3733 #ifdef AI_MASK
3734 PyModule_AddIntConstant(m, "AI_MASK", AI_MASK);
3735 #endif
3736 #ifdef AI_ALL
3737 PyModule_AddIntConstant(m, "AI_ALL", AI_ALL);
3738 #endif
3739 #ifdef AI_V4MAPPED_CFG
3740 PyModule_AddIntConstant(m, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG);
3741 #endif
3742 #ifdef AI_ADDRCONFIG
3743 PyModule_AddIntConstant(m, "AI_ADDRCONFIG", AI_ADDRCONFIG);
3744 #endif
3745 #ifdef AI_V4MAPPED
3746 PyModule_AddIntConstant(m, "AI_V4MAPPED", AI_V4MAPPED);
3747 #endif
3748 #ifdef AI_DEFAULT
3749 PyModule_AddIntConstant(m, "AI_DEFAULT", AI_DEFAULT);
3750 #endif
3751 #ifdef NI_MAXHOST
3752 PyModule_AddIntConstant(m, "NI_MAXHOST", NI_MAXHOST);
3753 #endif
3754 #ifdef NI_MAXSERV
3755 PyModule_AddIntConstant(m, "NI_MAXSERV", NI_MAXSERV);
3756 #endif
3757 #ifdef NI_NOFQDN
3758 PyModule_AddIntConstant(m, "NI_NOFQDN", NI_NOFQDN);
3759 #endif
3760 #ifdef NI_NUMERICHOST
3761 PyModule_AddIntConstant(m, "NI_NUMERICHOST", NI_NUMERICHOST);
3762 #endif
3763 #ifdef NI_NAMEREQD
3764 PyModule_AddIntConstant(m, "NI_NAMEREQD", NI_NAMEREQD);
3765 #endif
3766 #ifdef NI_NUMERICSERV
3767 PyModule_AddIntConstant(m, "NI_NUMERICSERV", NI_NUMERICSERV);
3768 #endif
3769 #ifdef NI_DGRAM
3770 PyModule_AddIntConstant(m, "NI_DGRAM", NI_DGRAM);
3771 #endif
3773 /* Initialize gethostbyname lock */
3774 #ifdef USE_GETHOSTBYNAME_LOCK
3775 gethostbyname_lock = PyThread_allocate_lock();
3776 #endif
3780 #ifndef HAVE_INET_PTON
3782 /* Simplistic emulation code for inet_pton that only works for IPv4 */
3785 inet_pton(int af, const char *src, void *dst)
3787 if (af == AF_INET) {
3788 long packed_addr;
3789 packed_addr = inet_addr(src);
3790 if (packed_addr == INADDR_NONE)
3791 return 0;
3792 memcpy(dst, &packed_addr, 4);
3793 return 1;
3795 /* Should set errno to EAFNOSUPPORT */
3796 return -1;
3799 const char *
3800 inet_ntop(int af, const void *src, char *dst, socklen_t size)
3802 if (af == AF_INET) {
3803 struct in_addr packed_addr;
3804 if (size < 16)
3805 /* Should set errno to ENOSPC. */
3806 return NULL;
3807 memcpy(&packed_addr, src, sizeof(packed_addr));
3808 return strncpy(dst, inet_ntoa(packed_addr), size);
3810 /* Should set errno to EAFNOSUPPORT */
3811 return NULL;
3814 #endif