Don't abbreviate ABS, use long name ABSOLUTE.
[python.git] / Modules / socketmodule.c
blobaf46921731740899f5c82fb6b15ad6abf0327eb3
1 /* Socket module */
3 /*
5 This module provides an interface to Berkeley socket IPC.
7 Limitations:
9 - Only AF_INET, AF_INET6 and AF_UNIX address families are supported in a
10 portable manner, though AF_PACKET and AF_NETLINK are supported under Linux.
11 - No read/write operations (use sendall/recv or makefile instead).
12 - Additional restrictions apply on some non-Unix platforms (compensated
13 for by socket.py).
15 Module interface:
17 - socket.error: exception raised for socket specific errors
18 - socket.gaierror: exception raised for getaddrinfo/getnameinfo errors,
19 a subclass of socket.error
20 - socket.herror: exception raised for gethostby* errors,
21 a subclass of socket.error
22 - socket.fromfd(fd, family, type[, proto]) --> new socket object (created
23 from an existing file descriptor)
24 - socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')
25 - socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])
26 - socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com')
27 - socket.getprotobyname(protocolname) --> protocol number
28 - socket.getservbyname(servicename[, protocolname]) --> port number
29 - socket.getservbyport(portnumber[, protocolname]) --> service name
30 - socket.socket([family[, type [, proto]]]) --> new socket object
31 - socket.socketpair([family[, type [, proto]]]) --> (socket, socket)
32 - socket.ntohs(16 bit value) --> new int object
33 - socket.ntohl(32 bit value) --> new int object
34 - socket.htons(16 bit value) --> new int object
35 - socket.htonl(32 bit value) --> new int object
36 - socket.getaddrinfo(host, port [, family, socktype, proto, flags])
37 --> List of (family, socktype, proto, canonname, sockaddr)
38 - socket.getnameinfo(sockaddr, flags) --> (host, port)
39 - socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
40 - socket.has_ipv6: boolean value indicating if IPv6 is supported
41 - socket.inet_aton(IP address) -> 32-bit packed IP representation
42 - socket.inet_ntoa(packed IP) -> IP address string
43 - socket.getdefaulttimeout() -> None | float
44 - socket.setdefaulttimeout(None | float)
45 - an Internet socket address is a pair (hostname, port)
46 where hostname can be anything recognized by gethostbyname()
47 (including the dd.dd.dd.dd notation) and port is in host byte order
48 - where a hostname is returned, the dd.dd.dd.dd notation is used
49 - a UNIX domain socket address is a string specifying the pathname
50 - an AF_PACKET socket address is a tuple containing a string
51 specifying the ethernet interface and an integer specifying
52 the Ethernet protocol number to be received. For example:
53 ("eth0",0x1234). Optional 3rd,4th,5th elements in the tuple
54 specify packet-type and ha-type/addr.
56 Local naming conventions:
58 - names starting with sock_ are socket object methods
59 - names starting with socket_ are module-level functions
60 - names starting with PySocket are exported through socketmodule.h
64 #include "Python.h"
65 #include "structmember.h"
67 #undef MAX
68 #define MAX(x, y) ((x) < (y) ? (y) : (x))
70 /* Socket object documentation */
71 PyDoc_STRVAR(sock_doc,
72 "socket([family[, type[, proto]]]) -> socket object\n\
73 \n\
74 Open a socket of the given type. The family argument specifies the\n\
75 address family; it defaults to AF_INET. The type argument specifies\n\
76 whether this is a stream (SOCK_STREAM, this is the default)\n\
77 or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0,\n\
78 specifying the default protocol. Keyword arguments are accepted.\n\
79 \n\
80 A socket object represents one endpoint of a network connection.\n\
81 \n\
82 Methods of socket objects (keyword arguments not allowed):\n\
83 \n\
84 accept() -- accept a connection, returning new socket and client address\n\
85 bind(addr) -- bind the socket to a local address\n\
86 close() -- close the socket\n\
87 connect(addr) -- connect the socket to a remote address\n\
88 connect_ex(addr) -- connect, return an error code instead of an exception\n\
89 dup() -- return a new socket object identical to the current one [*]\n\
90 fileno() -- return underlying file descriptor\n\
91 getpeername() -- return remote address [*]\n\
92 getsockname() -- return local address\n\
93 getsockopt(level, optname[, buflen]) -- get socket options\n\
94 gettimeout() -- return timeout or None\n\
95 listen(n) -- start listening for incoming connections\n\
96 makefile([mode, [bufsize]]) -- return a file object for the socket [*]\n\
97 recv(buflen[, flags]) -- receive data\n\
98 recvfrom(buflen[, flags]) -- receive data and sender's address\n\
99 sendall(data[, flags]) -- send all data\n\
100 send(data[, flags]) -- send data, may not send all of it\n\
101 sendto(data[, flags], addr) -- send data to a given address\n\
102 setblocking(0 | 1) -- set or clear the blocking I/O flag\n\
103 setsockopt(level, optname, value) -- set socket options\n\
104 settimeout(None | float) -- set or clear the timeout\n\
105 shutdown(how) -- shut down traffic in one or both directions\n\
107 [*] not available on all platforms!");
109 /* XXX This is a terrible mess of platform-dependent preprocessor hacks.
110 I hope some day someone can clean this up please... */
112 /* Hacks for gethostbyname_r(). On some non-Linux platforms, the configure
113 script doesn't get this right, so we hardcode some platform checks below.
114 On the other hand, not all Linux versions agree, so there the settings
115 computed by the configure script are needed! */
117 #ifndef linux
118 # undef HAVE_GETHOSTBYNAME_R_3_ARG
119 # undef HAVE_GETHOSTBYNAME_R_5_ARG
120 # undef HAVE_GETHOSTBYNAME_R_6_ARG
121 #endif
123 #ifndef WITH_THREAD
124 # undef HAVE_GETHOSTBYNAME_R
125 #endif
127 #ifdef HAVE_GETHOSTBYNAME_R
128 # if defined(_AIX) || defined(__osf__)
129 # define HAVE_GETHOSTBYNAME_R_3_ARG
130 # elif defined(__sun) || defined(__sgi)
131 # define HAVE_GETHOSTBYNAME_R_5_ARG
132 # elif defined(linux)
133 /* Rely on the configure script */
134 # else
135 # undef HAVE_GETHOSTBYNAME_R
136 # endif
137 #endif
139 #if !defined(HAVE_GETHOSTBYNAME_R) && defined(WITH_THREAD) && \
140 !defined(MS_WINDOWS)
141 # define USE_GETHOSTBYNAME_LOCK
142 #endif
144 /* To use __FreeBSD_version */
145 #ifdef HAVE_SYS_PARAM_H
146 #include <sys/param.h>
147 #endif
148 /* On systems on which getaddrinfo() is believed to not be thread-safe,
149 (this includes the getaddrinfo emulation) protect access with a lock. */
150 #if defined(WITH_THREAD) && (defined(__APPLE__) || \
151 (defined(__FreeBSD__) && __FreeBSD_version+0 < 503000) || \
152 defined(__OpenBSD__) || defined(__NetBSD__) || !defined(HAVE_GETADDRINFO))
153 #define USE_GETADDRINFO_LOCK
154 #endif
156 #ifdef USE_GETADDRINFO_LOCK
157 #define ACQUIRE_GETADDRINFO_LOCK PyThread_acquire_lock(netdb_lock, 1);
158 #define RELEASE_GETADDRINFO_LOCK PyThread_release_lock(netdb_lock);
159 #else
160 #define ACQUIRE_GETADDRINFO_LOCK
161 #define RELEASE_GETADDRINFO_LOCK
162 #endif
164 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
165 # include "pythread.h"
166 #endif
168 #if defined(PYCC_VACPP)
169 # include <types.h>
170 # include <io.h>
171 # include <sys/ioctl.h>
172 # include <utils.h>
173 # include <ctype.h>
174 #endif
176 #if defined(__VMS)
177 #if ! defined(_SOCKADDR_LEN)
178 # ifdef getaddrinfo
179 # undef getaddrinfo
180 # endif
181 # include "TCPIP_IOCTL_ROUTINE"
182 #else
183 # include <ioctl.h>
184 #endif
185 #endif
187 #if defined(PYOS_OS2)
188 # define INCL_DOS
189 # define INCL_DOSERRORS
190 # define INCL_NOPMAPI
191 # include <os2.h>
192 #endif
194 #if defined(__sgi) && _COMPILER_VERSION>700 && !_SGIAPI
195 /* make sure that the reentrant (gethostbyaddr_r etc)
196 functions are declared correctly if compiling with
197 MIPSPro 7.x in ANSI C mode (default) */
199 /* XXX Using _SGIAPI is the wrong thing,
200 but I don't know what the right thing is. */
201 #undef _SGIAPI /* to avoid warning */
202 #define _SGIAPI 1
204 #undef _XOPEN_SOURCE
205 #include <sys/socket.h>
206 #include <sys/types.h>
207 #include <netinet/in.h>
208 #ifdef _SS_ALIGNSIZE
209 #define HAVE_GETADDRINFO 1
210 #define HAVE_GETNAMEINFO 1
211 #endif
213 #define HAVE_INET_PTON
214 #include <netdb.h>
215 #endif
217 /* Irix 6.5 fails to define this variable at all. This is needed
218 for both GCC and SGI's compiler. I'd say that the SGI headers
219 are just busted. Same thing for Solaris. */
220 #if (defined(__sgi) || defined(sun)) && !defined(INET_ADDRSTRLEN)
221 #define INET_ADDRSTRLEN 16
222 #endif
224 /* Generic includes */
225 #include <sys/types.h>
227 /* Generic socket object definitions and includes */
228 #define PySocket_BUILDING_SOCKET
229 #include "socketmodule.h"
231 /* Addressing includes */
233 #ifndef MS_WINDOWS
235 /* Non-MS WINDOWS includes */
236 # include <netdb.h>
238 /* Headers needed for inet_ntoa() and inet_addr() */
239 # ifdef __BEOS__
240 # include <net/netdb.h>
241 # elif defined(PYOS_OS2) && defined(PYCC_VACPP)
242 # include <netdb.h>
243 typedef size_t socklen_t;
244 # else
245 # include <arpa/inet.h>
246 # endif
248 # ifndef RISCOS
249 # include <fcntl.h>
250 # else
251 # include <sys/ioctl.h>
252 # include <socklib.h>
253 # define NO_DUP
254 int h_errno; /* not used */
255 # define INET_ADDRSTRLEN 16
256 # endif
258 #else
260 /* MS_WINDOWS includes */
261 # include <fcntl.h>
263 #endif
265 #include <stddef.h>
267 #ifndef offsetof
268 # define offsetof(type, member) ((size_t)(&((type *)0)->member))
269 #endif
271 #ifndef O_NONBLOCK
272 # define O_NONBLOCK O_NDELAY
273 #endif
275 /* include Python's addrinfo.h unless it causes trouble */
276 #if defined(__sgi) && _COMPILER_VERSION>700 && defined(_SS_ALIGNSIZE)
277 /* Do not include addinfo.h on some newer IRIX versions.
278 * _SS_ALIGNSIZE is defined in sys/socket.h by 6.5.21,
279 * for example, but not by 6.5.10.
281 #elif defined(_MSC_VER) && _MSC_VER>1200
282 /* Do not include addrinfo.h for MSVC7 or greater. 'addrinfo' and
283 * EAI_* constants are defined in (the already included) ws2tcpip.h.
285 #else
286 # include "addrinfo.h"
287 #endif
289 #ifndef HAVE_INET_PTON
290 int inet_pton(int af, const char *src, void *dst);
291 const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
292 #endif
294 #ifdef __APPLE__
295 /* On OS X, getaddrinfo returns no error indication of lookup
296 failure, so we must use the emulation instead of the libinfo
297 implementation. Unfortunately, performing an autoconf test
298 for this bug would require DNS access for the machine performing
299 the configuration, which is not acceptable. Therefore, we
300 determine the bug just by checking for __APPLE__. If this bug
301 gets ever fixed, perhaps checking for sys/version.h would be
302 appropriate, which is 10/0 on the system with the bug. */
303 #ifndef HAVE_GETNAMEINFO
304 /* This bug seems to be fixed in Jaguar. Ths easiest way I could
305 Find to check for Jaguar is that it has getnameinfo(), which
306 older releases don't have */
307 #undef HAVE_GETADDRINFO
308 #endif
309 #endif
311 /* I know this is a bad practice, but it is the easiest... */
312 #if !defined(HAVE_GETADDRINFO)
313 /* avoid clashes with the C library definition of the symbol. */
314 #define getaddrinfo fake_getaddrinfo
315 #define gai_strerror fake_gai_strerror
316 #define freeaddrinfo fake_freeaddrinfo
317 #include "getaddrinfo.c"
318 #endif
319 #if !defined(HAVE_GETNAMEINFO)
320 #define getnameinfo fake_getnameinfo
321 #include "getnameinfo.c"
322 #endif
324 #if defined(MS_WINDOWS) || defined(__BEOS__)
325 /* BeOS suffers from the same socket dichotomy as Win32... - [cjh] */
326 /* seem to be a few differences in the API */
327 #define SOCKETCLOSE closesocket
328 #define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */
329 #endif
331 #ifdef MS_WIN32
332 #define EAFNOSUPPORT WSAEAFNOSUPPORT
333 #define snprintf _snprintf
334 #endif
336 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
337 #define SOCKETCLOSE soclose
338 #define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
339 #endif
341 #ifndef SOCKETCLOSE
342 #define SOCKETCLOSE close
343 #endif
345 #ifdef __VMS
346 /* TCP/IP Services for VMS uses a maximum send/revc buffer length of 65535 */
347 #define SEGMENT_SIZE 65535
348 #endif
350 #if defined(HAVE_BLUETOOTH_H) || defined(HAVE_BLUETOOTH_BLUETOOTH_H)
351 #define USE_BLUETOOTH 1
352 #if defined(__FreeBSD__)
353 #define BTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP
354 #define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM
355 #define sockaddr_l2 sockaddr_l2cap
356 #define sockaddr_rc sockaddr_rfcomm
357 #define _BT_SOCKADDR_MEMB(s, proto) &((s)->sock_addr)
358 #define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb)
359 #define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)
360 #else
361 #define _BT_SOCKADDR_MEMB(s, proto) (&((s)->sock_addr).bt_##proto)
362 #define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb)
363 #define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb)
364 #define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)
365 #endif
366 #endif
369 * Constants for getnameinfo()
371 #if !defined(NI_MAXHOST)
372 #define NI_MAXHOST 1025
373 #endif
374 #if !defined(NI_MAXSERV)
375 #define NI_MAXSERV 32
376 #endif
378 /* XXX There's a problem here: *static* functions are not supposed to have
379 a Py prefix (or use CapitalizedWords). Later... */
381 /* Global variable holding the exception type for errors detected
382 by this module (but not argument type or memory errors, etc.). */
383 static PyObject *socket_error;
384 static PyObject *socket_herror;
385 static PyObject *socket_gaierror;
386 static PyObject *socket_timeout;
388 #ifdef RISCOS
389 /* Global variable which is !=0 if Python is running in a RISC OS taskwindow */
390 static int taskwindow;
391 #endif
393 /* A forward reference to the socket type object.
394 The sock_type variable contains pointers to various functions,
395 some of which call new_sockobject(), which uses sock_type, so
396 there has to be a circular reference. */
397 static PyTypeObject sock_type;
399 /* Can we call select() with this socket without a buffer overrun? */
400 #ifdef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
401 /* Platform can select file descriptors beyond FD_SETSIZE */
402 #define IS_SELECTABLE(s) 1
403 #else
404 /* POSIX says selecting file descriptors beyond FD_SETSIZE
405 has undefined behaviour. */
406 #define IS_SELECTABLE(s) ((s)->sock_fd < FD_SETSIZE)
407 #endif
409 static PyObject*
410 select_error(void)
412 PyErr_SetString(socket_error, "unable to select on socket");
413 return NULL;
416 /* Convenience function to raise an error according to errno
417 and return a NULL pointer from a function. */
419 static PyObject *
420 set_error(void)
422 #ifdef MS_WINDOWS
423 int err_no = WSAGetLastError();
424 static struct {
425 int no;
426 const char *msg;
427 } *msgp, msgs[] = {
428 {WSAEINTR, "Interrupted system call"},
429 {WSAEBADF, "Bad file descriptor"},
430 {WSAEACCES, "Permission denied"},
431 {WSAEFAULT, "Bad address"},
432 {WSAEINVAL, "Invalid argument"},
433 {WSAEMFILE, "Too many open files"},
434 {WSAEWOULDBLOCK,
435 "The socket operation could not complete "
436 "without blocking"},
437 {WSAEINPROGRESS, "Operation now in progress"},
438 {WSAEALREADY, "Operation already in progress"},
439 {WSAENOTSOCK, "Socket operation on non-socket"},
440 {WSAEDESTADDRREQ, "Destination address required"},
441 {WSAEMSGSIZE, "Message too long"},
442 {WSAEPROTOTYPE, "Protocol wrong type for socket"},
443 {WSAENOPROTOOPT, "Protocol not available"},
444 {WSAEPROTONOSUPPORT, "Protocol not supported"},
445 {WSAESOCKTNOSUPPORT, "Socket type not supported"},
446 {WSAEOPNOTSUPP, "Operation not supported"},
447 {WSAEPFNOSUPPORT, "Protocol family not supported"},
448 {WSAEAFNOSUPPORT, "Address family not supported"},
449 {WSAEADDRINUSE, "Address already in use"},
450 {WSAEADDRNOTAVAIL, "Can't assign requested address"},
451 {WSAENETDOWN, "Network is down"},
452 {WSAENETUNREACH, "Network is unreachable"},
453 {WSAENETRESET, "Network dropped connection on reset"},
454 {WSAECONNABORTED, "Software caused connection abort"},
455 {WSAECONNRESET, "Connection reset by peer"},
456 {WSAENOBUFS, "No buffer space available"},
457 {WSAEISCONN, "Socket is already connected"},
458 {WSAENOTCONN, "Socket is not connected"},
459 {WSAESHUTDOWN, "Can't send after socket shutdown"},
460 {WSAETOOMANYREFS, "Too many references: can't splice"},
461 {WSAETIMEDOUT, "Operation timed out"},
462 {WSAECONNREFUSED, "Connection refused"},
463 {WSAELOOP, "Too many levels of symbolic links"},
464 {WSAENAMETOOLONG, "File name too long"},
465 {WSAEHOSTDOWN, "Host is down"},
466 {WSAEHOSTUNREACH, "No route to host"},
467 {WSAENOTEMPTY, "Directory not empty"},
468 {WSAEPROCLIM, "Too many processes"},
469 {WSAEUSERS, "Too many users"},
470 {WSAEDQUOT, "Disc quota exceeded"},
471 {WSAESTALE, "Stale NFS file handle"},
472 {WSAEREMOTE, "Too many levels of remote in path"},
473 {WSASYSNOTREADY, "Network subsystem is unvailable"},
474 {WSAVERNOTSUPPORTED, "WinSock version is not supported"},
475 {WSANOTINITIALISED,
476 "Successful WSAStartup() not yet performed"},
477 {WSAEDISCON, "Graceful shutdown in progress"},
478 /* Resolver errors */
479 {WSAHOST_NOT_FOUND, "No such host is known"},
480 {WSATRY_AGAIN, "Host not found, or server failed"},
481 {WSANO_RECOVERY, "Unexpected server error encountered"},
482 {WSANO_DATA, "Valid name without requested data"},
483 {WSANO_ADDRESS, "No address, look for MX record"},
484 {0, NULL}
486 if (err_no) {
487 PyObject *v;
488 const char *msg = "winsock error";
490 for (msgp = msgs; msgp->msg; msgp++) {
491 if (err_no == msgp->no) {
492 msg = msgp->msg;
493 break;
497 v = Py_BuildValue("(is)", err_no, msg);
498 if (v != NULL) {
499 PyErr_SetObject(socket_error, v);
500 Py_DECREF(v);
502 return NULL;
504 else
505 #endif
507 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
508 if (sock_errno() != NO_ERROR) {
509 APIRET rc;
510 ULONG msglen;
511 char outbuf[100];
512 int myerrorcode = sock_errno();
514 /* Retrieve socket-related error message from MPTN.MSG file */
515 rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf),
516 myerrorcode - SOCBASEERR + 26,
517 "mptn.msg",
518 &msglen);
519 if (rc == NO_ERROR) {
520 PyObject *v;
522 /* OS/2 doesn't guarantee a terminator */
523 outbuf[msglen] = '\0';
524 if (strlen(outbuf) > 0) {
525 /* If non-empty msg, trim CRLF */
526 char *lastc = &outbuf[ strlen(outbuf)-1 ];
527 while (lastc > outbuf &&
528 isspace(Py_CHARMASK(*lastc))) {
529 /* Trim trailing whitespace (CRLF) */
530 *lastc-- = '\0';
533 v = Py_BuildValue("(is)", myerrorcode, outbuf);
534 if (v != NULL) {
535 PyErr_SetObject(socket_error, v);
536 Py_DECREF(v);
538 return NULL;
541 #endif
543 #if defined(RISCOS)
544 if (_inet_error.errnum != NULL) {
545 PyObject *v;
546 v = Py_BuildValue("(is)", errno, _inet_err());
547 if (v != NULL) {
548 PyErr_SetObject(socket_error, v);
549 Py_DECREF(v);
551 return NULL;
553 #endif
555 return PyErr_SetFromErrno(socket_error);
559 static PyObject *
560 set_herror(int h_error)
562 PyObject *v;
564 #ifdef HAVE_HSTRERROR
565 v = Py_BuildValue("(is)", h_error, (char *)hstrerror(h_error));
566 #else
567 v = Py_BuildValue("(is)", h_error, "host not found");
568 #endif
569 if (v != NULL) {
570 PyErr_SetObject(socket_herror, v);
571 Py_DECREF(v);
574 return NULL;
578 static PyObject *
579 set_gaierror(int error)
581 PyObject *v;
583 #ifdef EAI_SYSTEM
584 /* EAI_SYSTEM is not available on Windows XP. */
585 if (error == EAI_SYSTEM)
586 return set_error();
587 #endif
589 #ifdef HAVE_GAI_STRERROR
590 v = Py_BuildValue("(is)", error, gai_strerror(error));
591 #else
592 v = Py_BuildValue("(is)", error, "getaddrinfo failed");
593 #endif
594 if (v != NULL) {
595 PyErr_SetObject(socket_gaierror, v);
596 Py_DECREF(v);
599 return NULL;
602 /* Function to perform the setting of socket blocking mode
603 internally. block = (1 | 0). */
604 static int
605 internal_setblocking(PySocketSockObject *s, int block)
607 #ifndef RISCOS
608 #ifndef MS_WINDOWS
609 int delay_flag;
610 #endif
611 #endif
613 Py_BEGIN_ALLOW_THREADS
614 #ifdef __BEOS__
615 block = !block;
616 setsockopt(s->sock_fd, SOL_SOCKET, SO_NONBLOCK,
617 (void *)(&block), sizeof(int));
618 #else
619 #ifndef RISCOS
620 #ifndef MS_WINDOWS
621 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
622 block = !block;
623 ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block));
624 #elif defined(__VMS)
625 block = !block;
626 ioctl(s->sock_fd, FIONBIO, (char *)&block);
627 #else /* !PYOS_OS2 && !_VMS */
628 delay_flag = fcntl(s->sock_fd, F_GETFL, 0);
629 if (block)
630 delay_flag &= (~O_NONBLOCK);
631 else
632 delay_flag |= O_NONBLOCK;
633 fcntl(s->sock_fd, F_SETFL, delay_flag);
634 #endif /* !PYOS_OS2 */
635 #else /* MS_WINDOWS */
636 block = !block;
637 ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
638 #endif /* MS_WINDOWS */
639 #else /* RISCOS */
640 block = !block;
641 socketioctl(s->sock_fd, FIONBIO, (u_long*)&block);
642 #endif /* RISCOS */
643 #endif /* __BEOS__ */
644 Py_END_ALLOW_THREADS
646 /* Since these don't return anything */
647 return 1;
650 /* Do a select() on the socket, if necessary (sock_timeout > 0).
651 The argument writing indicates the direction.
652 This does not raise an exception; we'll let our caller do that
653 after they've reacquired the interpreter lock.
654 Returns 1 on timeout, 0 otherwise. */
655 static int
656 internal_select(PySocketSockObject *s, int writing)
658 fd_set fds;
659 struct timeval tv;
660 int n;
662 /* Nothing to do unless we're in timeout mode (not non-blocking) */
663 if (s->sock_timeout <= 0.0)
664 return 0;
666 /* Guard against closed socket */
667 if (s->sock_fd < 0)
668 return 0;
670 /* Construct the arguments to select */
671 tv.tv_sec = (int)s->sock_timeout;
672 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
673 FD_ZERO(&fds);
674 FD_SET(s->sock_fd, &fds);
676 /* See if the socket is ready */
677 if (writing)
678 n = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
679 else
680 n = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
681 if (n == 0)
682 return 1;
683 return 0;
686 /* Initialize a new socket object. */
688 static double defaulttimeout = -1.0; /* Default timeout for new sockets */
690 PyMODINIT_FUNC
691 init_sockobject(PySocketSockObject *s,
692 SOCKET_T fd, int family, int type, int proto)
694 #ifdef RISCOS
695 int block = 1;
696 #endif
697 s->sock_fd = fd;
698 s->sock_family = family;
699 s->sock_type = type;
700 s->sock_proto = proto;
701 s->sock_timeout = defaulttimeout;
703 s->errorhandler = &set_error;
705 if (defaulttimeout >= 0.0)
706 internal_setblocking(s, 0);
708 #ifdef RISCOS
709 if (taskwindow)
710 socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
711 #endif
715 /* Create a new socket object.
716 This just creates the object and initializes it.
717 If the creation fails, return NULL and set an exception (implicit
718 in NEWOBJ()). */
720 static PySocketSockObject *
721 new_sockobject(SOCKET_T fd, int family, int type, int proto)
723 PySocketSockObject *s;
724 s = (PySocketSockObject *)
725 PyType_GenericNew(&sock_type, NULL, NULL);
726 if (s != NULL)
727 init_sockobject(s, fd, family, type, proto);
728 return s;
732 /* Lock to allow python interpreter to continue, but only allow one
733 thread to be in gethostbyname or getaddrinfo */
734 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
735 PyThread_type_lock netdb_lock;
736 #endif
739 /* Convert a string specifying a host name or one of a few symbolic
740 names to a numeric IP address. This usually calls gethostbyname()
741 to do the work; the names "" and "<broadcast>" are special.
742 Return the length (IPv4 should be 4 bytes), or negative if
743 an error occurred; then an exception is raised. */
745 static int
746 setipaddr(char *name, struct sockaddr *addr_ret, size_t addr_ret_size, int af)
748 struct addrinfo hints, *res;
749 int error;
750 int d1, d2, d3, d4;
751 char ch;
753 memset((void *) addr_ret, '\0', sizeof(*addr_ret));
754 if (name[0] == '\0') {
755 int siz;
756 memset(&hints, 0, sizeof(hints));
757 hints.ai_family = af;
758 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
759 hints.ai_flags = AI_PASSIVE;
760 Py_BEGIN_ALLOW_THREADS
761 ACQUIRE_GETADDRINFO_LOCK
762 error = getaddrinfo(NULL, "0", &hints, &res);
763 Py_END_ALLOW_THREADS
764 /* We assume that those thread-unsafe getaddrinfo() versions
765 *are* safe regarding their return value, ie. that a
766 subsequent call to getaddrinfo() does not destroy the
767 outcome of the first call. */
768 RELEASE_GETADDRINFO_LOCK
769 if (error) {
770 set_gaierror(error);
771 return -1;
773 switch (res->ai_family) {
774 case AF_INET:
775 siz = 4;
776 break;
777 #ifdef ENABLE_IPV6
778 case AF_INET6:
779 siz = 16;
780 break;
781 #endif
782 default:
783 freeaddrinfo(res);
784 PyErr_SetString(socket_error,
785 "unsupported address family");
786 return -1;
788 if (res->ai_next) {
789 freeaddrinfo(res);
790 PyErr_SetString(socket_error,
791 "wildcard resolved to multiple address");
792 return -1;
794 if (res->ai_addrlen < addr_ret_size)
795 addr_ret_size = res->ai_addrlen;
796 memcpy(addr_ret, res->ai_addr, addr_ret_size);
797 freeaddrinfo(res);
798 return siz;
800 if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
801 struct sockaddr_in *sin;
802 if (af != AF_INET && af != AF_UNSPEC) {
803 PyErr_SetString(socket_error,
804 "address family mismatched");
805 return -1;
807 sin = (struct sockaddr_in *)addr_ret;
808 memset((void *) sin, '\0', sizeof(*sin));
809 sin->sin_family = AF_INET;
810 #ifdef HAVE_SOCKADDR_SA_LEN
811 sin->sin_len = sizeof(*sin);
812 #endif
813 sin->sin_addr.s_addr = INADDR_BROADCAST;
814 return sizeof(sin->sin_addr);
816 if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 &&
817 0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 &&
818 0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) {
819 struct sockaddr_in *sin;
820 sin = (struct sockaddr_in *)addr_ret;
821 sin->sin_addr.s_addr = htonl(
822 ((long) d1 << 24) | ((long) d2 << 16) |
823 ((long) d3 << 8) | ((long) d4 << 0));
824 sin->sin_family = AF_INET;
825 #ifdef HAVE_SOCKADDR_SA_LEN
826 sin->sin_len = sizeof(*sin);
827 #endif
828 return 4;
830 memset(&hints, 0, sizeof(hints));
831 hints.ai_family = af;
832 Py_BEGIN_ALLOW_THREADS
833 ACQUIRE_GETADDRINFO_LOCK
834 error = getaddrinfo(name, NULL, &hints, &res);
835 #if defined(__digital__) && defined(__unix__)
836 if (error == EAI_NONAME && af == AF_UNSPEC) {
837 /* On Tru64 V5.1, numeric-to-addr conversion fails
838 if no address family is given. Assume IPv4 for now.*/
839 hints.ai_family = AF_INET;
840 error = getaddrinfo(name, NULL, &hints, &res);
842 #endif
843 Py_END_ALLOW_THREADS
844 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
845 if (error) {
846 set_gaierror(error);
847 return -1;
849 if (res->ai_addrlen < addr_ret_size)
850 addr_ret_size = res->ai_addrlen;
851 memcpy((char *) addr_ret, res->ai_addr, addr_ret_size);
852 freeaddrinfo(res);
853 switch (addr_ret->sa_family) {
854 case AF_INET:
855 return 4;
856 #ifdef ENABLE_IPV6
857 case AF_INET6:
858 return 16;
859 #endif
860 default:
861 PyErr_SetString(socket_error, "unknown address family");
862 return -1;
867 /* Create a string object representing an IP address.
868 This is always a string of the form 'dd.dd.dd.dd' (with variable
869 size numbers). */
871 static PyObject *
872 makeipaddr(struct sockaddr *addr, int addrlen)
874 char buf[NI_MAXHOST];
875 int error;
877 error = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0,
878 NI_NUMERICHOST);
879 if (error) {
880 set_gaierror(error);
881 return NULL;
883 return PyString_FromString(buf);
887 #ifdef USE_BLUETOOTH
888 /* Convert a string representation of a Bluetooth address into a numeric
889 address. Returns the length (6), or raises an exception and returns -1 if
890 an error occurred. */
892 static int
893 setbdaddr(char *name, bdaddr_t *bdaddr)
895 unsigned int b0, b1, b2, b3, b4, b5;
896 char ch;
897 int n;
899 n = sscanf(name, "%X:%X:%X:%X:%X:%X%c",
900 &b5, &b4, &b3, &b2, &b1, &b0, &ch);
901 if (n == 6 && (b0 | b1 | b2 | b3 | b4 | b5) < 256) {
902 bdaddr->b[0] = b0;
903 bdaddr->b[1] = b1;
904 bdaddr->b[2] = b2;
905 bdaddr->b[3] = b3;
906 bdaddr->b[4] = b4;
907 bdaddr->b[5] = b5;
908 return 6;
909 } else {
910 PyErr_SetString(socket_error, "bad bluetooth address");
911 return -1;
915 /* Create a string representation of the Bluetooth address. This is always a
916 string of the form 'XX:XX:XX:XX:XX:XX' where XX is a two digit hexadecimal
917 value (zero padded if necessary). */
919 static PyObject *
920 makebdaddr(bdaddr_t *bdaddr)
922 char buf[(6 * 2) + 5 + 1];
924 sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
925 bdaddr->b[5], bdaddr->b[4], bdaddr->b[3],
926 bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]);
927 return PyString_FromString(buf);
929 #endif
932 /* Create an object representing the given socket address,
933 suitable for passing it back to bind(), connect() etc.
934 The family field of the sockaddr structure is inspected
935 to determine what kind of address it really is. */
937 /*ARGSUSED*/
938 static PyObject *
939 makesockaddr(int sockfd, struct sockaddr *addr, int addrlen, int proto)
941 if (addrlen == 0) {
942 /* No address -- may be recvfrom() from known socket */
943 Py_INCREF(Py_None);
944 return Py_None;
947 #ifdef __BEOS__
948 /* XXX: BeOS version of accept() doesn't set family correctly */
949 addr->sa_family = AF_INET;
950 #endif
952 switch (addr->sa_family) {
954 case AF_INET:
956 struct sockaddr_in *a;
957 PyObject *addrobj = makeipaddr(addr, sizeof(*a));
958 PyObject *ret = NULL;
959 if (addrobj) {
960 a = (struct sockaddr_in *)addr;
961 ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
962 Py_DECREF(addrobj);
964 return ret;
967 #if defined(AF_UNIX)
968 case AF_UNIX:
970 struct sockaddr_un *a = (struct sockaddr_un *) addr;
971 return PyString_FromString(a->sun_path);
973 #endif /* AF_UNIX */
975 #if defined(AF_NETLINK)
976 case AF_NETLINK:
978 struct sockaddr_nl *a = (struct sockaddr_nl *) addr;
979 return Py_BuildValue("II", a->nl_pid, a->nl_groups);
981 #endif /* AF_NETLINK */
983 #ifdef ENABLE_IPV6
984 case AF_INET6:
986 struct sockaddr_in6 *a;
987 PyObject *addrobj = makeipaddr(addr, sizeof(*a));
988 PyObject *ret = NULL;
989 if (addrobj) {
990 a = (struct sockaddr_in6 *)addr;
991 ret = Py_BuildValue("Oiii",
992 addrobj,
993 ntohs(a->sin6_port),
994 a->sin6_flowinfo,
995 a->sin6_scope_id);
996 Py_DECREF(addrobj);
998 return ret;
1000 #endif
1002 #ifdef USE_BLUETOOTH
1003 case AF_BLUETOOTH:
1004 switch (proto) {
1006 case BTPROTO_L2CAP:
1008 struct sockaddr_l2 *a = (struct sockaddr_l2 *) addr;
1009 PyObject *addrobj = makebdaddr(&_BT_L2_MEMB(a, bdaddr));
1010 PyObject *ret = NULL;
1011 if (addrobj) {
1012 ret = Py_BuildValue("Oi",
1013 addrobj,
1014 _BT_L2_MEMB(a, psm));
1015 Py_DECREF(addrobj);
1017 return ret;
1020 case BTPROTO_RFCOMM:
1022 struct sockaddr_rc *a = (struct sockaddr_rc *) addr;
1023 PyObject *addrobj = makebdaddr(&_BT_RC_MEMB(a, bdaddr));
1024 PyObject *ret = NULL;
1025 if (addrobj) {
1026 ret = Py_BuildValue("Oi",
1027 addrobj,
1028 _BT_RC_MEMB(a, channel));
1029 Py_DECREF(addrobj);
1031 return ret;
1034 #if !defined(__FreeBSD__)
1035 case BTPROTO_SCO:
1037 struct sockaddr_sco *a = (struct sockaddr_sco *) addr;
1038 return makebdaddr(&_BT_SCO_MEMB(a, bdaddr));
1040 #endif
1043 #endif
1045 #ifdef HAVE_NETPACKET_PACKET_H
1046 case AF_PACKET:
1048 struct sockaddr_ll *a = (struct sockaddr_ll *)addr;
1049 char *ifname = "";
1050 struct ifreq ifr;
1051 /* need to look up interface name give index */
1052 if (a->sll_ifindex) {
1053 ifr.ifr_ifindex = a->sll_ifindex;
1054 if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0)
1055 ifname = ifr.ifr_name;
1057 return Py_BuildValue("shbhs#",
1058 ifname,
1059 ntohs(a->sll_protocol),
1060 a->sll_pkttype,
1061 a->sll_hatype,
1062 a->sll_addr,
1063 a->sll_halen);
1065 #endif
1067 /* More cases here... */
1069 default:
1070 /* If we don't know the address family, don't raise an
1071 exception -- return it as a tuple. */
1072 return Py_BuildValue("is#",
1073 addr->sa_family,
1074 addr->sa_data,
1075 sizeof(addr->sa_data));
1081 /* Parse a socket address argument according to the socket object's
1082 address family. Return 1 if the address was in the proper format,
1083 0 of not. The address is returned through addr_ret, its length
1084 through len_ret. */
1086 static int
1087 getsockaddrarg(PySocketSockObject *s, PyObject *args,
1088 struct sockaddr **addr_ret, int *len_ret)
1090 switch (s->sock_family) {
1092 #if defined(AF_UNIX)
1093 case AF_UNIX:
1095 struct sockaddr_un* addr;
1096 char *path;
1097 int len;
1098 addr = (struct sockaddr_un*)&(s->sock_addr).un;
1099 if (!PyArg_Parse(args, "t#", &path, &len))
1100 return 0;
1101 if (len > sizeof addr->sun_path) {
1102 PyErr_SetString(socket_error,
1103 "AF_UNIX path too long");
1104 return 0;
1106 addr->sun_family = s->sock_family;
1107 memcpy(addr->sun_path, path, len);
1108 addr->sun_path[len] = 0;
1109 *addr_ret = (struct sockaddr *) addr;
1110 #if defined(PYOS_OS2)
1111 *len_ret = sizeof(*addr);
1112 #else
1113 *len_ret = len + sizeof(*addr) - sizeof(addr->sun_path);
1114 #endif
1115 return 1;
1117 #endif /* AF_UNIX */
1119 #if defined(AF_NETLINK)
1120 case AF_NETLINK:
1122 struct sockaddr_nl* addr;
1123 int pid, groups;
1124 addr = (struct sockaddr_nl *)&(s->sock_addr).nl;
1125 if (!PyTuple_Check(args)) {
1126 PyErr_Format(
1127 PyExc_TypeError,
1128 "getsockaddrarg: "
1129 "AF_NETLINK address must be tuple, not %.500s",
1130 args->ob_type->tp_name);
1131 return 0;
1133 if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &pid, &groups))
1134 return 0;
1135 addr->nl_family = AF_NETLINK;
1136 addr->nl_pid = pid;
1137 addr->nl_groups = groups;
1138 *addr_ret = (struct sockaddr *) addr;
1139 *len_ret = sizeof(*addr);
1140 return 1;
1142 #endif
1144 case AF_INET:
1146 struct sockaddr_in* addr;
1147 char *host;
1148 int port, result;
1149 addr=(struct sockaddr_in*)&(s->sock_addr).in;
1150 if (!PyTuple_Check(args)) {
1151 PyErr_Format(
1152 PyExc_TypeError,
1153 "getsockaddrarg: "
1154 "AF_INET address must be tuple, not %.500s",
1155 args->ob_type->tp_name);
1156 return 0;
1158 if (!PyArg_ParseTuple(args, "eti:getsockaddrarg",
1159 "idna", &host, &port))
1160 return 0;
1161 result = setipaddr(host, (struct sockaddr *)addr,
1162 sizeof(*addr), AF_INET);
1163 PyMem_Free(host);
1164 if (result < 0)
1165 return 0;
1166 addr->sin_family = AF_INET;
1167 addr->sin_port = htons((short)port);
1168 *addr_ret = (struct sockaddr *) addr;
1169 *len_ret = sizeof *addr;
1170 return 1;
1173 #ifdef ENABLE_IPV6
1174 case AF_INET6:
1176 struct sockaddr_in6* addr;
1177 char *host;
1178 int port, flowinfo, scope_id, result;
1179 addr = (struct sockaddr_in6*)&(s->sock_addr).in6;
1180 flowinfo = scope_id = 0;
1181 if (!PyArg_ParseTuple(args, "eti|ii",
1182 "idna", &host, &port, &flowinfo,
1183 &scope_id)) {
1184 return 0;
1186 result = setipaddr(host, (struct sockaddr *)addr,
1187 sizeof(*addr), AF_INET6);
1188 PyMem_Free(host);
1189 if (result < 0)
1190 return 0;
1191 addr->sin6_family = s->sock_family;
1192 addr->sin6_port = htons((short)port);
1193 addr->sin6_flowinfo = flowinfo;
1194 addr->sin6_scope_id = scope_id;
1195 *addr_ret = (struct sockaddr *) addr;
1196 *len_ret = sizeof *addr;
1197 return 1;
1199 #endif
1201 #ifdef USE_BLUETOOTH
1202 case AF_BLUETOOTH:
1204 switch (s->sock_proto) {
1205 case BTPROTO_L2CAP:
1207 struct sockaddr_l2 *addr = (struct sockaddr_l2 *) _BT_SOCKADDR_MEMB(s, l2);
1208 char *straddr;
1210 _BT_L2_MEMB(addr, family) = AF_BLUETOOTH;
1211 if (!PyArg_ParseTuple(args, "si", &straddr,
1212 &_BT_L2_MEMB(addr, psm))) {
1213 PyErr_SetString(socket_error, "getsockaddrarg: "
1214 "wrong format");
1215 return 0;
1217 if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0)
1218 return 0;
1220 *addr_ret = (struct sockaddr *) addr;
1221 *len_ret = sizeof *addr;
1222 return 1;
1224 case BTPROTO_RFCOMM:
1226 struct sockaddr_rc *addr = (struct sockaddr_rc *) _BT_SOCKADDR_MEMB(s, rc);
1227 char *straddr;
1229 _BT_RC_MEMB(addr, family) = AF_BLUETOOTH;
1230 if (!PyArg_ParseTuple(args, "si", &straddr,
1231 &_BT_RC_MEMB(addr, channel))) {
1232 PyErr_SetString(socket_error, "getsockaddrarg: "
1233 "wrong format");
1234 return 0;
1236 if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0)
1237 return 0;
1239 *addr_ret = (struct sockaddr *) addr;
1240 *len_ret = sizeof *addr;
1241 return 1;
1243 #if !defined(__FreeBSD__)
1244 case BTPROTO_SCO:
1246 struct sockaddr_sco *addr = (struct sockaddr_sco *) _BT_SOCKADDR_MEMB(s, sco);
1247 char *straddr;
1249 _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH;
1250 straddr = PyString_AsString(args);
1251 if (straddr == NULL) {
1252 PyErr_SetString(socket_error, "getsockaddrarg: "
1253 "wrong format");
1254 return 0;
1256 if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0)
1257 return 0;
1259 *addr_ret = (struct sockaddr *) addr;
1260 *len_ret = sizeof *addr;
1261 return 1;
1263 #endif
1264 default:
1265 PyErr_SetString(socket_error, "getsockaddrarg: unknown Bluetooth protocol");
1266 return 0;
1269 #endif
1271 #ifdef HAVE_NETPACKET_PACKET_H
1272 case AF_PACKET:
1274 struct sockaddr_ll* addr;
1275 struct ifreq ifr;
1276 char *interfaceName;
1277 int protoNumber;
1278 int hatype = 0;
1279 int pkttype = 0;
1280 char *haddr = NULL;
1281 unsigned int halen = 0;
1283 if (!PyArg_ParseTuple(args, "si|iis#", &interfaceName,
1284 &protoNumber, &pkttype, &hatype,
1285 &haddr, &halen))
1286 return 0;
1287 strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name));
1288 ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
1289 if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
1290 s->errorhandler();
1291 return 0;
1293 addr = &(s->sock_addr.ll);
1294 addr->sll_family = AF_PACKET;
1295 addr->sll_protocol = htons((short)protoNumber);
1296 addr->sll_ifindex = ifr.ifr_ifindex;
1297 addr->sll_pkttype = pkttype;
1298 addr->sll_hatype = hatype;
1299 if (halen > 8) {
1300 PyErr_SetString(PyExc_ValueError,
1301 "Hardware address must be 8 bytes or less");
1302 return 0;
1304 if (halen != 0) {
1305 memcpy(&addr->sll_addr, haddr, halen);
1307 addr->sll_halen = halen;
1308 *addr_ret = (struct sockaddr *) addr;
1309 *len_ret = sizeof *addr;
1310 return 1;
1312 #endif
1314 /* More cases here... */
1316 default:
1317 PyErr_SetString(socket_error, "getsockaddrarg: bad family");
1318 return 0;
1324 /* Get the address length according to the socket object's address family.
1325 Return 1 if the family is known, 0 otherwise. The length is returned
1326 through len_ret. */
1328 static int
1329 getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
1331 switch (s->sock_family) {
1333 #if defined(AF_UNIX)
1334 case AF_UNIX:
1336 *len_ret = sizeof (struct sockaddr_un);
1337 return 1;
1339 #endif /* AF_UNIX */
1340 #if defined(AF_NETLINK)
1341 case AF_NETLINK:
1343 *len_ret = sizeof (struct sockaddr_nl);
1344 return 1;
1346 #endif
1348 case AF_INET:
1350 *len_ret = sizeof (struct sockaddr_in);
1351 return 1;
1354 #ifdef ENABLE_IPV6
1355 case AF_INET6:
1357 *len_ret = sizeof (struct sockaddr_in6);
1358 return 1;
1360 #endif
1362 #ifdef USE_BLUETOOTH
1363 case AF_BLUETOOTH:
1365 switch(s->sock_proto)
1368 case BTPROTO_L2CAP:
1369 *len_ret = sizeof (struct sockaddr_l2);
1370 return 1;
1371 case BTPROTO_RFCOMM:
1372 *len_ret = sizeof (struct sockaddr_rc);
1373 return 1;
1374 #if !defined(__FreeBSD__)
1375 case BTPROTO_SCO:
1376 *len_ret = sizeof (struct sockaddr_sco);
1377 return 1;
1378 #endif
1379 default:
1380 PyErr_SetString(socket_error, "getsockaddrlen: "
1381 "unknown BT protocol");
1382 return 0;
1386 #endif
1388 #ifdef HAVE_NETPACKET_PACKET_H
1389 case AF_PACKET:
1391 *len_ret = sizeof (struct sockaddr_ll);
1392 return 1;
1394 #endif
1396 /* More cases here... */
1398 default:
1399 PyErr_SetString(socket_error, "getsockaddrlen: bad family");
1400 return 0;
1406 /* s.accept() method */
1408 static PyObject *
1409 sock_accept(PySocketSockObject *s)
1411 sock_addr_t addrbuf;
1412 SOCKET_T newfd;
1413 socklen_t addrlen;
1414 PyObject *sock = NULL;
1415 PyObject *addr = NULL;
1416 PyObject *res = NULL;
1417 int timeout;
1419 if (!getsockaddrlen(s, &addrlen))
1420 return NULL;
1421 memset(&addrbuf, 0, addrlen);
1423 #ifdef MS_WINDOWS
1424 newfd = INVALID_SOCKET;
1425 #else
1426 newfd = -1;
1427 #endif
1429 if (!IS_SELECTABLE(s))
1430 return select_error();
1432 Py_BEGIN_ALLOW_THREADS
1433 timeout = internal_select(s, 0);
1434 if (!timeout)
1435 newfd = accept(s->sock_fd, (struct sockaddr *) &addrbuf,
1436 &addrlen);
1437 Py_END_ALLOW_THREADS
1439 if (timeout) {
1440 PyErr_SetString(socket_timeout, "timed out");
1441 return NULL;
1444 #ifdef MS_WINDOWS
1445 if (newfd == INVALID_SOCKET)
1446 #else
1447 if (newfd < 0)
1448 #endif
1449 return s->errorhandler();
1451 /* Create the new object with unspecified family,
1452 to avoid calls to bind() etc. on it. */
1453 sock = (PyObject *) new_sockobject(newfd,
1454 s->sock_family,
1455 s->sock_type,
1456 s->sock_proto);
1458 if (sock == NULL) {
1459 SOCKETCLOSE(newfd);
1460 goto finally;
1462 addr = makesockaddr(s->sock_fd, (struct sockaddr *) &addrbuf,
1463 addrlen, s->sock_proto);
1464 if (addr == NULL)
1465 goto finally;
1467 res = PyTuple_Pack(2, sock, addr);
1469 finally:
1470 Py_XDECREF(sock);
1471 Py_XDECREF(addr);
1472 return res;
1475 PyDoc_STRVAR(accept_doc,
1476 "accept() -> (socket object, address info)\n\
1478 Wait for an incoming connection. Return a new socket representing the\n\
1479 connection, and the address of the client. For IP sockets, the address\n\
1480 info is a pair (hostaddr, port).");
1482 /* s.setblocking(flag) method. Argument:
1483 False -- non-blocking mode; same as settimeout(0)
1484 True -- blocking mode; same as settimeout(None)
1487 static PyObject *
1488 sock_setblocking(PySocketSockObject *s, PyObject *arg)
1490 int block;
1492 block = PyInt_AsLong(arg);
1493 if (block == -1 && PyErr_Occurred())
1494 return NULL;
1496 s->sock_timeout = block ? -1.0 : 0.0;
1497 internal_setblocking(s, block);
1499 Py_INCREF(Py_None);
1500 return Py_None;
1503 PyDoc_STRVAR(setblocking_doc,
1504 "setblocking(flag)\n\
1506 Set the socket to blocking (flag is true) or non-blocking (false).\n\
1507 setblocking(True) is equivalent to settimeout(None);\n\
1508 setblocking(False) is equivalent to settimeout(0.0).");
1510 /* s.settimeout(timeout) method. Argument:
1511 None -- no timeout, blocking mode; same as setblocking(True)
1512 0.0 -- non-blocking mode; same as setblocking(False)
1513 > 0 -- timeout mode; operations time out after timeout seconds
1514 < 0 -- illegal; raises an exception
1516 static PyObject *
1517 sock_settimeout(PySocketSockObject *s, PyObject *arg)
1519 double timeout;
1521 if (arg == Py_None)
1522 timeout = -1.0;
1523 else {
1524 timeout = PyFloat_AsDouble(arg);
1525 if (timeout < 0.0) {
1526 if (!PyErr_Occurred())
1527 PyErr_SetString(PyExc_ValueError,
1528 "Timeout value out of range");
1529 return NULL;
1533 s->sock_timeout = timeout;
1534 internal_setblocking(s, timeout < 0.0);
1536 Py_INCREF(Py_None);
1537 return Py_None;
1540 PyDoc_STRVAR(settimeout_doc,
1541 "settimeout(timeout)\n\
1543 Set a timeout on socket operations. 'timeout' can be a float,\n\
1544 giving in seconds, or None. Setting a timeout of None disables\n\
1545 the timeout feature and is equivalent to setblocking(1).\n\
1546 Setting a timeout of zero is the same as setblocking(0).");
1548 /* s.gettimeout() method.
1549 Returns the timeout associated with a socket. */
1550 static PyObject *
1551 sock_gettimeout(PySocketSockObject *s)
1553 if (s->sock_timeout < 0.0) {
1554 Py_INCREF(Py_None);
1555 return Py_None;
1557 else
1558 return PyFloat_FromDouble(s->sock_timeout);
1561 PyDoc_STRVAR(gettimeout_doc,
1562 "gettimeout() -> timeout\n\
1564 Returns the timeout in floating seconds associated with socket \n\
1565 operations. A timeout of None indicates that timeouts on socket \n\
1566 operations are disabled.");
1568 #ifdef RISCOS
1569 /* s.sleeptaskw(1 | 0) method */
1571 static PyObject *
1572 sock_sleeptaskw(PySocketSockObject *s,PyObject *arg)
1574 int block;
1575 block = PyInt_AsLong(arg);
1576 if (block == -1 && PyErr_Occurred())
1577 return NULL;
1578 Py_BEGIN_ALLOW_THREADS
1579 socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
1580 Py_END_ALLOW_THREADS
1582 Py_INCREF(Py_None);
1583 return Py_None;
1585 PyDoc_STRVAR(sleeptaskw_doc,
1586 "sleeptaskw(flag)\n\
1588 Allow sleeps in taskwindows.");
1589 #endif
1592 /* s.setsockopt() method.
1593 With an integer third argument, sets an integer option.
1594 With a string third argument, sets an option from a buffer;
1595 use optional built-in module 'struct' to encode the string. */
1597 static PyObject *
1598 sock_setsockopt(PySocketSockObject *s, PyObject *args)
1600 int level;
1601 int optname;
1602 int res;
1603 char *buf;
1604 int buflen;
1605 int flag;
1607 if (PyArg_ParseTuple(args, "iii:setsockopt",
1608 &level, &optname, &flag)) {
1609 buf = (char *) &flag;
1610 buflen = sizeof flag;
1612 else {
1613 PyErr_Clear();
1614 if (!PyArg_ParseTuple(args, "iis#:setsockopt",
1615 &level, &optname, &buf, &buflen))
1616 return NULL;
1618 res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen);
1619 if (res < 0)
1620 return s->errorhandler();
1621 Py_INCREF(Py_None);
1622 return Py_None;
1625 PyDoc_STRVAR(setsockopt_doc,
1626 "setsockopt(level, option, value)\n\
1628 Set a socket option. See the Unix manual for level and option.\n\
1629 The value argument can either be an integer or a string.");
1632 /* s.getsockopt() method.
1633 With two arguments, retrieves an integer option.
1634 With a third integer argument, retrieves a string buffer of that size;
1635 use optional built-in module 'struct' to decode the string. */
1637 static PyObject *
1638 sock_getsockopt(PySocketSockObject *s, PyObject *args)
1640 int level;
1641 int optname;
1642 int res;
1643 PyObject *buf;
1644 socklen_t buflen = 0;
1646 #ifdef __BEOS__
1647 /* We have incomplete socket support. */
1648 PyErr_SetString(socket_error, "getsockopt not supported");
1649 return NULL;
1650 #else
1652 if (!PyArg_ParseTuple(args, "ii|i:getsockopt",
1653 &level, &optname, &buflen))
1654 return NULL;
1656 if (buflen == 0) {
1657 int flag = 0;
1658 socklen_t flagsize = sizeof flag;
1659 res = getsockopt(s->sock_fd, level, optname,
1660 (void *)&flag, &flagsize);
1661 if (res < 0)
1662 return s->errorhandler();
1663 return PyInt_FromLong(flag);
1665 #ifdef __VMS
1666 if (buflen > 1024) {
1667 #else
1668 if (buflen <= 0 || buflen > 1024) {
1669 #endif
1670 PyErr_SetString(socket_error,
1671 "getsockopt buflen out of range");
1672 return NULL;
1674 buf = PyString_FromStringAndSize((char *)NULL, buflen);
1675 if (buf == NULL)
1676 return NULL;
1677 res = getsockopt(s->sock_fd, level, optname,
1678 (void *)PyString_AS_STRING(buf), &buflen);
1679 if (res < 0) {
1680 Py_DECREF(buf);
1681 return s->errorhandler();
1683 _PyString_Resize(&buf, buflen);
1684 return buf;
1685 #endif /* __BEOS__ */
1688 PyDoc_STRVAR(getsockopt_doc,
1689 "getsockopt(level, option[, buffersize]) -> value\n\
1691 Get a socket option. See the Unix manual for level and option.\n\
1692 If a nonzero buffersize argument is given, the return value is a\n\
1693 string of that length; otherwise it is an integer.");
1696 /* s.bind(sockaddr) method */
1698 static PyObject *
1699 sock_bind(PySocketSockObject *s, PyObject *addro)
1701 struct sockaddr *addr;
1702 int addrlen;
1703 int res;
1705 if (!getsockaddrarg(s, addro, &addr, &addrlen))
1706 return NULL;
1707 Py_BEGIN_ALLOW_THREADS
1708 res = bind(s->sock_fd, addr, addrlen);
1709 Py_END_ALLOW_THREADS
1710 if (res < 0)
1711 return s->errorhandler();
1712 Py_INCREF(Py_None);
1713 return Py_None;
1716 PyDoc_STRVAR(bind_doc,
1717 "bind(address)\n\
1719 Bind the socket to a local address. For IP sockets, the address is a\n\
1720 pair (host, port); the host must refer to the local host. For raw packet\n\
1721 sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");
1724 /* s.close() method.
1725 Set the file descriptor to -1 so operations tried subsequently
1726 will surely fail. */
1728 static PyObject *
1729 sock_close(PySocketSockObject *s)
1731 SOCKET_T fd;
1733 if ((fd = s->sock_fd) != -1) {
1734 s->sock_fd = -1;
1735 Py_BEGIN_ALLOW_THREADS
1736 (void) SOCKETCLOSE(fd);
1737 Py_END_ALLOW_THREADS
1739 Py_INCREF(Py_None);
1740 return Py_None;
1743 PyDoc_STRVAR(close_doc,
1744 "close()\n\
1746 Close the socket. It cannot be used after this call.");
1748 static int
1749 internal_connect(PySocketSockObject *s, struct sockaddr *addr, int addrlen,
1750 int *timeoutp)
1752 int res, timeout;
1754 timeout = 0;
1755 res = connect(s->sock_fd, addr, addrlen);
1757 #ifdef MS_WINDOWS
1759 if (s->sock_timeout > 0.0) {
1760 if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK &&
1761 IS_SELECTABLE(s)) {
1762 /* This is a mess. Best solution: trust select */
1763 fd_set fds;
1764 fd_set fds_exc;
1765 struct timeval tv;
1766 tv.tv_sec = (int)s->sock_timeout;
1767 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1768 FD_ZERO(&fds);
1769 FD_SET(s->sock_fd, &fds);
1770 FD_ZERO(&fds_exc);
1771 FD_SET(s->sock_fd, &fds_exc);
1772 res = select(s->sock_fd+1, NULL, &fds, &fds_exc, &tv);
1773 if (res == 0) {
1774 res = WSAEWOULDBLOCK;
1775 timeout = 1;
1776 } else if (res > 0) {
1777 if (FD_ISSET(s->sock_fd, &fds))
1778 /* The socket is in the writeable set - this
1779 means connected */
1780 res = 0;
1781 else {
1782 /* As per MS docs, we need to call getsockopt()
1783 to get the underlying error */
1784 int res_size = sizeof res;
1785 /* It must be in the exception set */
1786 assert(FD_ISSET(s->sock_fd, &fds_exc));
1787 if (0 == getsockopt(s->sock_fd, SOL_SOCKET, SO_ERROR,
1788 (char *)&res, &res_size))
1789 /* getsockopt also clears WSAGetLastError,
1790 so reset it back. */
1791 WSASetLastError(res);
1792 else
1793 res = WSAGetLastError();
1796 /* else if (res < 0) an error occurred */
1800 if (res < 0)
1801 res = WSAGetLastError();
1803 #else
1805 if (s->sock_timeout > 0.0) {
1806 if (res < 0 && errno == EINPROGRESS && IS_SELECTABLE(s)) {
1807 timeout = internal_select(s, 1);
1808 res = connect(s->sock_fd, addr, addrlen);
1809 if (res < 0 && errno == EISCONN)
1810 res = 0;
1814 if (res < 0)
1815 res = errno;
1817 #endif
1818 *timeoutp = timeout;
1820 return res;
1823 /* s.connect(sockaddr) method */
1825 static PyObject *
1826 sock_connect(PySocketSockObject *s, PyObject *addro)
1828 struct sockaddr *addr;
1829 int addrlen;
1830 int res;
1831 int timeout;
1833 if (!getsockaddrarg(s, addro, &addr, &addrlen))
1834 return NULL;
1836 Py_BEGIN_ALLOW_THREADS
1837 res = internal_connect(s, addr, addrlen, &timeout);
1838 Py_END_ALLOW_THREADS
1840 if (timeout) {
1841 PyErr_SetString(socket_timeout, "timed out");
1842 return NULL;
1844 if (res != 0)
1845 return s->errorhandler();
1846 Py_INCREF(Py_None);
1847 return Py_None;
1850 PyDoc_STRVAR(connect_doc,
1851 "connect(address)\n\
1853 Connect the socket to a remote address. For IP sockets, the address\n\
1854 is a pair (host, port).");
1857 /* s.connect_ex(sockaddr) method */
1859 static PyObject *
1860 sock_connect_ex(PySocketSockObject *s, PyObject *addro)
1862 struct sockaddr *addr;
1863 int addrlen;
1864 int res;
1865 int timeout;
1867 if (!getsockaddrarg(s, addro, &addr, &addrlen))
1868 return NULL;
1870 Py_BEGIN_ALLOW_THREADS
1871 res = internal_connect(s, addr, addrlen, &timeout);
1872 Py_END_ALLOW_THREADS
1874 return PyInt_FromLong((long) res);
1877 PyDoc_STRVAR(connect_ex_doc,
1878 "connect_ex(address) -> errno\n\
1880 This is like connect(address), but returns an error code (the errno value)\n\
1881 instead of raising an exception when an error occurs.");
1884 /* s.fileno() method */
1886 static PyObject *
1887 sock_fileno(PySocketSockObject *s)
1889 #if SIZEOF_SOCKET_T <= SIZEOF_LONG
1890 return PyInt_FromLong((long) s->sock_fd);
1891 #else
1892 return PyLong_FromLongLong((PY_LONG_LONG)s->sock_fd);
1893 #endif
1896 PyDoc_STRVAR(fileno_doc,
1897 "fileno() -> integer\n\
1899 Return the integer file descriptor of the socket.");
1902 #ifndef NO_DUP
1903 /* s.dup() method */
1905 static PyObject *
1906 sock_dup(PySocketSockObject *s)
1908 SOCKET_T newfd;
1909 PyObject *sock;
1911 newfd = dup(s->sock_fd);
1912 if (newfd < 0)
1913 return s->errorhandler();
1914 sock = (PyObject *) new_sockobject(newfd,
1915 s->sock_family,
1916 s->sock_type,
1917 s->sock_proto);
1918 if (sock == NULL)
1919 SOCKETCLOSE(newfd);
1920 return sock;
1923 PyDoc_STRVAR(dup_doc,
1924 "dup() -> socket object\n\
1926 Return a new socket object connected to the same system resource.");
1928 #endif
1931 /* s.getsockname() method */
1933 static PyObject *
1934 sock_getsockname(PySocketSockObject *s)
1936 sock_addr_t addrbuf;
1937 int res;
1938 socklen_t addrlen;
1940 if (!getsockaddrlen(s, &addrlen))
1941 return NULL;
1942 memset(&addrbuf, 0, addrlen);
1943 Py_BEGIN_ALLOW_THREADS
1944 res = getsockname(s->sock_fd, (struct sockaddr *) &addrbuf, &addrlen);
1945 Py_END_ALLOW_THREADS
1946 if (res < 0)
1947 return s->errorhandler();
1948 return makesockaddr(s->sock_fd, (struct sockaddr *) &addrbuf, addrlen,
1949 s->sock_proto);
1952 PyDoc_STRVAR(getsockname_doc,
1953 "getsockname() -> address info\n\
1955 Return the address of the local endpoint. For IP sockets, the address\n\
1956 info is a pair (hostaddr, port).");
1959 #ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
1960 /* s.getpeername() method */
1962 static PyObject *
1963 sock_getpeername(PySocketSockObject *s)
1965 sock_addr_t addrbuf;
1966 int res;
1967 socklen_t addrlen;
1969 if (!getsockaddrlen(s, &addrlen))
1970 return NULL;
1971 memset(&addrbuf, 0, addrlen);
1972 Py_BEGIN_ALLOW_THREADS
1973 res = getpeername(s->sock_fd, (struct sockaddr *) &addrbuf, &addrlen);
1974 Py_END_ALLOW_THREADS
1975 if (res < 0)
1976 return s->errorhandler();
1977 return makesockaddr(s->sock_fd, (struct sockaddr *) &addrbuf, addrlen,
1978 s->sock_proto);
1981 PyDoc_STRVAR(getpeername_doc,
1982 "getpeername() -> address info\n\
1984 Return the address of the remote endpoint. For IP sockets, the address\n\
1985 info is a pair (hostaddr, port).");
1987 #endif /* HAVE_GETPEERNAME */
1990 /* s.listen(n) method */
1992 static PyObject *
1993 sock_listen(PySocketSockObject *s, PyObject *arg)
1995 int backlog;
1996 int res;
1998 backlog = PyInt_AsLong(arg);
1999 if (backlog == -1 && PyErr_Occurred())
2000 return NULL;
2001 Py_BEGIN_ALLOW_THREADS
2002 if (backlog < 1)
2003 backlog = 1;
2004 res = listen(s->sock_fd, backlog);
2005 Py_END_ALLOW_THREADS
2006 if (res < 0)
2007 return s->errorhandler();
2008 Py_INCREF(Py_None);
2009 return Py_None;
2012 PyDoc_STRVAR(listen_doc,
2013 "listen(backlog)\n\
2015 Enable a server to accept connections. The backlog argument must be at\n\
2016 least 1; it specifies the number of unaccepted connection that the system\n\
2017 will allow before refusing new connections.");
2020 #ifndef NO_DUP
2021 /* s.makefile(mode) method.
2022 Create a new open file object referring to a dupped version of
2023 the socket's file descriptor. (The dup() call is necessary so
2024 that the open file and socket objects may be closed independent
2025 of each other.)
2026 The mode argument specifies 'r' or 'w' passed to fdopen(). */
2028 static PyObject *
2029 sock_makefile(PySocketSockObject *s, PyObject *args)
2031 extern int fclose(FILE *);
2032 char *mode = "r";
2033 int bufsize = -1;
2034 #ifdef MS_WIN32
2035 Py_intptr_t fd;
2036 #else
2037 int fd;
2038 #endif
2039 FILE *fp;
2040 PyObject *f;
2041 #ifdef __VMS
2042 char *mode_r = "r";
2043 char *mode_w = "w";
2044 #endif
2046 if (!PyArg_ParseTuple(args, "|si:makefile", &mode, &bufsize))
2047 return NULL;
2048 #ifdef __VMS
2049 if (strcmp(mode,"rb") == 0) {
2050 mode = mode_r;
2052 else {
2053 if (strcmp(mode,"wb") == 0) {
2054 mode = mode_w;
2057 #endif
2058 #ifdef MS_WIN32
2059 if (((fd = _open_osfhandle(s->sock_fd, _O_BINARY)) < 0) ||
2060 ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL))
2061 #else
2062 if ((fd = dup(s->sock_fd)) < 0 || (fp = fdopen(fd, mode)) == NULL)
2063 #endif
2065 if (fd >= 0)
2066 SOCKETCLOSE(fd);
2067 return s->errorhandler();
2069 f = PyFile_FromFile(fp, "<socket>", mode, fclose);
2070 if (f != NULL)
2071 PyFile_SetBufSize(f, bufsize);
2072 return f;
2075 PyDoc_STRVAR(makefile_doc,
2076 "makefile([mode[, buffersize]]) -> file object\n\
2078 Return a regular file object corresponding to the socket.\n\
2079 The mode and buffersize arguments are as for the built-in open() function.");
2081 #endif /* NO_DUP */
2084 /* s.recv(nbytes [,flags]) method */
2086 static PyObject *
2087 sock_recv(PySocketSockObject *s, PyObject *args)
2089 int len, n = 0, flags = 0, timeout;
2090 PyObject *buf;
2091 #ifdef __VMS
2092 int read_length;
2093 char *read_buf;
2094 #endif
2096 if (!PyArg_ParseTuple(args, "i|i:recv", &len, &flags))
2097 return NULL;
2099 if (len < 0) {
2100 PyErr_SetString(PyExc_ValueError,
2101 "negative buffersize in recv");
2102 return NULL;
2105 buf = PyString_FromStringAndSize((char *) 0, len);
2106 if (buf == NULL)
2107 return NULL;
2109 if (!IS_SELECTABLE(s))
2110 return select_error();
2112 #ifndef __VMS
2113 Py_BEGIN_ALLOW_THREADS
2114 timeout = internal_select(s, 0);
2115 if (!timeout)
2116 n = recv(s->sock_fd, PyString_AS_STRING(buf), len, flags);
2117 Py_END_ALLOW_THREADS
2119 if (timeout) {
2120 Py_DECREF(buf);
2121 PyErr_SetString(socket_timeout, "timed out");
2122 return NULL;
2124 if (n < 0) {
2125 Py_DECREF(buf);
2126 return s->errorhandler();
2128 if (n != len)
2129 _PyString_Resize(&buf, n);
2130 #else
2131 read_buf = PyString_AsString(buf);
2132 read_length = len;
2133 while (read_length != 0) {
2134 unsigned int segment;
2136 segment = read_length /SEGMENT_SIZE;
2137 if (segment != 0) {
2138 segment = SEGMENT_SIZE;
2140 else {
2141 segment = read_length;
2144 Py_BEGIN_ALLOW_THREADS
2145 timeout = internal_select(s, 0);
2146 if (!timeout)
2147 n = recv(s->sock_fd, read_buf, segment, flags);
2148 Py_END_ALLOW_THREADS
2150 if (timeout) {
2151 Py_DECREF(buf);
2152 PyErr_SetString(socket_timeout, "timed out");
2153 return NULL;
2155 if (n < 0) {
2156 Py_DECREF(buf);
2157 return s->errorhandler();
2159 if (n != read_length) {
2160 read_buf += n;
2161 break;
2164 read_length -= segment;
2165 read_buf += segment;
2167 if (_PyString_Resize(&buf, (read_buf - PyString_AsString(buf))) < 0)
2169 return NULL;
2171 #endif /* !__VMS */
2172 return buf;
2175 PyDoc_STRVAR(recv_doc,
2176 "recv(buffersize[, flags]) -> data\n\
2178 Receive up to buffersize bytes from the socket. For the optional flags\n\
2179 argument, see the Unix manual. When no data is available, block until\n\
2180 at least one byte is available or until the remote end is closed. When\n\
2181 the remote end is closed and all data is read, return the empty string.");
2184 /* s.recvfrom(nbytes [,flags]) method */
2186 static PyObject *
2187 sock_recvfrom(PySocketSockObject *s, PyObject *args)
2189 sock_addr_t addrbuf;
2190 PyObject *buf = NULL;
2191 PyObject *addr = NULL;
2192 PyObject *ret = NULL;
2193 int len, n = 0, flags = 0, timeout;
2194 socklen_t addrlen;
2196 if (!PyArg_ParseTuple(args, "i|i:recvfrom", &len, &flags))
2197 return NULL;
2199 if (!getsockaddrlen(s, &addrlen))
2200 return NULL;
2201 buf = PyString_FromStringAndSize((char *) 0, len);
2202 if (buf == NULL)
2203 return NULL;
2205 if (!IS_SELECTABLE(s))
2206 return select_error();
2208 Py_BEGIN_ALLOW_THREADS
2209 memset(&addrbuf, 0, addrlen);
2210 timeout = internal_select(s, 0);
2211 if (!timeout)
2212 n = recvfrom(s->sock_fd, PyString_AS_STRING(buf), len, flags,
2213 #ifndef MS_WINDOWS
2214 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
2215 (struct sockaddr *) &addrbuf, &addrlen
2216 #else
2217 (void *) &addrbuf, &addrlen
2218 #endif
2219 #else
2220 (struct sockaddr *) &addrbuf, &addrlen
2221 #endif
2223 Py_END_ALLOW_THREADS
2225 if (timeout) {
2226 Py_DECREF(buf);
2227 PyErr_SetString(socket_timeout, "timed out");
2228 return NULL;
2230 if (n < 0) {
2231 Py_DECREF(buf);
2232 return s->errorhandler();
2235 if (n != len && _PyString_Resize(&buf, n) < 0)
2236 return NULL;
2238 if (!(addr = makesockaddr(s->sock_fd, (struct sockaddr *) &addrbuf,
2239 addrlen, s->sock_proto)))
2240 goto finally;
2242 ret = PyTuple_Pack(2, buf, addr);
2244 finally:
2245 Py_XDECREF(addr);
2246 Py_XDECREF(buf);
2247 return ret;
2250 PyDoc_STRVAR(recvfrom_doc,
2251 "recvfrom(buffersize[, flags]) -> (data, address info)\n\
2253 Like recv(buffersize, flags) but also return the sender's address info.");
2255 /* s.send(data [,flags]) method */
2257 static PyObject *
2258 sock_send(PySocketSockObject *s, PyObject *args)
2260 char *buf;
2261 int len, n = 0, flags = 0, timeout;
2262 #ifdef __VMS
2263 int send_length;
2264 #endif
2266 if (!PyArg_ParseTuple(args, "s#|i:send", &buf, &len, &flags))
2267 return NULL;
2269 if (!IS_SELECTABLE(s))
2270 return select_error();
2272 #ifndef __VMS
2273 Py_BEGIN_ALLOW_THREADS
2274 timeout = internal_select(s, 1);
2275 if (!timeout)
2276 n = send(s->sock_fd, buf, len, flags);
2277 Py_END_ALLOW_THREADS
2279 if (timeout) {
2280 PyErr_SetString(socket_timeout, "timed out");
2281 return NULL;
2283 if (n < 0)
2284 return s->errorhandler();
2285 #else
2286 /* Divide packet into smaller segments for */
2287 /* TCP/IP Services for OpenVMS */
2288 send_length = len;
2289 while (send_length != 0) {
2290 unsigned int segment;
2292 segment = send_length / SEGMENT_SIZE;
2293 if (segment != 0) {
2294 segment = SEGMENT_SIZE;
2296 else {
2297 segment = send_length;
2299 Py_BEGIN_ALLOW_THREADS
2300 timeout = internal_select(s, 1);
2301 if (!timeout)
2302 n = send(s->sock_fd, buf, segment, flags);
2303 Py_END_ALLOW_THREADS
2304 if (timeout) {
2305 PyErr_SetString(socket_timeout, "timed out");
2306 return NULL;
2308 if (n < 0) {
2309 return s->errorhandler();
2311 send_length -= segment;
2312 buf += segment;
2313 } /* end while */
2314 #endif /* !__VMS */
2315 return PyInt_FromLong((long)n);
2318 PyDoc_STRVAR(send_doc,
2319 "send(data[, flags]) -> count\n\
2321 Send a data string to the socket. For the optional flags\n\
2322 argument, see the Unix manual. Return the number of bytes\n\
2323 sent; this may be less than len(data) if the network is busy.");
2326 /* s.sendall(data [,flags]) method */
2328 static PyObject *
2329 sock_sendall(PySocketSockObject *s, PyObject *args)
2331 char *buf;
2332 int len, n = 0, flags = 0, timeout;
2334 if (!PyArg_ParseTuple(args, "s#|i:sendall", &buf, &len, &flags))
2335 return NULL;
2337 if (!IS_SELECTABLE(s))
2338 return select_error();
2340 Py_BEGIN_ALLOW_THREADS
2341 do {
2342 timeout = internal_select(s, 1);
2343 if (timeout)
2344 break;
2345 n = send(s->sock_fd, buf, len, flags);
2346 if (n < 0)
2347 break;
2348 buf += n;
2349 len -= n;
2350 } while (len > 0);
2351 Py_END_ALLOW_THREADS
2353 if (timeout) {
2354 PyErr_SetString(socket_timeout, "timed out");
2355 return NULL;
2357 if (n < 0)
2358 return s->errorhandler();
2360 Py_INCREF(Py_None);
2361 return Py_None;
2364 PyDoc_STRVAR(sendall_doc,
2365 "sendall(data[, flags])\n\
2367 Send a data string to the socket. For the optional flags\n\
2368 argument, see the Unix manual. This calls send() repeatedly\n\
2369 until all data is sent. If an error occurs, it's impossible\n\
2370 to tell how much data has been sent.");
2373 /* s.sendto(data, [flags,] sockaddr) method */
2375 static PyObject *
2376 sock_sendto(PySocketSockObject *s, PyObject *args)
2378 PyObject *addro;
2379 char *buf;
2380 struct sockaddr *addr;
2381 int addrlen, len, n = 0, flags, timeout;
2383 flags = 0;
2384 if (!PyArg_ParseTuple(args, "s#O:sendto", &buf, &len, &addro)) {
2385 PyErr_Clear();
2386 if (!PyArg_ParseTuple(args, "s#iO:sendto",
2387 &buf, &len, &flags, &addro))
2388 return NULL;
2391 if (!getsockaddrarg(s, addro, &addr, &addrlen))
2392 return NULL;
2394 if (!IS_SELECTABLE(s))
2395 return select_error();
2397 Py_BEGIN_ALLOW_THREADS
2398 timeout = internal_select(s, 1);
2399 if (!timeout)
2400 n = sendto(s->sock_fd, buf, len, flags, addr, addrlen);
2401 Py_END_ALLOW_THREADS
2403 if (timeout) {
2404 PyErr_SetString(socket_timeout, "timed out");
2405 return NULL;
2407 if (n < 0)
2408 return s->errorhandler();
2409 return PyInt_FromLong((long)n);
2412 PyDoc_STRVAR(sendto_doc,
2413 "sendto(data[, flags], address) -> count\n\
2415 Like send(data, flags) but allows specifying the destination address.\n\
2416 For IP sockets, the address is a pair (hostaddr, port).");
2419 /* s.shutdown(how) method */
2421 static PyObject *
2422 sock_shutdown(PySocketSockObject *s, PyObject *arg)
2424 int how;
2425 int res;
2427 how = PyInt_AsLong(arg);
2428 if (how == -1 && PyErr_Occurred())
2429 return NULL;
2430 Py_BEGIN_ALLOW_THREADS
2431 res = shutdown(s->sock_fd, how);
2432 Py_END_ALLOW_THREADS
2433 if (res < 0)
2434 return s->errorhandler();
2435 Py_INCREF(Py_None);
2436 return Py_None;
2439 PyDoc_STRVAR(shutdown_doc,
2440 "shutdown(flag)\n\
2442 Shut down the reading side of the socket (flag == SHUT_RD), the writing side\n\
2443 of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).");
2446 /* List of methods for socket objects */
2448 static PyMethodDef sock_methods[] = {
2449 {"accept", (PyCFunction)sock_accept, METH_NOARGS,
2450 accept_doc},
2451 {"bind", (PyCFunction)sock_bind, METH_O,
2452 bind_doc},
2453 {"close", (PyCFunction)sock_close, METH_NOARGS,
2454 close_doc},
2455 {"connect", (PyCFunction)sock_connect, METH_O,
2456 connect_doc},
2457 {"connect_ex", (PyCFunction)sock_connect_ex, METH_O,
2458 connect_ex_doc},
2459 #ifndef NO_DUP
2460 {"dup", (PyCFunction)sock_dup, METH_NOARGS,
2461 dup_doc},
2462 #endif
2463 {"fileno", (PyCFunction)sock_fileno, METH_NOARGS,
2464 fileno_doc},
2465 #ifdef HAVE_GETPEERNAME
2466 {"getpeername", (PyCFunction)sock_getpeername,
2467 METH_NOARGS, getpeername_doc},
2468 #endif
2469 {"getsockname", (PyCFunction)sock_getsockname,
2470 METH_NOARGS, getsockname_doc},
2471 {"getsockopt", (PyCFunction)sock_getsockopt, METH_VARARGS,
2472 getsockopt_doc},
2473 {"listen", (PyCFunction)sock_listen, METH_O,
2474 listen_doc},
2475 #ifndef NO_DUP
2476 {"makefile", (PyCFunction)sock_makefile, METH_VARARGS,
2477 makefile_doc},
2478 #endif
2479 {"recv", (PyCFunction)sock_recv, METH_VARARGS,
2480 recv_doc},
2481 {"recvfrom", (PyCFunction)sock_recvfrom, METH_VARARGS,
2482 recvfrom_doc},
2483 {"send", (PyCFunction)sock_send, METH_VARARGS,
2484 send_doc},
2485 {"sendall", (PyCFunction)sock_sendall, METH_VARARGS,
2486 sendall_doc},
2487 {"sendto", (PyCFunction)sock_sendto, METH_VARARGS,
2488 sendto_doc},
2489 {"setblocking", (PyCFunction)sock_setblocking, METH_O,
2490 setblocking_doc},
2491 {"settimeout", (PyCFunction)sock_settimeout, METH_O,
2492 settimeout_doc},
2493 {"gettimeout", (PyCFunction)sock_gettimeout, METH_NOARGS,
2494 gettimeout_doc},
2495 {"setsockopt", (PyCFunction)sock_setsockopt, METH_VARARGS,
2496 setsockopt_doc},
2497 {"shutdown", (PyCFunction)sock_shutdown, METH_O,
2498 shutdown_doc},
2499 #ifdef RISCOS
2500 {"sleeptaskw", (PyCFunction)sock_sleeptaskw, METH_O,
2501 sleeptaskw_doc},
2502 #endif
2503 {NULL, NULL} /* sentinel */
2506 /* SockObject members */
2507 static PyMemberDef sock_memberlist[] = {
2508 {"family", T_INT, offsetof(PySocketSockObject, sock_family), READONLY, "the socket family"},
2509 {"type", T_INT, offsetof(PySocketSockObject, sock_type), READONLY, "the socket type"},
2510 {"proto", T_INT, offsetof(PySocketSockObject, sock_proto), READONLY, "the socket protocol"},
2511 {"timeout", T_DOUBLE, offsetof(PySocketSockObject, sock_timeout), READONLY, "the socket timeout"},
2512 {0},
2515 /* Deallocate a socket object in response to the last Py_DECREF().
2516 First close the file description. */
2518 static void
2519 sock_dealloc(PySocketSockObject *s)
2521 if (s->sock_fd != -1)
2522 (void) SOCKETCLOSE(s->sock_fd);
2523 s->ob_type->tp_free((PyObject *)s);
2527 static PyObject *
2528 sock_repr(PySocketSockObject *s)
2530 char buf[512];
2531 #if SIZEOF_SOCKET_T > SIZEOF_LONG
2532 if (s->sock_fd > LONG_MAX) {
2533 /* this can occur on Win64, and actually there is a special
2534 ugly printf formatter for decimal pointer length integer
2535 printing, only bother if necessary*/
2536 PyErr_SetString(PyExc_OverflowError,
2537 "no printf formatter to display "
2538 "the socket descriptor in decimal");
2539 return NULL;
2541 #endif
2542 PyOS_snprintf(
2543 buf, sizeof(buf),
2544 "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
2545 (long)s->sock_fd, s->sock_family,
2546 s->sock_type,
2547 s->sock_proto);
2548 return PyString_FromString(buf);
2552 /* Create a new, uninitialized socket object. */
2554 static PyObject *
2555 sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2557 PyObject *new;
2559 new = type->tp_alloc(type, 0);
2560 if (new != NULL) {
2561 ((PySocketSockObject *)new)->sock_fd = -1;
2562 ((PySocketSockObject *)new)->sock_timeout = -1.0;
2563 ((PySocketSockObject *)new)->errorhandler = &set_error;
2565 return new;
2569 /* Initialize a new socket object. */
2571 /*ARGSUSED*/
2572 static int
2573 sock_initobj(PyObject *self, PyObject *args, PyObject *kwds)
2575 PySocketSockObject *s = (PySocketSockObject *)self;
2576 SOCKET_T fd;
2577 int family = AF_INET, type = SOCK_STREAM, proto = 0;
2578 static char *keywords[] = {"family", "type", "proto", 0};
2580 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2581 "|iii:socket", keywords,
2582 &family, &type, &proto))
2583 return -1;
2585 Py_BEGIN_ALLOW_THREADS
2586 fd = socket(family, type, proto);
2587 Py_END_ALLOW_THREADS
2589 #ifdef MS_WINDOWS
2590 if (fd == INVALID_SOCKET)
2591 #else
2592 if (fd < 0)
2593 #endif
2595 set_error();
2596 return -1;
2598 init_sockobject(s, fd, family, type, proto);
2600 return 0;
2605 /* Type object for socket objects. */
2607 static PyTypeObject sock_type = {
2608 PyObject_HEAD_INIT(0) /* Must fill in type value later */
2609 0, /* ob_size */
2610 "_socket.socket", /* tp_name */
2611 sizeof(PySocketSockObject), /* tp_basicsize */
2612 0, /* tp_itemsize */
2613 (destructor)sock_dealloc, /* tp_dealloc */
2614 0, /* tp_print */
2615 0, /* tp_getattr */
2616 0, /* tp_setattr */
2617 0, /* tp_compare */
2618 (reprfunc)sock_repr, /* tp_repr */
2619 0, /* tp_as_number */
2620 0, /* tp_as_sequence */
2621 0, /* tp_as_mapping */
2622 0, /* tp_hash */
2623 0, /* tp_call */
2624 0, /* tp_str */
2625 PyObject_GenericGetAttr, /* tp_getattro */
2626 0, /* tp_setattro */
2627 0, /* tp_as_buffer */
2628 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2629 sock_doc, /* tp_doc */
2630 0, /* tp_traverse */
2631 0, /* tp_clear */
2632 0, /* tp_richcompare */
2633 0, /* tp_weaklistoffset */
2634 0, /* tp_iter */
2635 0, /* tp_iternext */
2636 sock_methods, /* tp_methods */
2637 sock_memberlist, /* tp_members */
2638 0, /* tp_getset */
2639 0, /* tp_base */
2640 0, /* tp_dict */
2641 0, /* tp_descr_get */
2642 0, /* tp_descr_set */
2643 0, /* tp_dictoffset */
2644 sock_initobj, /* tp_init */
2645 PyType_GenericAlloc, /* tp_alloc */
2646 sock_new, /* tp_new */
2647 PyObject_Del, /* tp_free */
2651 /* Python interface to gethostname(). */
2653 /*ARGSUSED*/
2654 static PyObject *
2655 socket_gethostname(PyObject *self, PyObject *args)
2657 char buf[1024];
2658 int res;
2659 if (!PyArg_ParseTuple(args, ":gethostname"))
2660 return NULL;
2661 Py_BEGIN_ALLOW_THREADS
2662 res = gethostname(buf, (int) sizeof buf - 1);
2663 Py_END_ALLOW_THREADS
2664 if (res < 0)
2665 return set_error();
2666 buf[sizeof buf - 1] = '\0';
2667 return PyString_FromString(buf);
2670 PyDoc_STRVAR(gethostname_doc,
2671 "gethostname() -> string\n\
2673 Return the current host name.");
2676 /* Python interface to gethostbyname(name). */
2678 /*ARGSUSED*/
2679 static PyObject *
2680 socket_gethostbyname(PyObject *self, PyObject *args)
2682 char *name;
2683 sock_addr_t addrbuf;
2685 if (!PyArg_ParseTuple(args, "s:gethostbyname", &name))
2686 return NULL;
2687 if (setipaddr(name, (struct sockaddr *)&addrbuf, sizeof(addrbuf), AF_INET) < 0)
2688 return NULL;
2689 return makeipaddr((struct sockaddr *)&addrbuf,
2690 sizeof(struct sockaddr_in));
2693 PyDoc_STRVAR(gethostbyname_doc,
2694 "gethostbyname(host) -> address\n\
2696 Return the IP address (a string of the form '255.255.255.255') for a host.");
2699 /* Convenience function common to gethostbyname_ex and gethostbyaddr */
2701 static PyObject *
2702 gethost_common(struct hostent *h, struct sockaddr *addr, int alen, int af)
2704 char **pch;
2705 PyObject *rtn_tuple = (PyObject *)NULL;
2706 PyObject *name_list = (PyObject *)NULL;
2707 PyObject *addr_list = (PyObject *)NULL;
2708 PyObject *tmp;
2710 if (h == NULL) {
2711 /* Let's get real error message to return */
2712 #ifndef RISCOS
2713 set_herror(h_errno);
2714 #else
2715 PyErr_SetString(socket_error, "host not found");
2716 #endif
2717 return NULL;
2720 if (h->h_addrtype != af) {
2721 #ifdef HAVE_STRERROR
2722 /* Let's get real error message to return */
2723 PyErr_SetString(socket_error,
2724 (char *)strerror(EAFNOSUPPORT));
2725 #else
2726 PyErr_SetString(
2727 socket_error,
2728 "Address family not supported by protocol family");
2729 #endif
2730 return NULL;
2733 switch (af) {
2735 case AF_INET:
2736 if (alen < sizeof(struct sockaddr_in))
2737 return NULL;
2738 break;
2740 #ifdef ENABLE_IPV6
2741 case AF_INET6:
2742 if (alen < sizeof(struct sockaddr_in6))
2743 return NULL;
2744 break;
2745 #endif
2749 if ((name_list = PyList_New(0)) == NULL)
2750 goto err;
2752 if ((addr_list = PyList_New(0)) == NULL)
2753 goto err;
2755 for (pch = h->h_aliases; *pch != NULL; pch++) {
2756 int status;
2757 tmp = PyString_FromString(*pch);
2758 if (tmp == NULL)
2759 goto err;
2761 status = PyList_Append(name_list, tmp);
2762 Py_DECREF(tmp);
2764 if (status)
2765 goto err;
2768 for (pch = h->h_addr_list; *pch != NULL; pch++) {
2769 int status;
2771 switch (af) {
2773 case AF_INET:
2775 struct sockaddr_in sin;
2776 memset(&sin, 0, sizeof(sin));
2777 sin.sin_family = af;
2778 #ifdef HAVE_SOCKADDR_SA_LEN
2779 sin.sin_len = sizeof(sin);
2780 #endif
2781 memcpy(&sin.sin_addr, *pch, sizeof(sin.sin_addr));
2782 tmp = makeipaddr((struct sockaddr *)&sin, sizeof(sin));
2784 if (pch == h->h_addr_list && alen >= sizeof(sin))
2785 memcpy((char *) addr, &sin, sizeof(sin));
2786 break;
2789 #ifdef ENABLE_IPV6
2790 case AF_INET6:
2792 struct sockaddr_in6 sin6;
2793 memset(&sin6, 0, sizeof(sin6));
2794 sin6.sin6_family = af;
2795 #ifdef HAVE_SOCKADDR_SA_LEN
2796 sin6.sin6_len = sizeof(sin6);
2797 #endif
2798 memcpy(&sin6.sin6_addr, *pch, sizeof(sin6.sin6_addr));
2799 tmp = makeipaddr((struct sockaddr *)&sin6,
2800 sizeof(sin6));
2802 if (pch == h->h_addr_list && alen >= sizeof(sin6))
2803 memcpy((char *) addr, &sin6, sizeof(sin6));
2804 break;
2806 #endif
2808 default: /* can't happen */
2809 PyErr_SetString(socket_error,
2810 "unsupported address family");
2811 return NULL;
2814 if (tmp == NULL)
2815 goto err;
2817 status = PyList_Append(addr_list, tmp);
2818 Py_DECREF(tmp);
2820 if (status)
2821 goto err;
2824 rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list);
2826 err:
2827 Py_XDECREF(name_list);
2828 Py_XDECREF(addr_list);
2829 return rtn_tuple;
2833 /* Python interface to gethostbyname_ex(name). */
2835 /*ARGSUSED*/
2836 static PyObject *
2837 socket_gethostbyname_ex(PyObject *self, PyObject *args)
2839 char *name;
2840 struct hostent *h;
2841 #ifdef ENABLE_IPV6
2842 struct sockaddr_storage addr;
2843 #else
2844 struct sockaddr_in addr;
2845 #endif
2846 struct sockaddr *sa;
2847 PyObject *ret;
2848 #ifdef HAVE_GETHOSTBYNAME_R
2849 struct hostent hp_allocated;
2850 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
2851 struct hostent_data data;
2852 #else
2853 char buf[16384];
2854 int buf_len = (sizeof buf) - 1;
2855 int errnop;
2856 #endif
2857 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2858 int result;
2859 #endif
2860 #endif /* HAVE_GETHOSTBYNAME_R */
2862 if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name))
2863 return NULL;
2864 if (setipaddr(name, (struct sockaddr *)&addr, sizeof(addr), AF_INET) < 0)
2865 return NULL;
2866 Py_BEGIN_ALLOW_THREADS
2867 #ifdef HAVE_GETHOSTBYNAME_R
2868 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2869 result = gethostbyname_r(name, &hp_allocated, buf, buf_len,
2870 &h, &errnop);
2871 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
2872 h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
2873 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
2874 memset((void *) &data, '\0', sizeof(data));
2875 result = gethostbyname_r(name, &hp_allocated, &data);
2876 h = (result != 0) ? NULL : &hp_allocated;
2877 #endif
2878 #else /* not HAVE_GETHOSTBYNAME_R */
2879 #ifdef USE_GETHOSTBYNAME_LOCK
2880 PyThread_acquire_lock(netdb_lock, 1);
2881 #endif
2882 h = gethostbyname(name);
2883 #endif /* HAVE_GETHOSTBYNAME_R */
2884 Py_END_ALLOW_THREADS
2885 /* Some C libraries would require addr.__ss_family instead of
2886 addr.ss_family.
2887 Therefore, we cast the sockaddr_storage into sockaddr to
2888 access sa_family. */
2889 sa = (struct sockaddr*)&addr;
2890 ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr),
2891 sa->sa_family);
2892 #ifdef USE_GETHOSTBYNAME_LOCK
2893 PyThread_release_lock(netdb_lock);
2894 #endif
2895 return ret;
2898 PyDoc_STRVAR(ghbn_ex_doc,
2899 "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
2901 Return the true host name, a list of aliases, and a list of IP addresses,\n\
2902 for a host. The host argument is a string giving a host name or IP number.");
2905 /* Python interface to gethostbyaddr(IP). */
2907 /*ARGSUSED*/
2908 static PyObject *
2909 socket_gethostbyaddr(PyObject *self, PyObject *args)
2911 #ifdef ENABLE_IPV6
2912 struct sockaddr_storage addr;
2913 #else
2914 struct sockaddr_in addr;
2915 #endif
2916 struct sockaddr *sa = (struct sockaddr *)&addr;
2917 char *ip_num;
2918 struct hostent *h;
2919 PyObject *ret;
2920 #ifdef HAVE_GETHOSTBYNAME_R
2921 struct hostent hp_allocated;
2922 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
2923 struct hostent_data data;
2924 #else
2925 char buf[16384];
2926 int buf_len = (sizeof buf) - 1;
2927 int errnop;
2928 #endif
2929 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2930 int result;
2931 #endif
2932 #endif /* HAVE_GETHOSTBYNAME_R */
2933 char *ap;
2934 int al;
2935 int af;
2937 if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num))
2938 return NULL;
2939 af = AF_UNSPEC;
2940 if (setipaddr(ip_num, sa, sizeof(addr), af) < 0)
2941 return NULL;
2942 af = sa->sa_family;
2943 ap = NULL;
2944 al = 0;
2945 switch (af) {
2946 case AF_INET:
2947 ap = (char *)&((struct sockaddr_in *)sa)->sin_addr;
2948 al = sizeof(((struct sockaddr_in *)sa)->sin_addr);
2949 break;
2950 #ifdef ENABLE_IPV6
2951 case AF_INET6:
2952 ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr;
2953 al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr);
2954 break;
2955 #endif
2956 default:
2957 PyErr_SetString(socket_error, "unsupported address family");
2958 return NULL;
2960 Py_BEGIN_ALLOW_THREADS
2961 #ifdef HAVE_GETHOSTBYNAME_R
2962 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2963 result = gethostbyaddr_r(ap, al, af,
2964 &hp_allocated, buf, buf_len,
2965 &h, &errnop);
2966 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
2967 h = gethostbyaddr_r(ap, al, af,
2968 &hp_allocated, buf, buf_len, &errnop);
2969 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
2970 memset((void *) &data, '\0', sizeof(data));
2971 result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data);
2972 h = (result != 0) ? NULL : &hp_allocated;
2973 #endif
2974 #else /* not HAVE_GETHOSTBYNAME_R */
2975 #ifdef USE_GETHOSTBYNAME_LOCK
2976 PyThread_acquire_lock(netdb_lock, 1);
2977 #endif
2978 h = gethostbyaddr(ap, al, af);
2979 #endif /* HAVE_GETHOSTBYNAME_R */
2980 Py_END_ALLOW_THREADS
2981 ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), af);
2982 #ifdef USE_GETHOSTBYNAME_LOCK
2983 PyThread_release_lock(netdb_lock);
2984 #endif
2985 return ret;
2988 PyDoc_STRVAR(gethostbyaddr_doc,
2989 "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
2991 Return the true host name, a list of aliases, and a list of IP addresses,\n\
2992 for a host. The host argument is a string giving a host name or IP number.");
2995 /* Python interface to getservbyname(name).
2996 This only returns the port number, since the other info is already
2997 known or not useful (like the list of aliases). */
2999 /*ARGSUSED*/
3000 static PyObject *
3001 socket_getservbyname(PyObject *self, PyObject *args)
3003 char *name, *proto=NULL;
3004 struct servent *sp;
3005 if (!PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto))
3006 return NULL;
3007 Py_BEGIN_ALLOW_THREADS
3008 sp = getservbyname(name, proto);
3009 Py_END_ALLOW_THREADS
3010 if (sp == NULL) {
3011 PyErr_SetString(socket_error, "service/proto not found");
3012 return NULL;
3014 return PyInt_FromLong((long) ntohs(sp->s_port));
3017 PyDoc_STRVAR(getservbyname_doc,
3018 "getservbyname(servicename[, protocolname]) -> integer\n\
3020 Return a port number from a service name and protocol name.\n\
3021 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3022 otherwise any protocol will match.");
3025 /* Python interface to getservbyport(port).
3026 This only returns the service name, since the other info is already
3027 known or not useful (like the list of aliases). */
3029 /*ARGSUSED*/
3030 static PyObject *
3031 socket_getservbyport(PyObject *self, PyObject *args)
3033 unsigned short port;
3034 char *proto=NULL;
3035 struct servent *sp;
3036 if (!PyArg_ParseTuple(args, "H|s:getservbyport", &port, &proto))
3037 return NULL;
3038 Py_BEGIN_ALLOW_THREADS
3039 sp = getservbyport(htons(port), proto);
3040 Py_END_ALLOW_THREADS
3041 if (sp == NULL) {
3042 PyErr_SetString(socket_error, "port/proto not found");
3043 return NULL;
3045 return PyString_FromString(sp->s_name);
3048 PyDoc_STRVAR(getservbyport_doc,
3049 "getservbyport(port[, protocolname]) -> string\n\
3051 Return the service name from a port number and protocol name.\n\
3052 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3053 otherwise any protocol will match.");
3055 /* Python interface to getprotobyname(name).
3056 This only returns the protocol number, since the other info is
3057 already known or not useful (like the list of aliases). */
3059 /*ARGSUSED*/
3060 static PyObject *
3061 socket_getprotobyname(PyObject *self, PyObject *args)
3063 char *name;
3064 struct protoent *sp;
3065 #ifdef __BEOS__
3066 /* Not available in BeOS yet. - [cjh] */
3067 PyErr_SetString(socket_error, "getprotobyname not supported");
3068 return NULL;
3069 #else
3070 if (!PyArg_ParseTuple(args, "s:getprotobyname", &name))
3071 return NULL;
3072 Py_BEGIN_ALLOW_THREADS
3073 sp = getprotobyname(name);
3074 Py_END_ALLOW_THREADS
3075 if (sp == NULL) {
3076 PyErr_SetString(socket_error, "protocol not found");
3077 return NULL;
3079 return PyInt_FromLong((long) sp->p_proto);
3080 #endif
3083 PyDoc_STRVAR(getprotobyname_doc,
3084 "getprotobyname(name) -> integer\n\
3086 Return the protocol number for the named protocol. (Rarely used.)");
3089 #ifdef HAVE_SOCKETPAIR
3090 /* Create a pair of sockets using the socketpair() function.
3091 Arguments as for socket() except the default family is AF_UNIX if
3092 defined on the platform; otherwise, the default is AF_INET. */
3094 /*ARGSUSED*/
3095 static PyObject *
3096 socket_socketpair(PyObject *self, PyObject *args)
3098 PySocketSockObject *s0 = NULL, *s1 = NULL;
3099 SOCKET_T sv[2];
3100 int family, type = SOCK_STREAM, proto = 0;
3101 PyObject *res = NULL;
3103 #if defined(AF_UNIX)
3104 family = AF_UNIX;
3105 #else
3106 family = AF_INET;
3107 #endif
3108 if (!PyArg_ParseTuple(args, "|iii:socketpair",
3109 &family, &type, &proto))
3110 return NULL;
3111 /* Create a pair of socket fds */
3112 if (socketpair(family, type, proto, sv) < 0)
3113 return set_error();
3114 s0 = new_sockobject(sv[0], family, type, proto);
3115 if (s0 == NULL)
3116 goto finally;
3117 s1 = new_sockobject(sv[1], family, type, proto);
3118 if (s1 == NULL)
3119 goto finally;
3120 res = PyTuple_Pack(2, s0, s1);
3122 finally:
3123 if (res == NULL) {
3124 if (s0 == NULL)
3125 SOCKETCLOSE(sv[0]);
3126 if (s1 == NULL)
3127 SOCKETCLOSE(sv[1]);
3129 Py_XDECREF(s0);
3130 Py_XDECREF(s1);
3131 return res;
3134 PyDoc_STRVAR(socketpair_doc,
3135 "socketpair([family[, type[, proto]]]) -> (socket object, socket object)\n\
3137 Create a pair of socket objects from the sockets returned by the platform\n\
3138 socketpair() function.\n\
3139 The arguments are the same as for socket() except the default family is\n\
3140 AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");
3142 #endif /* HAVE_SOCKETPAIR */
3145 #ifndef NO_DUP
3146 /* Create a socket object from a numeric file description.
3147 Useful e.g. if stdin is a socket.
3148 Additional arguments as for socket(). */
3150 /*ARGSUSED*/
3151 static PyObject *
3152 socket_fromfd(PyObject *self, PyObject *args)
3154 PySocketSockObject *s;
3155 SOCKET_T fd;
3156 int family, type, proto = 0;
3157 if (!PyArg_ParseTuple(args, "iii|i:fromfd",
3158 &fd, &family, &type, &proto))
3159 return NULL;
3160 /* Dup the fd so it and the socket can be closed independently */
3161 fd = dup(fd);
3162 if (fd < 0)
3163 return set_error();
3164 s = new_sockobject(fd, family, type, proto);
3165 return (PyObject *) s;
3168 PyDoc_STRVAR(fromfd_doc,
3169 "fromfd(fd, family, type[, proto]) -> socket object\n\
3171 Create a socket object from a duplicate of the given\n\
3172 file descriptor.\n\
3173 The remaining arguments are the same as for socket().");
3175 #endif /* NO_DUP */
3178 static PyObject *
3179 socket_ntohs(PyObject *self, PyObject *args)
3181 int x1, x2;
3183 if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) {
3184 return NULL;
3186 x2 = (int)ntohs((short)x1);
3187 return PyInt_FromLong(x2);
3190 PyDoc_STRVAR(ntohs_doc,
3191 "ntohs(integer) -> integer\n\
3193 Convert a 16-bit integer from network to host byte order.");
3196 static PyObject *
3197 socket_ntohl(PyObject *self, PyObject *arg)
3199 unsigned long x;
3201 if (PyInt_Check(arg)) {
3202 x = PyInt_AS_LONG(arg);
3203 if (x == (unsigned long) -1 && PyErr_Occurred())
3204 return NULL;
3206 else if (PyLong_Check(arg)) {
3207 x = PyLong_AsUnsignedLong(arg);
3208 if (x == (unsigned long) -1 && PyErr_Occurred())
3209 return NULL;
3210 #if SIZEOF_LONG > 4
3212 unsigned long y;
3213 /* only want the trailing 32 bits */
3214 y = x & 0xFFFFFFFFUL;
3215 if (y ^ x)
3216 return PyErr_Format(PyExc_OverflowError,
3217 "long int larger than 32 bits");
3218 x = y;
3220 #endif
3222 else
3223 return PyErr_Format(PyExc_TypeError,
3224 "expected int/long, %s found",
3225 arg->ob_type->tp_name);
3226 if (x == (unsigned long) -1 && PyErr_Occurred())
3227 return NULL;
3228 return PyInt_FromLong(ntohl(x));
3231 PyDoc_STRVAR(ntohl_doc,
3232 "ntohl(integer) -> integer\n\
3234 Convert a 32-bit integer from network to host byte order.");
3237 static PyObject *
3238 socket_htons(PyObject *self, PyObject *args)
3240 int x1, x2;
3242 if (!PyArg_ParseTuple(args, "i:htons", &x1)) {
3243 return NULL;
3245 x2 = (int)htons((short)x1);
3246 return PyInt_FromLong(x2);
3249 PyDoc_STRVAR(htons_doc,
3250 "htons(integer) -> integer\n\
3252 Convert a 16-bit integer from host to network byte order.");
3255 static PyObject *
3256 socket_htonl(PyObject *self, PyObject *arg)
3258 unsigned long x;
3260 if (PyInt_Check(arg)) {
3261 x = PyInt_AS_LONG(arg);
3262 if (x == (unsigned long) -1 && PyErr_Occurred())
3263 return NULL;
3265 else if (PyLong_Check(arg)) {
3266 x = PyLong_AsUnsignedLong(arg);
3267 if (x == (unsigned long) -1 && PyErr_Occurred())
3268 return NULL;
3269 #if SIZEOF_LONG > 4
3271 unsigned long y;
3272 /* only want the trailing 32 bits */
3273 y = x & 0xFFFFFFFFUL;
3274 if (y ^ x)
3275 return PyErr_Format(PyExc_OverflowError,
3276 "long int larger than 32 bits");
3277 x = y;
3279 #endif
3281 else
3282 return PyErr_Format(PyExc_TypeError,
3283 "expected int/long, %s found",
3284 arg->ob_type->tp_name);
3285 return PyInt_FromLong(htonl(x));
3288 PyDoc_STRVAR(htonl_doc,
3289 "htonl(integer) -> integer\n\
3291 Convert a 32-bit integer from host to network byte order.");
3293 /* socket.inet_aton() and socket.inet_ntoa() functions. */
3295 PyDoc_STRVAR(inet_aton_doc,
3296 "inet_aton(string) -> packed 32-bit IP representation\n\
3298 Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
3299 binary format used in low-level network functions.");
3301 static PyObject*
3302 socket_inet_aton(PyObject *self, PyObject *args)
3304 #ifndef INADDR_NONE
3305 #define INADDR_NONE (-1)
3306 #endif
3307 #ifdef HAVE_INET_ATON
3308 struct in_addr buf;
3309 #else
3310 /* Have to use inet_addr() instead */
3311 unsigned long packed_addr;
3312 #endif
3313 char *ip_addr;
3315 if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr))
3316 return NULL;
3319 #ifdef HAVE_INET_ATON
3320 if (inet_aton(ip_addr, &buf))
3321 return PyString_FromStringAndSize((char *)(&buf),
3322 sizeof(buf));
3324 PyErr_SetString(socket_error,
3325 "illegal IP address string passed to inet_aton");
3326 return NULL;
3328 #else /* ! HAVE_INET_ATON */
3329 /* special-case this address as inet_addr might return INADDR_NONE
3330 * for this */
3331 if (strcmp(ip_addr, "255.255.255.255") == 0) {
3332 packed_addr = 0xFFFFFFFF;
3333 } else {
3335 packed_addr = inet_addr(ip_addr);
3337 if (packed_addr == INADDR_NONE) { /* invalid address */
3338 PyErr_SetString(socket_error,
3339 "illegal IP address string passed to inet_aton");
3340 return NULL;
3343 return PyString_FromStringAndSize((char *) &packed_addr,
3344 sizeof(packed_addr));
3345 #endif
3348 PyDoc_STRVAR(inet_ntoa_doc,
3349 "inet_ntoa(packed_ip) -> ip_address_string\n\
3351 Convert an IP address from 32-bit packed binary format to string format");
3353 static PyObject*
3354 socket_inet_ntoa(PyObject *self, PyObject *args)
3356 char *packed_str;
3357 int addr_len;
3358 struct in_addr packed_addr;
3360 if (!PyArg_ParseTuple(args, "s#:inet_ntoa", &packed_str, &addr_len)) {
3361 return NULL;
3364 if (addr_len != sizeof(packed_addr)) {
3365 PyErr_SetString(socket_error,
3366 "packed IP wrong length for inet_ntoa");
3367 return NULL;
3370 memcpy(&packed_addr, packed_str, addr_len);
3372 return PyString_FromString(inet_ntoa(packed_addr));
3375 #ifdef HAVE_INET_PTON
3377 PyDoc_STRVAR(inet_pton_doc,
3378 "inet_pton(af, ip) -> packed IP address string\n\
3380 Convert an IP address from string format to a packed string suitable\n\
3381 for use with low-level network functions.");
3383 static PyObject *
3384 socket_inet_pton(PyObject *self, PyObject *args)
3386 int af;
3387 char* ip;
3388 int retval;
3389 #ifdef ENABLE_IPV6
3390 char packed[MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
3391 #else
3392 char packed[sizeof(struct in_addr)];
3393 #endif
3394 if (!PyArg_ParseTuple(args, "is:inet_pton", &af, &ip)) {
3395 return NULL;
3398 #if !defined(ENABLE_IPV6) && defined(AF_INET6)
3399 if(af == AF_INET6) {
3400 PyErr_SetString(socket_error,
3401 "can't use AF_INET6, IPv6 is disabled");
3402 return NULL;
3404 #endif
3406 retval = inet_pton(af, ip, packed);
3407 if (retval < 0) {
3408 PyErr_SetFromErrno(socket_error);
3409 return NULL;
3410 } else if (retval == 0) {
3411 PyErr_SetString(socket_error,
3412 "illegal IP address string passed to inet_pton");
3413 return NULL;
3414 } else if (af == AF_INET) {
3415 return PyString_FromStringAndSize(packed,
3416 sizeof(struct in_addr));
3417 #ifdef ENABLE_IPV6
3418 } else if (af == AF_INET6) {
3419 return PyString_FromStringAndSize(packed,
3420 sizeof(struct in6_addr));
3421 #endif
3422 } else {
3423 PyErr_SetString(socket_error, "unknown address family");
3424 return NULL;
3428 PyDoc_STRVAR(inet_ntop_doc,
3429 "inet_ntop(af, packed_ip) -> string formatted IP address\n\
3431 Convert a packed IP address of the given family to string format.");
3433 static PyObject *
3434 socket_inet_ntop(PyObject *self, PyObject *args)
3436 int af;
3437 char* packed;
3438 int len;
3439 const char* retval;
3440 #ifdef ENABLE_IPV6
3441 char ip[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) + 1];
3442 #else
3443 char ip[INET_ADDRSTRLEN + 1];
3444 #endif
3446 /* Guarantee NUL-termination for PyString_FromString() below */
3447 memset((void *) &ip[0], '\0', sizeof(ip));
3449 if (!PyArg_ParseTuple(args, "is#:inet_ntop", &af, &packed, &len)) {
3450 return NULL;
3453 if (af == AF_INET) {
3454 if (len != sizeof(struct in_addr)) {
3455 PyErr_SetString(PyExc_ValueError,
3456 "invalid length of packed IP address string");
3457 return NULL;
3459 #ifdef ENABLE_IPV6
3460 } else if (af == AF_INET6) {
3461 if (len != sizeof(struct in6_addr)) {
3462 PyErr_SetString(PyExc_ValueError,
3463 "invalid length of packed IP address string");
3464 return NULL;
3466 #endif
3467 } else {
3468 PyErr_Format(PyExc_ValueError,
3469 "unknown address family %d", af);
3470 return NULL;
3473 retval = inet_ntop(af, packed, ip, sizeof(ip));
3474 if (!retval) {
3475 PyErr_SetFromErrno(socket_error);
3476 return NULL;
3477 } else {
3478 return PyString_FromString(retval);
3481 /* NOTREACHED */
3482 PyErr_SetString(PyExc_RuntimeError, "invalid handling of inet_ntop");
3483 return NULL;
3486 #endif /* HAVE_INET_PTON */
3488 /* Python interface to getaddrinfo(host, port). */
3490 /*ARGSUSED*/
3491 static PyObject *
3492 socket_getaddrinfo(PyObject *self, PyObject *args)
3494 struct addrinfo hints, *res;
3495 struct addrinfo *res0 = NULL;
3496 PyObject *hobj = NULL;
3497 PyObject *pobj = (PyObject *)NULL;
3498 char pbuf[30];
3499 char *hptr, *pptr;
3500 int family, socktype, protocol, flags;
3501 int error;
3502 PyObject *all = (PyObject *)NULL;
3503 PyObject *single = (PyObject *)NULL;
3504 PyObject *idna = NULL;
3506 family = socktype = protocol = flags = 0;
3507 family = AF_UNSPEC;
3508 if (!PyArg_ParseTuple(args, "OO|iiii:getaddrinfo",
3509 &hobj, &pobj, &family, &socktype,
3510 &protocol, &flags)) {
3511 return NULL;
3513 if (hobj == Py_None) {
3514 hptr = NULL;
3515 } else if (PyUnicode_Check(hobj)) {
3516 idna = PyObject_CallMethod(hobj, "encode", "s", "idna");
3517 if (!idna)
3518 return NULL;
3519 hptr = PyString_AsString(idna);
3520 } else if (PyString_Check(hobj)) {
3521 hptr = PyString_AsString(hobj);
3522 } else {
3523 PyErr_SetString(PyExc_TypeError,
3524 "getaddrinfo() argument 1 must be string or None");
3525 return NULL;
3527 if (PyInt_Check(pobj)) {
3528 PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", PyInt_AsLong(pobj));
3529 pptr = pbuf;
3530 } else if (PyString_Check(pobj)) {
3531 pptr = PyString_AsString(pobj);
3532 } else if (pobj == Py_None) {
3533 pptr = (char *)NULL;
3534 } else {
3535 PyErr_SetString(socket_error, "Int or String expected");
3536 goto err;
3538 memset(&hints, 0, sizeof(hints));
3539 hints.ai_family = family;
3540 hints.ai_socktype = socktype;
3541 hints.ai_protocol = protocol;
3542 hints.ai_flags = flags;
3543 Py_BEGIN_ALLOW_THREADS
3544 ACQUIRE_GETADDRINFO_LOCK
3545 error = getaddrinfo(hptr, pptr, &hints, &res0);
3546 Py_END_ALLOW_THREADS
3547 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
3548 if (error) {
3549 set_gaierror(error);
3550 goto err;
3553 if ((all = PyList_New(0)) == NULL)
3554 goto err;
3555 for (res = res0; res; res = res->ai_next) {
3556 PyObject *addr =
3557 makesockaddr(-1, res->ai_addr, res->ai_addrlen, protocol);
3558 if (addr == NULL)
3559 goto err;
3560 single = Py_BuildValue("iiisO", res->ai_family,
3561 res->ai_socktype, res->ai_protocol,
3562 res->ai_canonname ? res->ai_canonname : "",
3563 addr);
3564 Py_DECREF(addr);
3565 if (single == NULL)
3566 goto err;
3568 if (PyList_Append(all, single))
3569 goto err;
3570 Py_XDECREF(single);
3572 Py_XDECREF(idna);
3573 if (res0)
3574 freeaddrinfo(res0);
3575 return all;
3576 err:
3577 Py_XDECREF(single);
3578 Py_XDECREF(all);
3579 Py_XDECREF(idna);
3580 if (res0)
3581 freeaddrinfo(res0);
3582 return (PyObject *)NULL;
3585 PyDoc_STRVAR(getaddrinfo_doc,
3586 "getaddrinfo(host, port [, family, socktype, proto, flags])\n\
3587 -> list of (family, socktype, proto, canonname, sockaddr)\n\
3589 Resolve host and port into addrinfo struct.");
3591 /* Python interface to getnameinfo(sa, flags). */
3593 /*ARGSUSED*/
3594 static PyObject *
3595 socket_getnameinfo(PyObject *self, PyObject *args)
3597 PyObject *sa = (PyObject *)NULL;
3598 int flags;
3599 char *hostp;
3600 int port, flowinfo, scope_id;
3601 char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
3602 struct addrinfo hints, *res = NULL;
3603 int error;
3604 PyObject *ret = (PyObject *)NULL;
3606 flags = flowinfo = scope_id = 0;
3607 if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags))
3608 return NULL;
3609 if (!PyArg_ParseTuple(sa, "si|ii",
3610 &hostp, &port, &flowinfo, &scope_id))
3611 return NULL;
3612 PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port);
3613 memset(&hints, 0, sizeof(hints));
3614 hints.ai_family = AF_UNSPEC;
3615 hints.ai_socktype = SOCK_DGRAM; /* make numeric port happy */
3616 Py_BEGIN_ALLOW_THREADS
3617 ACQUIRE_GETADDRINFO_LOCK
3618 error = getaddrinfo(hostp, pbuf, &hints, &res);
3619 Py_END_ALLOW_THREADS
3620 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
3621 if (error) {
3622 set_gaierror(error);
3623 goto fail;
3625 if (res->ai_next) {
3626 PyErr_SetString(socket_error,
3627 "sockaddr resolved to multiple addresses");
3628 goto fail;
3630 switch (res->ai_family) {
3631 case AF_INET:
3633 char *t1;
3634 int t2;
3635 if (PyArg_ParseTuple(sa, "si", &t1, &t2) == 0) {
3636 PyErr_SetString(socket_error,
3637 "IPv4 sockaddr must be 2 tuple");
3638 goto fail;
3640 break;
3642 #ifdef ENABLE_IPV6
3643 case AF_INET6:
3645 struct sockaddr_in6 *sin6;
3646 sin6 = (struct sockaddr_in6 *)res->ai_addr;
3647 sin6->sin6_flowinfo = flowinfo;
3648 sin6->sin6_scope_id = scope_id;
3649 break;
3651 #endif
3653 error = getnameinfo(res->ai_addr, res->ai_addrlen,
3654 hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags);
3655 if (error) {
3656 set_gaierror(error);
3657 goto fail;
3659 ret = Py_BuildValue("ss", hbuf, pbuf);
3661 fail:
3662 if (res)
3663 freeaddrinfo(res);
3664 return ret;
3667 PyDoc_STRVAR(getnameinfo_doc,
3668 "getnameinfo(sockaddr, flags) --> (host, port)\n\
3670 Get host and port for a sockaddr.");
3673 /* Python API to getting and setting the default timeout value. */
3675 static PyObject *
3676 socket_getdefaulttimeout(PyObject *self)
3678 if (defaulttimeout < 0.0) {
3679 Py_INCREF(Py_None);
3680 return Py_None;
3682 else
3683 return PyFloat_FromDouble(defaulttimeout);
3686 PyDoc_STRVAR(getdefaulttimeout_doc,
3687 "getdefaulttimeout() -> timeout\n\
3689 Returns the default timeout in floating seconds for new socket objects.\n\
3690 A value of None indicates that new socket objects have no timeout.\n\
3691 When the socket module is first imported, the default is None.");
3693 static PyObject *
3694 socket_setdefaulttimeout(PyObject *self, PyObject *arg)
3696 double timeout;
3698 if (arg == Py_None)
3699 timeout = -1.0;
3700 else {
3701 timeout = PyFloat_AsDouble(arg);
3702 if (timeout < 0.0) {
3703 if (!PyErr_Occurred())
3704 PyErr_SetString(PyExc_ValueError,
3705 "Timeout value out of range");
3706 return NULL;
3710 defaulttimeout = timeout;
3712 Py_INCREF(Py_None);
3713 return Py_None;
3716 PyDoc_STRVAR(setdefaulttimeout_doc,
3717 "setdefaulttimeout(timeout)\n\
3719 Set the default timeout in floating seconds for new socket objects.\n\
3720 A value of None indicates that new socket objects have no timeout.\n\
3721 When the socket module is first imported, the default is None.");
3724 /* List of functions exported by this module. */
3726 static PyMethodDef socket_methods[] = {
3727 {"gethostbyname", socket_gethostbyname,
3728 METH_VARARGS, gethostbyname_doc},
3729 {"gethostbyname_ex", socket_gethostbyname_ex,
3730 METH_VARARGS, ghbn_ex_doc},
3731 {"gethostbyaddr", socket_gethostbyaddr,
3732 METH_VARARGS, gethostbyaddr_doc},
3733 {"gethostname", socket_gethostname,
3734 METH_VARARGS, gethostname_doc},
3735 {"getservbyname", socket_getservbyname,
3736 METH_VARARGS, getservbyname_doc},
3737 {"getservbyport", socket_getservbyport,
3738 METH_VARARGS, getservbyport_doc},
3739 {"getprotobyname", socket_getprotobyname,
3740 METH_VARARGS,getprotobyname_doc},
3741 #ifndef NO_DUP
3742 {"fromfd", socket_fromfd,
3743 METH_VARARGS, fromfd_doc},
3744 #endif
3745 #ifdef HAVE_SOCKETPAIR
3746 {"socketpair", socket_socketpair,
3747 METH_VARARGS, socketpair_doc},
3748 #endif
3749 {"ntohs", socket_ntohs,
3750 METH_VARARGS, ntohs_doc},
3751 {"ntohl", socket_ntohl,
3752 METH_O, ntohl_doc},
3753 {"htons", socket_htons,
3754 METH_VARARGS, htons_doc},
3755 {"htonl", socket_htonl,
3756 METH_O, htonl_doc},
3757 {"inet_aton", socket_inet_aton,
3758 METH_VARARGS, inet_aton_doc},
3759 {"inet_ntoa", socket_inet_ntoa,
3760 METH_VARARGS, inet_ntoa_doc},
3761 #ifdef HAVE_INET_PTON
3762 {"inet_pton", socket_inet_pton,
3763 METH_VARARGS, inet_pton_doc},
3764 {"inet_ntop", socket_inet_ntop,
3765 METH_VARARGS, inet_ntop_doc},
3766 #endif
3767 {"getaddrinfo", socket_getaddrinfo,
3768 METH_VARARGS, getaddrinfo_doc},
3769 {"getnameinfo", socket_getnameinfo,
3770 METH_VARARGS, getnameinfo_doc},
3771 {"getdefaulttimeout", (PyCFunction)socket_getdefaulttimeout,
3772 METH_NOARGS, getdefaulttimeout_doc},
3773 {"setdefaulttimeout", socket_setdefaulttimeout,
3774 METH_O, setdefaulttimeout_doc},
3775 {NULL, NULL} /* Sentinel */
3779 #ifdef RISCOS
3780 #define OS_INIT_DEFINED
3782 static int
3783 os_init(void)
3785 _kernel_swi_regs r;
3787 r.r[0] = 0;
3788 _kernel_swi(0x43380, &r, &r);
3789 taskwindow = r.r[0];
3791 return 1;
3794 #endif /* RISCOS */
3797 #ifdef MS_WINDOWS
3798 #define OS_INIT_DEFINED
3800 /* Additional initialization and cleanup for Windows */
3802 static void
3803 os_cleanup(void)
3805 WSACleanup();
3808 static int
3809 os_init(void)
3811 WSADATA WSAData;
3812 int ret;
3813 char buf[100];
3814 ret = WSAStartup(0x0101, &WSAData);
3815 switch (ret) {
3816 case 0: /* No error */
3817 Py_AtExit(os_cleanup);
3818 return 1; /* Success */
3819 case WSASYSNOTREADY:
3820 PyErr_SetString(PyExc_ImportError,
3821 "WSAStartup failed: network not ready");
3822 break;
3823 case WSAVERNOTSUPPORTED:
3824 case WSAEINVAL:
3825 PyErr_SetString(
3826 PyExc_ImportError,
3827 "WSAStartup failed: requested version not supported");
3828 break;
3829 default:
3830 PyOS_snprintf(buf, sizeof(buf),
3831 "WSAStartup failed: error code %d", ret);
3832 PyErr_SetString(PyExc_ImportError, buf);
3833 break;
3835 return 0; /* Failure */
3838 #endif /* MS_WINDOWS */
3841 #ifdef PYOS_OS2
3842 #define OS_INIT_DEFINED
3844 /* Additional initialization for OS/2 */
3846 static int
3847 os_init(void)
3849 #ifndef PYCC_GCC
3850 char reason[64];
3851 int rc = sock_init();
3853 if (rc == 0) {
3854 return 1; /* Success */
3857 PyOS_snprintf(reason, sizeof(reason),
3858 "OS/2 TCP/IP Error# %d", sock_errno());
3859 PyErr_SetString(PyExc_ImportError, reason);
3861 return 0; /* Failure */
3862 #else
3863 /* No need to initialise sockets with GCC/EMX */
3864 return 1; /* Success */
3865 #endif
3868 #endif /* PYOS_OS2 */
3871 #ifndef OS_INIT_DEFINED
3872 static int
3873 os_init(void)
3875 return 1; /* Success */
3877 #endif
3880 /* C API table - always add new things to the end for binary
3881 compatibility. */
3882 static
3883 PySocketModule_APIObject PySocketModuleAPI =
3885 &sock_type,
3886 NULL
3890 /* Initialize the _socket module.
3892 This module is actually called "_socket", and there's a wrapper
3893 "socket.py" which implements some additional functionality. On some
3894 platforms (e.g. Windows and OS/2), socket.py also implements a
3895 wrapper for the socket type that provides missing functionality such
3896 as makefile(), dup() and fromfd(). The import of "_socket" may fail
3897 with an ImportError exception if os-specific initialization fails.
3898 On Windows, this does WINSOCK initialization. When WINSOCK is
3899 initialized succesfully, a call to WSACleanup() is scheduled to be
3900 made at exit time.
3903 PyDoc_STRVAR(socket_doc,
3904 "Implementation module for socket operations.\n\
3906 See the socket module for documentation.");
3908 PyMODINIT_FUNC
3909 init_socket(void)
3911 PyObject *m, *has_ipv6;
3913 if (!os_init())
3914 return;
3916 sock_type.ob_type = &PyType_Type;
3917 m = Py_InitModule3(PySocket_MODULE_NAME,
3918 socket_methods,
3919 socket_doc);
3920 if (m == NULL)
3921 return;
3923 socket_error = PyErr_NewException("socket.error", NULL, NULL);
3924 if (socket_error == NULL)
3925 return;
3926 PySocketModuleAPI.error = socket_error;
3927 Py_INCREF(socket_error);
3928 PyModule_AddObject(m, "error", socket_error);
3929 socket_herror = PyErr_NewException("socket.herror",
3930 socket_error, NULL);
3931 if (socket_herror == NULL)
3932 return;
3933 Py_INCREF(socket_herror);
3934 PyModule_AddObject(m, "herror", socket_herror);
3935 socket_gaierror = PyErr_NewException("socket.gaierror", socket_error,
3936 NULL);
3937 if (socket_gaierror == NULL)
3938 return;
3939 Py_INCREF(socket_gaierror);
3940 PyModule_AddObject(m, "gaierror", socket_gaierror);
3941 socket_timeout = PyErr_NewException("socket.timeout",
3942 socket_error, NULL);
3943 if (socket_timeout == NULL)
3944 return;
3945 Py_INCREF(socket_timeout);
3946 PyModule_AddObject(m, "timeout", socket_timeout);
3947 Py_INCREF((PyObject *)&sock_type);
3948 if (PyModule_AddObject(m, "SocketType",
3949 (PyObject *)&sock_type) != 0)
3950 return;
3951 Py_INCREF((PyObject *)&sock_type);
3952 if (PyModule_AddObject(m, "socket",
3953 (PyObject *)&sock_type) != 0)
3954 return;
3956 #ifdef ENABLE_IPV6
3957 has_ipv6 = Py_True;
3958 #else
3959 has_ipv6 = Py_False;
3960 #endif
3961 Py_INCREF(has_ipv6);
3962 PyModule_AddObject(m, "has_ipv6", has_ipv6);
3964 /* Export C API */
3965 if (PyModule_AddObject(m, PySocket_CAPI_NAME,
3966 PyCObject_FromVoidPtr((void *)&PySocketModuleAPI, NULL)
3967 ) != 0)
3968 return;
3970 /* Address families (we only support AF_INET and AF_UNIX) */
3971 #ifdef AF_UNSPEC
3972 PyModule_AddIntConstant(m, "AF_UNSPEC", AF_UNSPEC);
3973 #endif
3974 PyModule_AddIntConstant(m, "AF_INET", AF_INET);
3975 #ifdef AF_INET6
3976 PyModule_AddIntConstant(m, "AF_INET6", AF_INET6);
3977 #endif /* AF_INET6 */
3978 #if defined(AF_UNIX)
3979 PyModule_AddIntConstant(m, "AF_UNIX", AF_UNIX);
3980 #endif /* AF_UNIX */
3981 #ifdef AF_AX25
3982 /* Amateur Radio AX.25 */
3983 PyModule_AddIntConstant(m, "AF_AX25", AF_AX25);
3984 #endif
3985 #ifdef AF_IPX
3986 PyModule_AddIntConstant(m, "AF_IPX", AF_IPX); /* Novell IPX */
3987 #endif
3988 #ifdef AF_APPLETALK
3989 /* Appletalk DDP */
3990 PyModule_AddIntConstant(m, "AF_APPLETALK", AF_APPLETALK);
3991 #endif
3992 #ifdef AF_NETROM
3993 /* Amateur radio NetROM */
3994 PyModule_AddIntConstant(m, "AF_NETROM", AF_NETROM);
3995 #endif
3996 #ifdef AF_BRIDGE
3997 /* Multiprotocol bridge */
3998 PyModule_AddIntConstant(m, "AF_BRIDGE", AF_BRIDGE);
3999 #endif
4000 #ifdef AF_ATMPVC
4001 /* ATM PVCs */
4002 PyModule_AddIntConstant(m, "AF_ATMPVC", AF_ATMPVC);
4003 #endif
4004 #ifdef AF_AAL5
4005 /* Reserved for Werner's ATM */
4006 PyModule_AddIntConstant(m, "AF_AAL5", AF_AAL5);
4007 #endif
4008 #ifdef AF_X25
4009 /* Reserved for X.25 project */
4010 PyModule_AddIntConstant(m, "AF_X25", AF_X25);
4011 #endif
4012 #ifdef AF_INET6
4013 PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); /* IP version 6 */
4014 #endif
4015 #ifdef AF_ROSE
4016 /* Amateur Radio X.25 PLP */
4017 PyModule_AddIntConstant(m, "AF_ROSE", AF_ROSE);
4018 #endif
4019 #ifdef AF_DECnet
4020 /* Reserved for DECnet project */
4021 PyModule_AddIntConstant(m, "AF_DECnet", AF_DECnet);
4022 #endif
4023 #ifdef AF_NETBEUI
4024 /* Reserved for 802.2LLC project */
4025 PyModule_AddIntConstant(m, "AF_NETBEUI", AF_NETBEUI);
4026 #endif
4027 #ifdef AF_SECURITY
4028 /* Security callback pseudo AF */
4029 PyModule_AddIntConstant(m, "AF_SECURITY", AF_SECURITY);
4030 #endif
4031 #ifdef AF_KEY
4032 /* PF_KEY key management API */
4033 PyModule_AddIntConstant(m, "AF_KEY", AF_KEY);
4034 #endif
4035 #ifdef AF_NETLINK
4036 /* */
4037 PyModule_AddIntConstant(m, "AF_NETLINK", AF_NETLINK);
4038 PyModule_AddIntConstant(m, "NETLINK_ROUTE", NETLINK_ROUTE);
4039 PyModule_AddIntConstant(m, "NETLINK_SKIP", NETLINK_SKIP);
4040 PyModule_AddIntConstant(m, "NETLINK_USERSOCK", NETLINK_USERSOCK);
4041 PyModule_AddIntConstant(m, "NETLINK_FIREWALL", NETLINK_FIREWALL);
4042 #ifdef NETLINK_TCPDIAG
4043 PyModule_AddIntConstant(m, "NETLINK_TCPDIAG", NETLINK_TCPDIAG);
4044 #endif
4045 #ifdef NETLINK_NFLOG
4046 PyModule_AddIntConstant(m, "NETLINK_NFLOG", NETLINK_NFLOG);
4047 #endif
4048 #ifdef NETLINK_XFRM
4049 PyModule_AddIntConstant(m, "NETLINK_XFRM", NETLINK_XFRM);
4050 #endif
4051 PyModule_AddIntConstant(m, "NETLINK_ARPD", NETLINK_ARPD);
4052 PyModule_AddIntConstant(m, "NETLINK_ROUTE6", NETLINK_ROUTE6);
4053 PyModule_AddIntConstant(m, "NETLINK_IP6_FW", NETLINK_IP6_FW);
4054 PyModule_AddIntConstant(m, "NETLINK_DNRTMSG", NETLINK_DNRTMSG);
4055 PyModule_AddIntConstant(m, "NETLINK_TAPBASE", NETLINK_TAPBASE);
4056 #endif /* AF_NETLINK */
4057 #ifdef AF_ROUTE
4058 /* Alias to emulate 4.4BSD */
4059 PyModule_AddIntConstant(m, "AF_ROUTE", AF_ROUTE);
4060 #endif
4061 #ifdef AF_ASH
4062 /* Ash */
4063 PyModule_AddIntConstant(m, "AF_ASH", AF_ASH);
4064 #endif
4065 #ifdef AF_ECONET
4066 /* Acorn Econet */
4067 PyModule_AddIntConstant(m, "AF_ECONET", AF_ECONET);
4068 #endif
4069 #ifdef AF_ATMSVC
4070 /* ATM SVCs */
4071 PyModule_AddIntConstant(m, "AF_ATMSVC", AF_ATMSVC);
4072 #endif
4073 #ifdef AF_SNA
4074 /* Linux SNA Project (nutters!) */
4075 PyModule_AddIntConstant(m, "AF_SNA", AF_SNA);
4076 #endif
4077 #ifdef AF_IRDA
4078 /* IRDA sockets */
4079 PyModule_AddIntConstant(m, "AF_IRDA", AF_IRDA);
4080 #endif
4081 #ifdef AF_PPPOX
4082 /* PPPoX sockets */
4083 PyModule_AddIntConstant(m, "AF_PPPOX", AF_PPPOX);
4084 #endif
4085 #ifdef AF_WANPIPE
4086 /* Wanpipe API Sockets */
4087 PyModule_AddIntConstant(m, "AF_WANPIPE", AF_WANPIPE);
4088 #endif
4089 #ifdef AF_LLC
4090 /* Linux LLC */
4091 PyModule_AddIntConstant(m, "AF_LLC", AF_LLC);
4092 #endif
4094 #ifdef USE_BLUETOOTH
4095 PyModule_AddIntConstant(m, "AF_BLUETOOTH", AF_BLUETOOTH);
4096 PyModule_AddIntConstant(m, "BTPROTO_L2CAP", BTPROTO_L2CAP);
4097 #if !defined(__FreeBSD__)
4098 PyModule_AddIntConstant(m, "BTPROTO_SCO", BTPROTO_SCO);
4099 #endif
4100 PyModule_AddIntConstant(m, "BTPROTO_RFCOMM", BTPROTO_RFCOMM);
4101 PyModule_AddObject(m, "BDADDR_ANY", Py_BuildValue("s", "00:00:00:00:00:00"));
4102 PyModule_AddObject(m, "BDADDR_LOCAL", Py_BuildValue("s", "00:00:00:FF:FF:FF"));
4103 #endif
4105 #ifdef HAVE_NETPACKET_PACKET_H
4106 PyModule_AddIntConstant(m, "AF_PACKET", AF_PACKET);
4107 PyModule_AddIntConstant(m, "PF_PACKET", PF_PACKET);
4108 PyModule_AddIntConstant(m, "PACKET_HOST", PACKET_HOST);
4109 PyModule_AddIntConstant(m, "PACKET_BROADCAST", PACKET_BROADCAST);
4110 PyModule_AddIntConstant(m, "PACKET_MULTICAST", PACKET_MULTICAST);
4111 PyModule_AddIntConstant(m, "PACKET_OTHERHOST", PACKET_OTHERHOST);
4112 PyModule_AddIntConstant(m, "PACKET_OUTGOING", PACKET_OUTGOING);
4113 PyModule_AddIntConstant(m, "PACKET_LOOPBACK", PACKET_LOOPBACK);
4114 PyModule_AddIntConstant(m, "PACKET_FASTROUTE", PACKET_FASTROUTE);
4115 #endif
4117 /* Socket types */
4118 PyModule_AddIntConstant(m, "SOCK_STREAM", SOCK_STREAM);
4119 PyModule_AddIntConstant(m, "SOCK_DGRAM", SOCK_DGRAM);
4120 #ifndef __BEOS__
4121 /* We have incomplete socket support. */
4122 PyModule_AddIntConstant(m, "SOCK_RAW", SOCK_RAW);
4123 PyModule_AddIntConstant(m, "SOCK_SEQPACKET", SOCK_SEQPACKET);
4124 #if defined(SOCK_RDM)
4125 PyModule_AddIntConstant(m, "SOCK_RDM", SOCK_RDM);
4126 #endif
4127 #endif
4129 #ifdef SO_DEBUG
4130 PyModule_AddIntConstant(m, "SO_DEBUG", SO_DEBUG);
4131 #endif
4132 #ifdef SO_ACCEPTCONN
4133 PyModule_AddIntConstant(m, "SO_ACCEPTCONN", SO_ACCEPTCONN);
4134 #endif
4135 #ifdef SO_REUSEADDR
4136 PyModule_AddIntConstant(m, "SO_REUSEADDR", SO_REUSEADDR);
4137 #endif
4138 #ifdef SO_EXCLUSIVEADDRUSE
4139 PyModule_AddIntConstant(m, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE);
4140 #endif
4142 #ifdef SO_KEEPALIVE
4143 PyModule_AddIntConstant(m, "SO_KEEPALIVE", SO_KEEPALIVE);
4144 #endif
4145 #ifdef SO_DONTROUTE
4146 PyModule_AddIntConstant(m, "SO_DONTROUTE", SO_DONTROUTE);
4147 #endif
4148 #ifdef SO_BROADCAST
4149 PyModule_AddIntConstant(m, "SO_BROADCAST", SO_BROADCAST);
4150 #endif
4151 #ifdef SO_USELOOPBACK
4152 PyModule_AddIntConstant(m, "SO_USELOOPBACK", SO_USELOOPBACK);
4153 #endif
4154 #ifdef SO_LINGER
4155 PyModule_AddIntConstant(m, "SO_LINGER", SO_LINGER);
4156 #endif
4157 #ifdef SO_OOBINLINE
4158 PyModule_AddIntConstant(m, "SO_OOBINLINE", SO_OOBINLINE);
4159 #endif
4160 #ifdef SO_REUSEPORT
4161 PyModule_AddIntConstant(m, "SO_REUSEPORT", SO_REUSEPORT);
4162 #endif
4163 #ifdef SO_SNDBUF
4164 PyModule_AddIntConstant(m, "SO_SNDBUF", SO_SNDBUF);
4165 #endif
4166 #ifdef SO_RCVBUF
4167 PyModule_AddIntConstant(m, "SO_RCVBUF", SO_RCVBUF);
4168 #endif
4169 #ifdef SO_SNDLOWAT
4170 PyModule_AddIntConstant(m, "SO_SNDLOWAT", SO_SNDLOWAT);
4171 #endif
4172 #ifdef SO_RCVLOWAT
4173 PyModule_AddIntConstant(m, "SO_RCVLOWAT", SO_RCVLOWAT);
4174 #endif
4175 #ifdef SO_SNDTIMEO
4176 PyModule_AddIntConstant(m, "SO_SNDTIMEO", SO_SNDTIMEO);
4177 #endif
4178 #ifdef SO_RCVTIMEO
4179 PyModule_AddIntConstant(m, "SO_RCVTIMEO", SO_RCVTIMEO);
4180 #endif
4181 #ifdef SO_ERROR
4182 PyModule_AddIntConstant(m, "SO_ERROR", SO_ERROR);
4183 #endif
4184 #ifdef SO_TYPE
4185 PyModule_AddIntConstant(m, "SO_TYPE", SO_TYPE);
4186 #endif
4188 /* Maximum number of connections for "listen" */
4189 #ifdef SOMAXCONN
4190 PyModule_AddIntConstant(m, "SOMAXCONN", SOMAXCONN);
4191 #else
4192 PyModule_AddIntConstant(m, "SOMAXCONN", 5); /* Common value */
4193 #endif
4195 /* Flags for send, recv */
4196 #ifdef MSG_OOB
4197 PyModule_AddIntConstant(m, "MSG_OOB", MSG_OOB);
4198 #endif
4199 #ifdef MSG_PEEK
4200 PyModule_AddIntConstant(m, "MSG_PEEK", MSG_PEEK);
4201 #endif
4202 #ifdef MSG_DONTROUTE
4203 PyModule_AddIntConstant(m, "MSG_DONTROUTE", MSG_DONTROUTE);
4204 #endif
4205 #ifdef MSG_DONTWAIT
4206 PyModule_AddIntConstant(m, "MSG_DONTWAIT", MSG_DONTWAIT);
4207 #endif
4208 #ifdef MSG_EOR
4209 PyModule_AddIntConstant(m, "MSG_EOR", MSG_EOR);
4210 #endif
4211 #ifdef MSG_TRUNC
4212 PyModule_AddIntConstant(m, "MSG_TRUNC", MSG_TRUNC);
4213 #endif
4214 #ifdef MSG_CTRUNC
4215 PyModule_AddIntConstant(m, "MSG_CTRUNC", MSG_CTRUNC);
4216 #endif
4217 #ifdef MSG_WAITALL
4218 PyModule_AddIntConstant(m, "MSG_WAITALL", MSG_WAITALL);
4219 #endif
4220 #ifdef MSG_BTAG
4221 PyModule_AddIntConstant(m, "MSG_BTAG", MSG_BTAG);
4222 #endif
4223 #ifdef MSG_ETAG
4224 PyModule_AddIntConstant(m, "MSG_ETAG", MSG_ETAG);
4225 #endif
4227 /* Protocol level and numbers, usable for [gs]etsockopt */
4228 #ifdef SOL_SOCKET
4229 PyModule_AddIntConstant(m, "SOL_SOCKET", SOL_SOCKET);
4230 #endif
4231 #ifdef SOL_IP
4232 PyModule_AddIntConstant(m, "SOL_IP", SOL_IP);
4233 #else
4234 PyModule_AddIntConstant(m, "SOL_IP", 0);
4235 #endif
4236 #ifdef SOL_IPX
4237 PyModule_AddIntConstant(m, "SOL_IPX", SOL_IPX);
4238 #endif
4239 #ifdef SOL_AX25
4240 PyModule_AddIntConstant(m, "SOL_AX25", SOL_AX25);
4241 #endif
4242 #ifdef SOL_ATALK
4243 PyModule_AddIntConstant(m, "SOL_ATALK", SOL_ATALK);
4244 #endif
4245 #ifdef SOL_NETROM
4246 PyModule_AddIntConstant(m, "SOL_NETROM", SOL_NETROM);
4247 #endif
4248 #ifdef SOL_ROSE
4249 PyModule_AddIntConstant(m, "SOL_ROSE", SOL_ROSE);
4250 #endif
4251 #ifdef SOL_TCP
4252 PyModule_AddIntConstant(m, "SOL_TCP", SOL_TCP);
4253 #else
4254 PyModule_AddIntConstant(m, "SOL_TCP", 6);
4255 #endif
4256 #ifdef SOL_UDP
4257 PyModule_AddIntConstant(m, "SOL_UDP", SOL_UDP);
4258 #else
4259 PyModule_AddIntConstant(m, "SOL_UDP", 17);
4260 #endif
4261 #ifdef IPPROTO_IP
4262 PyModule_AddIntConstant(m, "IPPROTO_IP", IPPROTO_IP);
4263 #else
4264 PyModule_AddIntConstant(m, "IPPROTO_IP", 0);
4265 #endif
4266 #ifdef IPPROTO_HOPOPTS
4267 PyModule_AddIntConstant(m, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS);
4268 #endif
4269 #ifdef IPPROTO_ICMP
4270 PyModule_AddIntConstant(m, "IPPROTO_ICMP", IPPROTO_ICMP);
4271 #else
4272 PyModule_AddIntConstant(m, "IPPROTO_ICMP", 1);
4273 #endif
4274 #ifdef IPPROTO_IGMP
4275 PyModule_AddIntConstant(m, "IPPROTO_IGMP", IPPROTO_IGMP);
4276 #endif
4277 #ifdef IPPROTO_GGP
4278 PyModule_AddIntConstant(m, "IPPROTO_GGP", IPPROTO_GGP);
4279 #endif
4280 #ifdef IPPROTO_IPV4
4281 PyModule_AddIntConstant(m, "IPPROTO_IPV4", IPPROTO_IPV4);
4282 #endif
4283 #ifdef IPPROTO_IPV6
4284 PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
4285 #endif
4286 #ifdef IPPROTO_IPIP
4287 PyModule_AddIntConstant(m, "IPPROTO_IPIP", IPPROTO_IPIP);
4288 #endif
4289 #ifdef IPPROTO_TCP
4290 PyModule_AddIntConstant(m, "IPPROTO_TCP", IPPROTO_TCP);
4291 #else
4292 PyModule_AddIntConstant(m, "IPPROTO_TCP", 6);
4293 #endif
4294 #ifdef IPPROTO_EGP
4295 PyModule_AddIntConstant(m, "IPPROTO_EGP", IPPROTO_EGP);
4296 #endif
4297 #ifdef IPPROTO_PUP
4298 PyModule_AddIntConstant(m, "IPPROTO_PUP", IPPROTO_PUP);
4299 #endif
4300 #ifdef IPPROTO_UDP
4301 PyModule_AddIntConstant(m, "IPPROTO_UDP", IPPROTO_UDP);
4302 #else
4303 PyModule_AddIntConstant(m, "IPPROTO_UDP", 17);
4304 #endif
4305 #ifdef IPPROTO_IDP
4306 PyModule_AddIntConstant(m, "IPPROTO_IDP", IPPROTO_IDP);
4307 #endif
4308 #ifdef IPPROTO_HELLO
4309 PyModule_AddIntConstant(m, "IPPROTO_HELLO", IPPROTO_HELLO);
4310 #endif
4311 #ifdef IPPROTO_ND
4312 PyModule_AddIntConstant(m, "IPPROTO_ND", IPPROTO_ND);
4313 #endif
4314 #ifdef IPPROTO_TP
4315 PyModule_AddIntConstant(m, "IPPROTO_TP", IPPROTO_TP);
4316 #endif
4317 #ifdef IPPROTO_IPV6
4318 PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
4319 #endif
4320 #ifdef IPPROTO_ROUTING
4321 PyModule_AddIntConstant(m, "IPPROTO_ROUTING", IPPROTO_ROUTING);
4322 #endif
4323 #ifdef IPPROTO_FRAGMENT
4324 PyModule_AddIntConstant(m, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT);
4325 #endif
4326 #ifdef IPPROTO_RSVP
4327 PyModule_AddIntConstant(m, "IPPROTO_RSVP", IPPROTO_RSVP);
4328 #endif
4329 #ifdef IPPROTO_GRE
4330 PyModule_AddIntConstant(m, "IPPROTO_GRE", IPPROTO_GRE);
4331 #endif
4332 #ifdef IPPROTO_ESP
4333 PyModule_AddIntConstant(m, "IPPROTO_ESP", IPPROTO_ESP);
4334 #endif
4335 #ifdef IPPROTO_AH
4336 PyModule_AddIntConstant(m, "IPPROTO_AH", IPPROTO_AH);
4337 #endif
4338 #ifdef IPPROTO_MOBILE
4339 PyModule_AddIntConstant(m, "IPPROTO_MOBILE", IPPROTO_MOBILE);
4340 #endif
4341 #ifdef IPPROTO_ICMPV6
4342 PyModule_AddIntConstant(m, "IPPROTO_ICMPV6", IPPROTO_ICMPV6);
4343 #endif
4344 #ifdef IPPROTO_NONE
4345 PyModule_AddIntConstant(m, "IPPROTO_NONE", IPPROTO_NONE);
4346 #endif
4347 #ifdef IPPROTO_DSTOPTS
4348 PyModule_AddIntConstant(m, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS);
4349 #endif
4350 #ifdef IPPROTO_XTP
4351 PyModule_AddIntConstant(m, "IPPROTO_XTP", IPPROTO_XTP);
4352 #endif
4353 #ifdef IPPROTO_EON
4354 PyModule_AddIntConstant(m, "IPPROTO_EON", IPPROTO_EON);
4355 #endif
4356 #ifdef IPPROTO_PIM
4357 PyModule_AddIntConstant(m, "IPPROTO_PIM", IPPROTO_PIM);
4358 #endif
4359 #ifdef IPPROTO_IPCOMP
4360 PyModule_AddIntConstant(m, "IPPROTO_IPCOMP", IPPROTO_IPCOMP);
4361 #endif
4362 #ifdef IPPROTO_VRRP
4363 PyModule_AddIntConstant(m, "IPPROTO_VRRP", IPPROTO_VRRP);
4364 #endif
4365 #ifdef IPPROTO_BIP
4366 PyModule_AddIntConstant(m, "IPPROTO_BIP", IPPROTO_BIP);
4367 #endif
4368 /**/
4369 #ifdef IPPROTO_RAW
4370 PyModule_AddIntConstant(m, "IPPROTO_RAW", IPPROTO_RAW);
4371 #else
4372 PyModule_AddIntConstant(m, "IPPROTO_RAW", 255);
4373 #endif
4374 #ifdef IPPROTO_MAX
4375 PyModule_AddIntConstant(m, "IPPROTO_MAX", IPPROTO_MAX);
4376 #endif
4378 /* Some port configuration */
4379 #ifdef IPPORT_RESERVED
4380 PyModule_AddIntConstant(m, "IPPORT_RESERVED", IPPORT_RESERVED);
4381 #else
4382 PyModule_AddIntConstant(m, "IPPORT_RESERVED", 1024);
4383 #endif
4384 #ifdef IPPORT_USERRESERVED
4385 PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", IPPORT_USERRESERVED);
4386 #else
4387 PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", 5000);
4388 #endif
4390 /* Some reserved IP v.4 addresses */
4391 #ifdef INADDR_ANY
4392 PyModule_AddIntConstant(m, "INADDR_ANY", INADDR_ANY);
4393 #else
4394 PyModule_AddIntConstant(m, "INADDR_ANY", 0x00000000);
4395 #endif
4396 #ifdef INADDR_BROADCAST
4397 PyModule_AddIntConstant(m, "INADDR_BROADCAST", INADDR_BROADCAST);
4398 #else
4399 PyModule_AddIntConstant(m, "INADDR_BROADCAST", 0xffffffff);
4400 #endif
4401 #ifdef INADDR_LOOPBACK
4402 PyModule_AddIntConstant(m, "INADDR_LOOPBACK", INADDR_LOOPBACK);
4403 #else
4404 PyModule_AddIntConstant(m, "INADDR_LOOPBACK", 0x7F000001);
4405 #endif
4406 #ifdef INADDR_UNSPEC_GROUP
4407 PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
4408 #else
4409 PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", 0xe0000000);
4410 #endif
4411 #ifdef INADDR_ALLHOSTS_GROUP
4412 PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP",
4413 INADDR_ALLHOSTS_GROUP);
4414 #else
4415 PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
4416 #endif
4417 #ifdef INADDR_MAX_LOCAL_GROUP
4418 PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP",
4419 INADDR_MAX_LOCAL_GROUP);
4420 #else
4421 PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
4422 #endif
4423 #ifdef INADDR_NONE
4424 PyModule_AddIntConstant(m, "INADDR_NONE", INADDR_NONE);
4425 #else
4426 PyModule_AddIntConstant(m, "INADDR_NONE", 0xffffffff);
4427 #endif
4429 /* IPv4 [gs]etsockopt options */
4430 #ifdef IP_OPTIONS
4431 PyModule_AddIntConstant(m, "IP_OPTIONS", IP_OPTIONS);
4432 #endif
4433 #ifdef IP_HDRINCL
4434 PyModule_AddIntConstant(m, "IP_HDRINCL", IP_HDRINCL);
4435 #endif
4436 #ifdef IP_TOS
4437 PyModule_AddIntConstant(m, "IP_TOS", IP_TOS);
4438 #endif
4439 #ifdef IP_TTL
4440 PyModule_AddIntConstant(m, "IP_TTL", IP_TTL);
4441 #endif
4442 #ifdef IP_RECVOPTS
4443 PyModule_AddIntConstant(m, "IP_RECVOPTS", IP_RECVOPTS);
4444 #endif
4445 #ifdef IP_RECVRETOPTS
4446 PyModule_AddIntConstant(m, "IP_RECVRETOPTS", IP_RECVRETOPTS);
4447 #endif
4448 #ifdef IP_RECVDSTADDR
4449 PyModule_AddIntConstant(m, "IP_RECVDSTADDR", IP_RECVDSTADDR);
4450 #endif
4451 #ifdef IP_RETOPTS
4452 PyModule_AddIntConstant(m, "IP_RETOPTS", IP_RETOPTS);
4453 #endif
4454 #ifdef IP_MULTICAST_IF
4455 PyModule_AddIntConstant(m, "IP_MULTICAST_IF", IP_MULTICAST_IF);
4456 #endif
4457 #ifdef IP_MULTICAST_TTL
4458 PyModule_AddIntConstant(m, "IP_MULTICAST_TTL", IP_MULTICAST_TTL);
4459 #endif
4460 #ifdef IP_MULTICAST_LOOP
4461 PyModule_AddIntConstant(m, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
4462 #endif
4463 #ifdef IP_ADD_MEMBERSHIP
4464 PyModule_AddIntConstant(m, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
4465 #endif
4466 #ifdef IP_DROP_MEMBERSHIP
4467 PyModule_AddIntConstant(m, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
4468 #endif
4469 #ifdef IP_DEFAULT_MULTICAST_TTL
4470 PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_TTL",
4471 IP_DEFAULT_MULTICAST_TTL);
4472 #endif
4473 #ifdef IP_DEFAULT_MULTICAST_LOOP
4474 PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_LOOP",
4475 IP_DEFAULT_MULTICAST_LOOP);
4476 #endif
4477 #ifdef IP_MAX_MEMBERSHIPS
4478 PyModule_AddIntConstant(m, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS);
4479 #endif
4481 /* IPv6 [gs]etsockopt options, defined in RFC2553 */
4482 #ifdef IPV6_JOIN_GROUP
4483 PyModule_AddIntConstant(m, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP);
4484 #endif
4485 #ifdef IPV6_LEAVE_GROUP
4486 PyModule_AddIntConstant(m, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP);
4487 #endif
4488 #ifdef IPV6_MULTICAST_HOPS
4489 PyModule_AddIntConstant(m, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS);
4490 #endif
4491 #ifdef IPV6_MULTICAST_IF
4492 PyModule_AddIntConstant(m, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF);
4493 #endif
4494 #ifdef IPV6_MULTICAST_LOOP
4495 PyModule_AddIntConstant(m, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP);
4496 #endif
4497 #ifdef IPV6_UNICAST_HOPS
4498 PyModule_AddIntConstant(m, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS);
4499 #endif
4500 /* Additional IPV6 socket options, defined in RFC 3493 */
4501 #ifdef IPV6_V6ONLY
4502 PyModule_AddIntConstant(m, "IPV6_V6ONLY", IPV6_V6ONLY);
4503 #endif
4504 /* Advanced IPV6 socket options, from RFC 3542 */
4505 #ifdef IPV6_CHECKSUM
4506 PyModule_AddIntConstant(m, "IPV6_CHECKSUM", IPV6_CHECKSUM);
4507 #endif
4508 #ifdef IPV6_DONTFRAG
4509 PyModule_AddIntConstant(m, "IPV6_DONTFRAG", IPV6_DONTFRAG);
4510 #endif
4511 #ifdef IPV6_DSTOPTS
4512 PyModule_AddIntConstant(m, "IPV6_DSTOPTS", IPV6_DSTOPTS);
4513 #endif
4514 #ifdef IPV6_HOPLIMIT
4515 PyModule_AddIntConstant(m, "IPV6_HOPLIMIT", IPV6_HOPLIMIT);
4516 #endif
4517 #ifdef IPV6_HOPOPTS
4518 PyModule_AddIntConstant(m, "IPV6_HOPOPTS", IPV6_HOPOPTS);
4519 #endif
4520 #ifdef IPV6_NEXTHOP
4521 PyModule_AddIntConstant(m, "IPV6_NEXTHOP", IPV6_NEXTHOP);
4522 #endif
4523 #ifdef IPV6_PATHMTU
4524 PyModule_AddIntConstant(m, "IPV6_PATHMTU", IPV6_PATHMTU);
4525 #endif
4526 #ifdef IPV6_PKTINFO
4527 PyModule_AddIntConstant(m, "IPV6_PKTINFO", IPV6_PKTINFO);
4528 #endif
4529 #ifdef IPV6_RECVDSTOPTS
4530 PyModule_AddIntConstant(m, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS);
4531 #endif
4532 #ifdef IPV6_RECVHOPLIMIT
4533 PyModule_AddIntConstant(m, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT);
4534 #endif
4535 #ifdef IPV6_RECVHOPOPTS
4536 PyModule_AddIntConstant(m, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS);
4537 #endif
4538 #ifdef IPV6_RECVPKTINFO
4539 PyModule_AddIntConstant(m, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO);
4540 #endif
4541 #ifdef IPV6_RECVRTHDR
4542 PyModule_AddIntConstant(m, "IPV6_RECVRTHDR", IPV6_RECVRTHDR);
4543 #endif
4544 #ifdef IPV6_RECVTCLASS
4545 PyModule_AddIntConstant(m, "IPV6_RECVTCLASS", IPV6_RECVTCLASS);
4546 #endif
4547 #ifdef IPV6_RTHDR
4548 PyModule_AddIntConstant(m, "IPV6_RTHDR", IPV6_RTHDR);
4549 #endif
4550 #ifdef IPV6_RTHDRDSTOPTS
4551 PyModule_AddIntConstant(m, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS);
4552 #endif
4553 #ifdef IPV6_RTHDR_TYPE_0
4554 PyModule_AddIntConstant(m, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0);
4555 #endif
4556 #ifdef IPV6_RECVPATHMTU
4557 PyModule_AddIntConstant(m, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU);
4558 #endif
4559 #ifdef IPV6_TCLASS
4560 PyModule_AddIntConstant(m, "IPV6_TCLASS", IPV6_TCLASS);
4561 #endif
4562 #ifdef IPV6_USE_MIN_MTU
4563 PyModule_AddIntConstant(m, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU);
4564 #endif
4566 /* TCP options */
4567 #ifdef TCP_NODELAY
4568 PyModule_AddIntConstant(m, "TCP_NODELAY", TCP_NODELAY);
4569 #endif
4570 #ifdef TCP_MAXSEG
4571 PyModule_AddIntConstant(m, "TCP_MAXSEG", TCP_MAXSEG);
4572 #endif
4573 #ifdef TCP_CORK
4574 PyModule_AddIntConstant(m, "TCP_CORK", TCP_CORK);
4575 #endif
4576 #ifdef TCP_KEEPIDLE
4577 PyModule_AddIntConstant(m, "TCP_KEEPIDLE", TCP_KEEPIDLE);
4578 #endif
4579 #ifdef TCP_KEEPINTVL
4580 PyModule_AddIntConstant(m, "TCP_KEEPINTVL", TCP_KEEPINTVL);
4581 #endif
4582 #ifdef TCP_KEEPCNT
4583 PyModule_AddIntConstant(m, "TCP_KEEPCNT", TCP_KEEPCNT);
4584 #endif
4585 #ifdef TCP_SYNCNT
4586 PyModule_AddIntConstant(m, "TCP_SYNCNT", TCP_SYNCNT);
4587 #endif
4588 #ifdef TCP_LINGER2
4589 PyModule_AddIntConstant(m, "TCP_LINGER2", TCP_LINGER2);
4590 #endif
4591 #ifdef TCP_DEFER_ACCEPT
4592 PyModule_AddIntConstant(m, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT);
4593 #endif
4594 #ifdef TCP_WINDOW_CLAMP
4595 PyModule_AddIntConstant(m, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP);
4596 #endif
4597 #ifdef TCP_INFO
4598 PyModule_AddIntConstant(m, "TCP_INFO", TCP_INFO);
4599 #endif
4600 #ifdef TCP_QUICKACK
4601 PyModule_AddIntConstant(m, "TCP_QUICKACK", TCP_QUICKACK);
4602 #endif
4605 /* IPX options */
4606 #ifdef IPX_TYPE
4607 PyModule_AddIntConstant(m, "IPX_TYPE", IPX_TYPE);
4608 #endif
4610 /* get{addr,name}info parameters */
4611 #ifdef EAI_ADDRFAMILY
4612 PyModule_AddIntConstant(m, "EAI_ADDRFAMILY", EAI_ADDRFAMILY);
4613 #endif
4614 #ifdef EAI_AGAIN
4615 PyModule_AddIntConstant(m, "EAI_AGAIN", EAI_AGAIN);
4616 #endif
4617 #ifdef EAI_BADFLAGS
4618 PyModule_AddIntConstant(m, "EAI_BADFLAGS", EAI_BADFLAGS);
4619 #endif
4620 #ifdef EAI_FAIL
4621 PyModule_AddIntConstant(m, "EAI_FAIL", EAI_FAIL);
4622 #endif
4623 #ifdef EAI_FAMILY
4624 PyModule_AddIntConstant(m, "EAI_FAMILY", EAI_FAMILY);
4625 #endif
4626 #ifdef EAI_MEMORY
4627 PyModule_AddIntConstant(m, "EAI_MEMORY", EAI_MEMORY);
4628 #endif
4629 #ifdef EAI_NODATA
4630 PyModule_AddIntConstant(m, "EAI_NODATA", EAI_NODATA);
4631 #endif
4632 #ifdef EAI_NONAME
4633 PyModule_AddIntConstant(m, "EAI_NONAME", EAI_NONAME);
4634 #endif
4635 #ifdef EAI_OVERFLOW
4636 PyModule_AddIntConstant(m, "EAI_OVERFLOW", EAI_OVERFLOW);
4637 #endif
4638 #ifdef EAI_SERVICE
4639 PyModule_AddIntConstant(m, "EAI_SERVICE", EAI_SERVICE);
4640 #endif
4641 #ifdef EAI_SOCKTYPE
4642 PyModule_AddIntConstant(m, "EAI_SOCKTYPE", EAI_SOCKTYPE);
4643 #endif
4644 #ifdef EAI_SYSTEM
4645 PyModule_AddIntConstant(m, "EAI_SYSTEM", EAI_SYSTEM);
4646 #endif
4647 #ifdef EAI_BADHINTS
4648 PyModule_AddIntConstant(m, "EAI_BADHINTS", EAI_BADHINTS);
4649 #endif
4650 #ifdef EAI_PROTOCOL
4651 PyModule_AddIntConstant(m, "EAI_PROTOCOL", EAI_PROTOCOL);
4652 #endif
4653 #ifdef EAI_MAX
4654 PyModule_AddIntConstant(m, "EAI_MAX", EAI_MAX);
4655 #endif
4656 #ifdef AI_PASSIVE
4657 PyModule_AddIntConstant(m, "AI_PASSIVE", AI_PASSIVE);
4658 #endif
4659 #ifdef AI_CANONNAME
4660 PyModule_AddIntConstant(m, "AI_CANONNAME", AI_CANONNAME);
4661 #endif
4662 #ifdef AI_NUMERICHOST
4663 PyModule_AddIntConstant(m, "AI_NUMERICHOST", AI_NUMERICHOST);
4664 #endif
4665 #ifdef AI_NUMERICSERV
4666 PyModule_AddIntConstant(m, "AI_NUMERICSERV", AI_NUMERICSERV);
4667 #endif
4668 #ifdef AI_MASK
4669 PyModule_AddIntConstant(m, "AI_MASK", AI_MASK);
4670 #endif
4671 #ifdef AI_ALL
4672 PyModule_AddIntConstant(m, "AI_ALL", AI_ALL);
4673 #endif
4674 #ifdef AI_V4MAPPED_CFG
4675 PyModule_AddIntConstant(m, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG);
4676 #endif
4677 #ifdef AI_ADDRCONFIG
4678 PyModule_AddIntConstant(m, "AI_ADDRCONFIG", AI_ADDRCONFIG);
4679 #endif
4680 #ifdef AI_V4MAPPED
4681 PyModule_AddIntConstant(m, "AI_V4MAPPED", AI_V4MAPPED);
4682 #endif
4683 #ifdef AI_DEFAULT
4684 PyModule_AddIntConstant(m, "AI_DEFAULT", AI_DEFAULT);
4685 #endif
4686 #ifdef NI_MAXHOST
4687 PyModule_AddIntConstant(m, "NI_MAXHOST", NI_MAXHOST);
4688 #endif
4689 #ifdef NI_MAXSERV
4690 PyModule_AddIntConstant(m, "NI_MAXSERV", NI_MAXSERV);
4691 #endif
4692 #ifdef NI_NOFQDN
4693 PyModule_AddIntConstant(m, "NI_NOFQDN", NI_NOFQDN);
4694 #endif
4695 #ifdef NI_NUMERICHOST
4696 PyModule_AddIntConstant(m, "NI_NUMERICHOST", NI_NUMERICHOST);
4697 #endif
4698 #ifdef NI_NAMEREQD
4699 PyModule_AddIntConstant(m, "NI_NAMEREQD", NI_NAMEREQD);
4700 #endif
4701 #ifdef NI_NUMERICSERV
4702 PyModule_AddIntConstant(m, "NI_NUMERICSERV", NI_NUMERICSERV);
4703 #endif
4704 #ifdef NI_DGRAM
4705 PyModule_AddIntConstant(m, "NI_DGRAM", NI_DGRAM);
4706 #endif
4708 /* shutdown() parameters */
4709 #ifdef SHUT_RD
4710 PyModule_AddIntConstant(m, "SHUT_RD", SHUT_RD);
4711 #elif defined(SD_RECEIVE)
4712 PyModule_AddIntConstant(m, "SHUT_RD", SD_RECEIVE);
4713 #else
4714 PyModule_AddIntConstant(m, "SHUT_RD", 0);
4715 #endif
4716 #ifdef SHUT_WR
4717 PyModule_AddIntConstant(m, "SHUT_WR", SHUT_WR);
4718 #elif defined(SD_SEND)
4719 PyModule_AddIntConstant(m, "SHUT_WR", SD_SEND);
4720 #else
4721 PyModule_AddIntConstant(m, "SHUT_WR", 1);
4722 #endif
4723 #ifdef SHUT_RDWR
4724 PyModule_AddIntConstant(m, "SHUT_RDWR", SHUT_RDWR);
4725 #elif defined(SD_BOTH)
4726 PyModule_AddIntConstant(m, "SHUT_RDWR", SD_BOTH);
4727 #else
4728 PyModule_AddIntConstant(m, "SHUT_RDWR", 2);
4729 #endif
4731 /* Initialize gethostbyname lock */
4732 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
4733 netdb_lock = PyThread_allocate_lock();
4734 #endif
4738 #ifndef HAVE_INET_PTON
4740 /* Simplistic emulation code for inet_pton that only works for IPv4 */
4741 /* These are not exposed because they do not set errno properly */
4744 inet_pton(int af, const char *src, void *dst)
4746 if (af == AF_INET) {
4747 long packed_addr;
4748 packed_addr = inet_addr(src);
4749 if (packed_addr == INADDR_NONE)
4750 return 0;
4751 memcpy(dst, &packed_addr, 4);
4752 return 1;
4754 /* Should set errno to EAFNOSUPPORT */
4755 return -1;
4758 const char *
4759 inet_ntop(int af, const void *src, char *dst, socklen_t size)
4761 if (af == AF_INET) {
4762 struct in_addr packed_addr;
4763 if (size < 16)
4764 /* Should set errno to ENOSPC. */
4765 return NULL;
4766 memcpy(&packed_addr, src, sizeof(packed_addr));
4767 return strncpy(dst, inet_ntoa(packed_addr), size);
4769 /* Should set errno to EAFNOSUPPORT */
4770 return NULL;
4773 #endif