_make_boundary(): Fix for SF bug #745478, broken boundary calculation
[python/dscho.git] / Modules / socketmodule.c
blob956c59ebffc694e96277c31444ff317d3947ea98
1 /* Socket module */
3 /*
5 This module provides an interface to Berkeley socket IPC.
7 Limitations:
9 - Only AF_INET, AF_INET6 and AF_UNIX address families are supported in a
10 portable manner, though AF_PACKET is supported under Linux.
11 - No read/write operations (use sendall/recv or makefile instead).
12 - Additional restrictions apply on some non-Unix platforms (compensated
13 for by socket.py).
15 Module interface:
17 - socket.error: exception raised for socket specific errors
18 - socket.gaierror: exception raised for getaddrinfo/getnameinfo errors,
19 a subclass of socket.error
20 - socket.herror: exception raised for gethostby* errors,
21 a subclass of socket.error
22 - socket.fromfd(fd, family, type[, proto]) --> new socket object (created
23 from an existing file descriptor)
24 - socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')
25 - socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])
26 - socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com')
27 - socket.getprotobyname(protocolname) --> protocol number
28 - socket.getservbyname(servicename, protocolname) --> port number
29 - socket.socket([family[, type [, proto]]]) --> new socket object
30 - socket.ntohs(16 bit value) --> new int object
31 - socket.ntohl(32 bit value) --> new int object
32 - socket.htons(16 bit value) --> new int object
33 - socket.htonl(32 bit value) --> new int object
34 - socket.getaddrinfo(host, port [, family, socktype, proto, flags])
35 --> List of (family, socktype, proto, canonname, sockaddr)
36 - socket.getnameinfo(sockaddr, flags) --> (host, port)
37 - socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
38 - socket.has_ipv6: boolean value indicating if IPv6 is supported
39 - socket.inet_aton(IP address) -> 32-bit packed IP representation
40 - socket.inet_ntoa(packed IP) -> IP address string
41 - socket.getdefaulttimeout() -> None | float
42 - socket.setdefaulttimeout(None | float)
43 - an Internet socket address is a pair (hostname, port)
44 where hostname can be anything recognized by gethostbyname()
45 (including the dd.dd.dd.dd notation) and port is in host byte order
46 - where a hostname is returned, the dd.dd.dd.dd notation is used
47 - a UNIX domain socket address is a string specifying the pathname
48 - an AF_PACKET socket address is a tuple containing a string
49 specifying the ethernet interface and an integer specifying
50 the Ethernet protocol number to be received. For example:
51 ("eth0",0x1234). Optional 3rd,4th,5th elements in the tuple
52 specify packet-type and ha-type/addr -- these are ignored by
53 networking code, but accepted since they are returned by the
54 getsockname() method.
56 Local naming conventions:
58 - names starting with sock_ are socket object methods
59 - names starting with socket_ are module-level functions
60 - names starting with PySocket are exported through socketmodule.h
64 #include "Python.h"
66 #undef MAX
67 #define MAX(x, y) ((x) < (y) ? (y) : (x))
69 /* Socket object documentation */
70 PyDoc_STRVAR(sock_doc,
71 "socket([family[, type[, proto]]]) -> socket object\n\
72 \n\
73 Open a socket of the given type. The family argument specifies the\n\
74 address family; it defaults to AF_INET. The type argument specifies\n\
75 whether this is a stream (SOCK_STREAM, this is the default)\n\
76 or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0,\n\
77 specifying the default protocol. Keyword arguments are accepted.\n\
78 \n\
79 A socket object represents one endpoint of a network connection.\n\
80 \n\
81 Methods of socket objects (keyword arguments not allowed):\n\
82 \n\
83 accept() -- accept a connection, returning new socket and client address\n\
84 bind(addr) -- bind the socket to a local address\n\
85 close() -- close the socket\n\
86 connect(addr) -- connect the socket to a remote address\n\
87 connect_ex(addr) -- connect, return an error code instead of an exception\n\
88 dup() -- return a new socket object identical to the current one [*]\n\
89 fileno() -- return underlying file descriptor\n\
90 getpeername() -- return remote address [*]\n\
91 getsockname() -- return local address\n\
92 getsockopt(level, optname[, buflen]) -- get socket options\n\
93 gettimeout() -- return timeout or None\n\
94 listen(n) -- start listening for incoming connections\n\
95 makefile([mode, [bufsize]]) -- return a file object for the socket [*]\n\
96 recv(buflen[, flags]) -- receive data\n\
97 recvfrom(buflen[, flags]) -- receive data and sender's address\n\
98 sendall(data[, flags]) -- send all data\n\
99 send(data[, flags]) -- send data, may not send all of it\n\
100 sendto(data[, flags], addr) -- send data to a given address\n\
101 setblocking(0 | 1) -- set or clear the blocking I/O flag\n\
102 setsockopt(level, optname, value) -- set socket options\n\
103 settimeout(None | float) -- set or clear the timeout\n\
104 shutdown(how) -- shut down traffic in one or both directions\n\
106 [*] not available on all platforms!");
108 /* XXX This is a terrible mess of of platform-dependent preprocessor hacks.
109 I hope some day someone can clean this up please... */
111 /* Hacks for gethostbyname_r(). On some non-Linux platforms, the configure
112 script doesn't get this right, so we hardcode some platform checks below.
113 On the other hand, not all Linux versions agree, so there the settings
114 computed by the configure script are needed! */
116 #ifndef linux
117 # undef HAVE_GETHOSTBYNAME_R_3_ARG
118 # undef HAVE_GETHOSTBYNAME_R_5_ARG
119 # undef HAVE_GETHOSTBYNAME_R_6_ARG
120 #endif
122 #ifndef WITH_THREAD
123 # undef HAVE_GETHOSTBYNAME_R
124 #endif
126 #ifdef HAVE_GETHOSTBYNAME_R
127 # if defined(_AIX) || defined(__osf__)
128 # define HAVE_GETHOSTBYNAME_R_3_ARG
129 # elif defined(__sun) || defined(__sgi)
130 # define HAVE_GETHOSTBYNAME_R_5_ARG
131 # elif defined(linux)
132 /* Rely on the configure script */
133 # else
134 # undef HAVE_GETHOSTBYNAME_R
135 # endif
136 #endif
138 #if !defined(HAVE_GETHOSTBYNAME_R) && defined(WITH_THREAD) && \
139 !defined(MS_WINDOWS)
140 # define USE_GETHOSTBYNAME_LOCK
141 #endif
143 /* On systems on which getaddrinfo() is believed to not be thread-safe,
144 (this includes the getaddrinfo emulation) protect access with a lock. */
145 #if defined(WITH_THREAD) && (defined(__APPLE__) || defined(__FreeBSD__) || \
146 defined(__OpenBSD__) || defined(__NetBSD__) || !defined(HAVE_GETADDRINFO))
147 #define USE_GETADDRINFO_LOCK
148 #endif
150 #ifdef USE_GETADDRINFO_LOCK
151 #define ACQUIRE_GETADDRINFO_LOCK PyThread_acquire_lock(netdb_lock, 1);
152 #define RELEASE_GETADDRINFO_LOCK PyThread_release_lock(netdb_lock);
153 #else
154 #define ACQUIRE_GETADDRINFO_LOCK
155 #define RELEASE_GETADDRINFO_LOCK
156 #endif
158 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
159 # include "pythread.h"
160 #endif
162 #if defined(PYCC_VACPP)
163 # include <types.h>
164 # include <io.h>
165 # include <sys/ioctl.h>
166 # include <utils.h>
167 # include <ctype.h>
168 #endif
170 #if defined(__VMS)
171 #if ! defined(_SOCKADDR_LEN)
172 # ifdef getaddrinfo
173 # undef getaddrinfo
174 # endif
175 # include "TCPIP_IOCTL_ROUTINE"
176 #else
177 # include <ioctl.h>
178 #endif
179 #endif
181 #if defined(PYOS_OS2)
182 # define INCL_DOS
183 # define INCL_DOSERRORS
184 # define INCL_NOPMAPI
185 # include <os2.h>
186 #endif
188 #if defined(__sgi)&&_COMPILER_VERSION>700 && !_SGIAPI
189 /* make sure that the reentrant (gethostbyaddr_r etc)
190 functions are declared correctly if compiling with
191 MIPSPro 7.x in ANSI C mode (default) */
192 #define _SGIAPI 1
193 #include "netdb.h"
194 #endif
196 /* Generic includes */
197 #include <sys/types.h>
198 #include <signal.h>
200 /* Generic socket object definitions and includes */
201 #define PySocket_BUILDING_SOCKET
202 #include "socketmodule.h"
204 /* Addressing includes */
206 #ifndef MS_WINDOWS
208 /* Non-MS WINDOWS includes */
209 # include <netdb.h>
211 /* Headers needed for inet_ntoa() and inet_addr() */
212 # ifdef __BEOS__
213 # include <net/netdb.h>
214 # elif defined(PYOS_OS2) && defined(PYCC_VACPP)
215 # include <netdb.h>
216 typedef size_t socklen_t;
217 # else
218 # include <arpa/inet.h>
219 # endif
221 # ifndef RISCOS
222 # include <fcntl.h>
223 # else
224 # include <sys/ioctl.h>
225 # include <socklib.h>
226 # define NO_DUP
227 int h_errno; /* not used */
228 # define INET_ADDRSTRLEN 16
229 # endif
231 #else
233 /* MS_WINDOWS includes */
234 # include <fcntl.h>
236 #endif
238 #ifdef HAVE_STDDEF_H
239 # include <stddef.h>
240 #endif
242 #ifndef offsetof
243 # define offsetof(type, member) ((size_t)(&((type *)0)->member))
244 #endif
246 #ifndef O_NONBLOCK
247 # define O_NONBLOCK O_NDELAY
248 #endif
250 #include "addrinfo.h"
252 #ifndef HAVE_INET_PTON
253 int inet_pton(int af, const char *src, void *dst);
254 const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
255 #endif
257 #ifdef __APPLE__
258 /* On OS X, getaddrinfo returns no error indication of lookup
259 failure, so we must use the emulation instead of the libinfo
260 implementation. Unfortunately, performing an autoconf test
261 for this bug would require DNS access for the machine performing
262 the configuration, which is not acceptable. Therefore, we
263 determine the bug just by checking for __APPLE__. If this bug
264 gets ever fixed, perhaps checking for sys/version.h would be
265 appropriate, which is 10/0 on the system with the bug. */
266 #ifndef HAVE_GETNAMEINFO
267 /* This bug seems to be fixed in Jaguar. Ths easiest way I could
268 Find to check for Jaguar is that it has getnameinfo(), which
269 older releases don't have */
270 #undef HAVE_GETADDRINFO
271 #endif
272 #endif
274 /* I know this is a bad practice, but it is the easiest... */
275 #if !defined(HAVE_GETADDRINFO)
276 /* avoid clashes with the C library definition of the symbol. */
277 #define getaddrinfo fake_getaddrinfo
278 #define gai_strerror fake_gai_strerror
279 #define freeaddrinfo fake_freeaddrinfo
280 #include "getaddrinfo.c"
281 #endif
282 #if !defined(HAVE_GETNAMEINFO)
283 #define getnameinfo fake_getnameinfo
284 #include "getnameinfo.c"
285 #endif
287 #if defined(MS_WINDOWS) || defined(__BEOS__)
288 /* BeOS suffers from the same socket dichotomy as Win32... - [cjh] */
289 /* seem to be a few differences in the API */
290 #define SOCKETCLOSE closesocket
291 #define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */
292 #endif
294 #ifdef MS_WIN32
295 #define EAFNOSUPPORT WSAEAFNOSUPPORT
296 #define snprintf _snprintf
297 #endif
299 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
300 #define SOCKETCLOSE soclose
301 #define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
302 #endif
304 #ifndef SOCKETCLOSE
305 #define SOCKETCLOSE close
306 #endif
308 #ifdef __VMS
309 /* TCP/IP Services for VMS uses a maximum send/revc buffer length of 65535 */
310 #define SEGMENT_SIZE 65535
311 #endif
314 * Constants for getnameinfo()
316 #if !defined(NI_MAXHOST)
317 #define NI_MAXHOST 1025
318 #endif
319 #if !defined(NI_MAXSERV)
320 #define NI_MAXSERV 32
321 #endif
323 /* XXX There's a problem here: *static* functions are not supposed to have
324 a Py prefix (or use CapitalizedWords). Later... */
326 /* Global variable holding the exception type for errors detected
327 by this module (but not argument type or memory errors, etc.). */
328 static PyObject *socket_error;
329 static PyObject *socket_herror;
330 static PyObject *socket_gaierror;
332 #ifdef RISCOS
333 /* Global variable which is !=0 if Python is running in a RISC OS taskwindow */
334 static int taskwindow;
335 #endif
337 /* A forward reference to the socket type object.
338 The sock_type variable contains pointers to various functions,
339 some of which call new_sockobject(), which uses sock_type, so
340 there has to be a circular reference. */
341 static PyTypeObject sock_type;
343 /* Convenience function to raise an error according to errno
344 and return a NULL pointer from a function. */
346 static PyObject *
347 set_error(void)
349 #ifdef MS_WINDOWS
350 int err_no = WSAGetLastError();
351 static struct {
352 int no;
353 const char *msg;
354 } *msgp, msgs[] = {
355 {WSAEINTR, "Interrupted system call"},
356 {WSAEBADF, "Bad file descriptor"},
357 {WSAEACCES, "Permission denied"},
358 {WSAEFAULT, "Bad address"},
359 {WSAEINVAL, "Invalid argument"},
360 {WSAEMFILE, "Too many open files"},
361 {WSAEWOULDBLOCK,
362 "The socket operation could not complete "
363 "without blocking"},
364 {WSAEINPROGRESS, "Operation now in progress"},
365 {WSAEALREADY, "Operation already in progress"},
366 {WSAENOTSOCK, "Socket operation on non-socket"},
367 {WSAEDESTADDRREQ, "Destination address required"},
368 {WSAEMSGSIZE, "Message too long"},
369 {WSAEPROTOTYPE, "Protocol wrong type for socket"},
370 {WSAENOPROTOOPT, "Protocol not available"},
371 {WSAEPROTONOSUPPORT, "Protocol not supported"},
372 {WSAESOCKTNOSUPPORT, "Socket type not supported"},
373 {WSAEOPNOTSUPP, "Operation not supported"},
374 {WSAEPFNOSUPPORT, "Protocol family not supported"},
375 {WSAEAFNOSUPPORT, "Address family not supported"},
376 {WSAEADDRINUSE, "Address already in use"},
377 {WSAEADDRNOTAVAIL, "Can't assign requested address"},
378 {WSAENETDOWN, "Network is down"},
379 {WSAENETUNREACH, "Network is unreachable"},
380 {WSAENETRESET, "Network dropped connection on reset"},
381 {WSAECONNABORTED, "Software caused connection abort"},
382 {WSAECONNRESET, "Connection reset by peer"},
383 {WSAENOBUFS, "No buffer space available"},
384 {WSAEISCONN, "Socket is already connected"},
385 {WSAENOTCONN, "Socket is not connected"},
386 {WSAESHUTDOWN, "Can't send after socket shutdown"},
387 {WSAETOOMANYREFS, "Too many references: can't splice"},
388 {WSAETIMEDOUT, "Operation timed out"},
389 {WSAECONNREFUSED, "Connection refused"},
390 {WSAELOOP, "Too many levels of symbolic links"},
391 {WSAENAMETOOLONG, "File name too long"},
392 {WSAEHOSTDOWN, "Host is down"},
393 {WSAEHOSTUNREACH, "No route to host"},
394 {WSAENOTEMPTY, "Directory not empty"},
395 {WSAEPROCLIM, "Too many processes"},
396 {WSAEUSERS, "Too many users"},
397 {WSAEDQUOT, "Disc quota exceeded"},
398 {WSAESTALE, "Stale NFS file handle"},
399 {WSAEREMOTE, "Too many levels of remote in path"},
400 {WSASYSNOTREADY, "Network subsystem is unvailable"},
401 {WSAVERNOTSUPPORTED, "WinSock version is not supported"},
402 {WSANOTINITIALISED,
403 "Successful WSAStartup() not yet performed"},
404 {WSAEDISCON, "Graceful shutdown in progress"},
405 /* Resolver errors */
406 {WSAHOST_NOT_FOUND, "No such host is known"},
407 {WSATRY_AGAIN, "Host not found, or server failed"},
408 {WSANO_RECOVERY, "Unexpected server error encountered"},
409 {WSANO_DATA, "Valid name without requested data"},
410 {WSANO_ADDRESS, "No address, look for MX record"},
411 {0, NULL}
413 if (err_no) {
414 PyObject *v;
415 const char *msg = "winsock error";
417 for (msgp = msgs; msgp->msg; msgp++) {
418 if (err_no == msgp->no) {
419 msg = msgp->msg;
420 break;
424 v = Py_BuildValue("(is)", err_no, msg);
425 if (v != NULL) {
426 PyErr_SetObject(socket_error, v);
427 Py_DECREF(v);
429 return NULL;
431 else
432 #endif
434 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
435 if (sock_errno() != NO_ERROR) {
436 APIRET rc;
437 ULONG msglen;
438 char outbuf[100];
439 int myerrorcode = sock_errno();
441 /* Retrieve socket-related error message from MPTN.MSG file */
442 rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf),
443 myerrorcode - SOCBASEERR + 26,
444 "mptn.msg",
445 &msglen);
446 if (rc == NO_ERROR) {
447 PyObject *v;
449 /* OS/2 doesn't guarantee a terminator */
450 outbuf[msglen] = '\0';
451 if (strlen(outbuf) > 0) {
452 /* If non-empty msg, trim CRLF */
453 char *lastc = &outbuf[ strlen(outbuf)-1 ];
454 while (lastc > outbuf && isspace(*lastc)) {
455 /* Trim trailing whitespace (CRLF) */
456 *lastc-- = '\0';
459 v = Py_BuildValue("(is)", myerrorcode, outbuf);
460 if (v != NULL) {
461 PyErr_SetObject(socket_error, v);
462 Py_DECREF(v);
464 return NULL;
467 #endif
469 #if defined(RISCOS)
470 if (_inet_error.errnum != NULL) {
471 PyObject *v;
472 v = Py_BuildValue("(is)", errno, _inet_err());
473 if (v != NULL) {
474 PyErr_SetObject(socket_error, v);
475 Py_DECREF(v);
477 return NULL;
479 #endif
481 return PyErr_SetFromErrno(socket_error);
485 static PyObject *
486 set_herror(int h_error)
488 PyObject *v;
490 #ifdef HAVE_HSTRERROR
491 v = Py_BuildValue("(is)", h_error, (char *)hstrerror(h_error));
492 #else
493 v = Py_BuildValue("(is)", h_error, "host not found");
494 #endif
495 if (v != NULL) {
496 PyErr_SetObject(socket_herror, v);
497 Py_DECREF(v);
500 return NULL;
504 static PyObject *
505 set_gaierror(int error)
507 PyObject *v;
509 #ifdef EAI_SYSTEM
510 /* EAI_SYSTEM is not available on Windows XP. */
511 if (error == EAI_SYSTEM)
512 return set_error();
513 #endif
515 #ifdef HAVE_GAI_STRERROR
516 v = Py_BuildValue("(is)", error, gai_strerror(error));
517 #else
518 v = Py_BuildValue("(is)", error, "getaddrinfo failed");
519 #endif
520 if (v != NULL) {
521 PyErr_SetObject(socket_gaierror, v);
522 Py_DECREF(v);
525 return NULL;
528 /* Function to perform the setting of socket blocking mode
529 internally. block = (1 | 0). */
530 static int
531 internal_setblocking(PySocketSockObject *s, int block)
533 #ifndef RISCOS
534 #ifndef MS_WINDOWS
535 int delay_flag;
536 #endif
537 #endif
539 Py_BEGIN_ALLOW_THREADS
540 #ifdef __BEOS__
541 block = !block;
542 setsockopt(s->sock_fd, SOL_SOCKET, SO_NONBLOCK,
543 (void *)(&block), sizeof(int));
544 #else
545 #ifndef RISCOS
546 #ifndef MS_WINDOWS
547 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
548 block = !block;
549 ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block));
550 #elif defined(__VMS)
551 block = !block;
552 ioctl(s->sock_fd, FIONBIO, (char *)&block);
553 #else /* !PYOS_OS2 && !_VMS */
554 delay_flag = fcntl(s->sock_fd, F_GETFL, 0);
555 if (block)
556 delay_flag &= (~O_NONBLOCK);
557 else
558 delay_flag |= O_NONBLOCK;
559 fcntl(s->sock_fd, F_SETFL, delay_flag);
560 #endif /* !PYOS_OS2 */
561 #else /* MS_WINDOWS */
562 block = !block;
563 ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
564 #endif /* MS_WINDOWS */
565 #else /* RISCOS */
566 block = !block;
567 socketioctl(s->sock_fd, FIONBIO, (u_long*)&block);
568 #endif /* RISCOS */
569 #endif /* __BEOS__ */
570 Py_END_ALLOW_THREADS
572 /* Since these don't return anything */
573 return 1;
576 /* Do a select() on the socket, if necessary (sock_timeout > 0).
577 The argument writing indicates the direction.
578 This does not raise an exception or return a success indicator;
579 we'll let the actual socket call do that. */
580 static void
581 internal_select(PySocketSockObject *s, int writing)
583 fd_set fds;
584 struct timeval tv;
586 /* Nothing to do unless we're in timeout mode (not non-blocking) */
587 if (s->sock_timeout <= 0.0)
588 return;
590 /* Guard against closed socket */
591 if (s->sock_fd < 0)
592 return;
594 /* Construct the arguments to select */
595 tv.tv_sec = (int)s->sock_timeout;
596 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
597 FD_ZERO(&fds);
598 FD_SET(s->sock_fd, &fds);
600 /* See if the socket is ready */
601 if (writing)
602 select(s->sock_fd+1, NULL, &fds, NULL, &tv);
603 else
604 select(s->sock_fd+1, &fds, NULL, NULL, &tv);
607 /* Initialize a new socket object. */
609 static double defaulttimeout = -1.0; /* Default timeout for new sockets */
611 PyMODINIT_FUNC
612 init_sockobject(PySocketSockObject *s,
613 SOCKET_T fd, int family, int type, int proto)
615 #ifdef RISCOS
616 int block = 1;
617 #endif
618 s->sock_fd = fd;
619 s->sock_family = family;
620 s->sock_type = type;
621 s->sock_proto = proto;
622 s->sock_timeout = defaulttimeout;
624 s->errorhandler = &set_error;
626 if (defaulttimeout >= 0.0)
627 internal_setblocking(s, 0);
629 #ifdef RISCOS
630 if (taskwindow)
631 socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
632 #endif
636 /* Create a new socket object.
637 This just creates the object and initializes it.
638 If the creation fails, return NULL and set an exception (implicit
639 in NEWOBJ()). */
641 static PySocketSockObject *
642 new_sockobject(SOCKET_T fd, int family, int type, int proto)
644 PySocketSockObject *s;
645 s = (PySocketSockObject *)
646 PyType_GenericNew(&sock_type, NULL, NULL);
647 if (s != NULL)
648 init_sockobject(s, fd, family, type, proto);
649 return s;
653 /* Lock to allow python interpreter to continue, but only allow one
654 thread to be in gethostbyname or getaddrinfo */
655 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
656 PyThread_type_lock netdb_lock;
657 #endif
660 /* Convert a string specifying a host name or one of a few symbolic
661 names to a numeric IP address. This usually calls gethostbyname()
662 to do the work; the names "" and "<broadcast>" are special.
663 Return the length (IPv4 should be 4 bytes), or negative if
664 an error occurred; then an exception is raised. */
666 static int
667 setipaddr(char *name, struct sockaddr *addr_ret, size_t addr_ret_size, int af)
669 struct addrinfo hints, *res;
670 int error;
671 int d1, d2, d3, d4;
672 char ch;
674 memset((void *) addr_ret, '\0', sizeof(*addr_ret));
675 if (name[0] == '\0') {
676 int siz;
677 memset(&hints, 0, sizeof(hints));
678 hints.ai_family = af;
679 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
680 hints.ai_flags = AI_PASSIVE;
681 Py_BEGIN_ALLOW_THREADS
682 ACQUIRE_GETADDRINFO_LOCK
683 error = getaddrinfo(NULL, "0", &hints, &res);
684 Py_END_ALLOW_THREADS
685 /* We assume that those thread-unsafe getaddrinfo() versions
686 *are* safe regarding their return value, ie. that a
687 subsequent call to getaddrinfo() does not destroy the
688 outcome of the first call. */
689 RELEASE_GETADDRINFO_LOCK
690 if (error) {
691 set_gaierror(error);
692 return -1;
694 switch (res->ai_family) {
695 case AF_INET:
696 siz = 4;
697 break;
698 #ifdef ENABLE_IPV6
699 case AF_INET6:
700 siz = 16;
701 break;
702 #endif
703 default:
704 freeaddrinfo(res);
705 PyErr_SetString(socket_error,
706 "unsupported address family");
707 return -1;
709 if (res->ai_next) {
710 freeaddrinfo(res);
711 PyErr_SetString(socket_error,
712 "wildcard resolved to multiple address");
713 return -1;
715 if (res->ai_addrlen < addr_ret_size)
716 addr_ret_size = res->ai_addrlen;
717 memcpy(addr_ret, res->ai_addr, addr_ret_size);
718 freeaddrinfo(res);
719 return siz;
721 if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
722 struct sockaddr_in *sin;
723 if (af != AF_INET && af != AF_UNSPEC) {
724 PyErr_SetString(socket_error,
725 "address family mismatched");
726 return -1;
728 sin = (struct sockaddr_in *)addr_ret;
729 memset((void *) sin, '\0', sizeof(*sin));
730 sin->sin_family = AF_INET;
731 #ifdef HAVE_SOCKADDR_SA_LEN
732 sin->sin_len = sizeof(*sin);
733 #endif
734 sin->sin_addr.s_addr = INADDR_BROADCAST;
735 return sizeof(sin->sin_addr);
737 if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 &&
738 0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 &&
739 0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) {
740 struct sockaddr_in *sin;
741 sin = (struct sockaddr_in *)addr_ret;
742 sin->sin_addr.s_addr = htonl(
743 ((long) d1 << 24) | ((long) d2 << 16) |
744 ((long) d3 << 8) | ((long) d4 << 0));
745 sin->sin_family = AF_INET;
746 #ifdef HAVE_SOCKADDR_SA_LEN
747 sin->sin_len = sizeof(*sin);
748 #endif
749 return 4;
751 memset(&hints, 0, sizeof(hints));
752 hints.ai_family = af;
753 Py_BEGIN_ALLOW_THREADS
754 ACQUIRE_GETADDRINFO_LOCK
755 error = getaddrinfo(name, NULL, &hints, &res);
756 #if defined(__digital__) && defined(__unix__)
757 if (error == EAI_NONAME && af == AF_UNSPEC) {
758 /* On Tru64 V5.1, numeric-to-addr conversion fails
759 if no address family is given. Assume IPv4 for now.*/
760 hints.ai_family = AF_INET;
761 error = getaddrinfo(name, NULL, &hints, &res);
763 #endif
764 Py_END_ALLOW_THREADS
765 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
766 if (error) {
767 set_gaierror(error);
768 return -1;
770 if (res->ai_addrlen < addr_ret_size)
771 addr_ret_size = res->ai_addrlen;
772 memcpy((char *) addr_ret, res->ai_addr, addr_ret_size);
773 freeaddrinfo(res);
774 switch (addr_ret->sa_family) {
775 case AF_INET:
776 return 4;
777 #ifdef ENABLE_IPV6
778 case AF_INET6:
779 return 16;
780 #endif
781 default:
782 PyErr_SetString(socket_error, "unknown address family");
783 return -1;
788 /* Create a string object representing an IP address.
789 This is always a string of the form 'dd.dd.dd.dd' (with variable
790 size numbers). */
792 static PyObject *
793 makeipaddr(struct sockaddr *addr, int addrlen)
795 char buf[NI_MAXHOST];
796 int error;
798 error = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0,
799 NI_NUMERICHOST);
800 if (error) {
801 set_gaierror(error);
802 return NULL;
804 return PyString_FromString(buf);
808 /* Create an object representing the given socket address,
809 suitable for passing it back to bind(), connect() etc.
810 The family field of the sockaddr structure is inspected
811 to determine what kind of address it really is. */
813 /*ARGSUSED*/
814 static PyObject *
815 makesockaddr(int sockfd, struct sockaddr *addr, int addrlen)
817 if (addrlen == 0) {
818 /* No address -- may be recvfrom() from known socket */
819 Py_INCREF(Py_None);
820 return Py_None;
823 #ifdef __BEOS__
824 /* XXX: BeOS version of accept() doesn't set family correctly */
825 addr->sa_family = AF_INET;
826 #endif
828 switch (addr->sa_family) {
830 case AF_INET:
832 struct sockaddr_in *a;
833 PyObject *addrobj = makeipaddr(addr, sizeof(*a));
834 PyObject *ret = NULL;
835 if (addrobj) {
836 a = (struct sockaddr_in *)addr;
837 ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
838 Py_DECREF(addrobj);
840 return ret;
843 #if defined(AF_UNIX) && !defined(PYOS_OS2)
844 case AF_UNIX:
846 struct sockaddr_un *a = (struct sockaddr_un *) addr;
847 return PyString_FromString(a->sun_path);
849 #endif /* AF_UNIX */
851 #ifdef ENABLE_IPV6
852 case AF_INET6:
854 struct sockaddr_in6 *a;
855 PyObject *addrobj = makeipaddr(addr, sizeof(*a));
856 PyObject *ret = NULL;
857 if (addrobj) {
858 a = (struct sockaddr_in6 *)addr;
859 ret = Py_BuildValue("Oiii",
860 addrobj,
861 ntohs(a->sin6_port),
862 a->sin6_flowinfo,
863 a->sin6_scope_id);
864 Py_DECREF(addrobj);
866 return ret;
868 #endif
870 #ifdef HAVE_NETPACKET_PACKET_H
871 case AF_PACKET:
873 struct sockaddr_ll *a = (struct sockaddr_ll *)addr;
874 char *ifname = "";
875 struct ifreq ifr;
876 /* need to look up interface name give index */
877 if (a->sll_ifindex) {
878 ifr.ifr_ifindex = a->sll_ifindex;
879 if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0)
880 ifname = ifr.ifr_name;
882 return Py_BuildValue("shbhs#",
883 ifname,
884 ntohs(a->sll_protocol),
885 a->sll_pkttype,
886 a->sll_hatype,
887 a->sll_addr,
888 a->sll_halen);
890 #endif
892 /* More cases here... */
894 default:
895 /* If we don't know the address family, don't raise an
896 exception -- return it as a tuple. */
897 return Py_BuildValue("is#",
898 addr->sa_family,
899 addr->sa_data,
900 sizeof(addr->sa_data));
906 /* Parse a socket address argument according to the socket object's
907 address family. Return 1 if the address was in the proper format,
908 0 of not. The address is returned through addr_ret, its length
909 through len_ret. */
911 static int
912 getsockaddrarg(PySocketSockObject *s, PyObject *args,
913 struct sockaddr **addr_ret, int *len_ret)
915 switch (s->sock_family) {
917 #if defined(AF_UNIX) && !defined(PYOS_OS2)
918 case AF_UNIX:
920 struct sockaddr_un* addr;
921 char *path;
922 int len;
923 addr = (struct sockaddr_un*)&(s->sock_addr).un;
924 if (!PyArg_Parse(args, "t#", &path, &len))
925 return 0;
926 if (len > sizeof addr->sun_path) {
927 PyErr_SetString(socket_error,
928 "AF_UNIX path too long");
929 return 0;
931 addr->sun_family = s->sock_family;
932 memcpy(addr->sun_path, path, len);
933 addr->sun_path[len] = 0;
934 *addr_ret = (struct sockaddr *) addr;
935 *len_ret = len + sizeof(*addr) - sizeof(addr->sun_path);
936 return 1;
938 #endif /* AF_UNIX */
940 case AF_INET:
942 struct sockaddr_in* addr;
943 char *host;
944 int port;
945 addr=(struct sockaddr_in*)&(s->sock_addr).in;
946 if (!PyTuple_Check(args)) {
947 PyErr_Format(
948 PyExc_TypeError,
949 "getsockaddrarg: "
950 "AF_INET address must be tuple, not %.500s",
951 args->ob_type->tp_name);
952 return 0;
954 if (!PyArg_ParseTuple(args, "eti:getsockaddrarg",
955 "idna", &host, &port))
956 return 0;
957 if (setipaddr(host, (struct sockaddr *)addr, sizeof(*addr), AF_INET) < 0)
958 return 0;
959 addr->sin_family = AF_INET;
960 addr->sin_port = htons((short)port);
961 *addr_ret = (struct sockaddr *) addr;
962 *len_ret = sizeof *addr;
963 return 1;
966 #ifdef ENABLE_IPV6
967 case AF_INET6:
969 struct sockaddr_in6* addr;
970 char *host;
971 int port, flowinfo, scope_id;
972 addr = (struct sockaddr_in6*)&(s->sock_addr).in6;
973 flowinfo = scope_id = 0;
974 if (!PyArg_ParseTuple(args, "eti|ii",
975 "idna", &host, &port, &flowinfo,
976 &scope_id)) {
977 return 0;
979 if (setipaddr(host, (struct sockaddr *)addr, sizeof(*addr), AF_INET6) < 0)
980 return 0;
981 addr->sin6_family = s->sock_family;
982 addr->sin6_port = htons((short)port);
983 addr->sin6_flowinfo = flowinfo;
984 addr->sin6_scope_id = scope_id;
985 *addr_ret = (struct sockaddr *) addr;
986 *len_ret = sizeof *addr;
987 return 1;
989 #endif
991 #ifdef HAVE_NETPACKET_PACKET_H
992 case AF_PACKET:
994 struct sockaddr_ll* addr;
995 struct ifreq ifr;
996 char *interfaceName;
997 int protoNumber;
998 int hatype = 0;
999 int pkttype = 0;
1000 char *haddr;
1002 if (!PyArg_ParseTuple(args, "si|iis", &interfaceName,
1003 &protoNumber, &pkttype, &hatype, &haddr))
1004 return 0;
1005 strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name));
1006 ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
1007 if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
1008 s->errorhandler();
1009 return 0;
1011 addr = &(s->sock_addr.ll);
1012 addr->sll_family = AF_PACKET;
1013 addr->sll_protocol = htons((short)protoNumber);
1014 addr->sll_ifindex = ifr.ifr_ifindex;
1015 addr->sll_pkttype = pkttype;
1016 addr->sll_hatype = hatype;
1017 *addr_ret = (struct sockaddr *) addr;
1018 *len_ret = sizeof *addr;
1019 return 1;
1021 #endif
1023 /* More cases here... */
1025 default:
1026 PyErr_SetString(socket_error, "getsockaddrarg: bad family");
1027 return 0;
1033 /* Get the address length according to the socket object's address family.
1034 Return 1 if the family is known, 0 otherwise. The length is returned
1035 through len_ret. */
1037 static int
1038 getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
1040 switch (s->sock_family) {
1042 #if defined(AF_UNIX) && !defined(PYOS_OS2)
1043 case AF_UNIX:
1045 *len_ret = sizeof (struct sockaddr_un);
1046 return 1;
1048 #endif /* AF_UNIX */
1050 case AF_INET:
1052 *len_ret = sizeof (struct sockaddr_in);
1053 return 1;
1056 #ifdef ENABLE_IPV6
1057 case AF_INET6:
1059 *len_ret = sizeof (struct sockaddr_in6);
1060 return 1;
1062 #endif
1064 #ifdef HAVE_NETPACKET_PACKET_H
1065 case AF_PACKET:
1067 *len_ret = sizeof (struct sockaddr_ll);
1068 return 1;
1070 #endif
1072 /* More cases here... */
1074 default:
1075 PyErr_SetString(socket_error, "getsockaddrlen: bad family");
1076 return 0;
1082 /* s.accept() method */
1084 static PyObject *
1085 sock_accept(PySocketSockObject *s)
1087 char addrbuf[256];
1088 SOCKET_T newfd;
1089 socklen_t addrlen;
1090 PyObject *sock = NULL;
1091 PyObject *addr = NULL;
1092 PyObject *res = NULL;
1094 if (!getsockaddrlen(s, &addrlen))
1095 return NULL;
1096 memset(addrbuf, 0, addrlen);
1098 Py_BEGIN_ALLOW_THREADS
1099 internal_select(s, 0);
1100 newfd = accept(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
1101 Py_END_ALLOW_THREADS
1103 #ifdef MS_WINDOWS
1104 if (newfd == INVALID_SOCKET)
1105 #else
1106 if (newfd < 0)
1107 #endif
1108 return s->errorhandler();
1110 /* Create the new object with unspecified family,
1111 to avoid calls to bind() etc. on it. */
1112 sock = (PyObject *) new_sockobject(newfd,
1113 s->sock_family,
1114 s->sock_type,
1115 s->sock_proto);
1117 if (sock == NULL) {
1118 SOCKETCLOSE(newfd);
1119 goto finally;
1121 addr = makesockaddr(s->sock_fd, (struct sockaddr *)addrbuf,
1122 addrlen);
1123 if (addr == NULL)
1124 goto finally;
1126 res = Py_BuildValue("OO", sock, addr);
1128 finally:
1129 Py_XDECREF(sock);
1130 Py_XDECREF(addr);
1131 return res;
1134 PyDoc_STRVAR(accept_doc,
1135 "accept() -> (socket object, address info)\n\
1137 Wait for an incoming connection. Return a new socket representing the\n\
1138 connection, and the address of the client. For IP sockets, the address\n\
1139 info is a pair (hostaddr, port).");
1141 /* s.setblocking(flag) method. Argument:
1142 False -- non-blocking mode; same as settimeout(0)
1143 True -- blocking mode; same as settimeout(None)
1146 static PyObject *
1147 sock_setblocking(PySocketSockObject *s, PyObject *arg)
1149 int block;
1151 block = PyInt_AsLong(arg);
1152 if (block == -1 && PyErr_Occurred())
1153 return NULL;
1155 s->sock_timeout = block ? -1.0 : 0.0;
1156 internal_setblocking(s, block);
1158 Py_INCREF(Py_None);
1159 return Py_None;
1162 PyDoc_STRVAR(setblocking_doc,
1163 "setblocking(flag)\n\
1165 Set the socket to blocking (flag is true) or non-blocking (false).\n\
1166 setblocking(True) is equivalent to settimeout(None);\n\
1167 setblocking(False) is equivalent to settimeout(0.0).");
1169 /* s.settimeout(timeout) method. Argument:
1170 None -- no timeout, blocking mode; same as setblocking(True)
1171 0.0 -- non-blocking mode; same as setblocking(False)
1172 > 0 -- timeout mode; operations time out after timeout seconds
1173 < 0 -- illegal; raises an exception
1175 static PyObject *
1176 sock_settimeout(PySocketSockObject *s, PyObject *arg)
1178 double timeout;
1180 if (arg == Py_None)
1181 timeout = -1.0;
1182 else {
1183 timeout = PyFloat_AsDouble(arg);
1184 if (timeout < 0.0) {
1185 if (!PyErr_Occurred())
1186 PyErr_SetString(PyExc_ValueError,
1187 "Timeout value out of range");
1188 return NULL;
1192 s->sock_timeout = timeout;
1193 internal_setblocking(s, timeout < 0.0);
1195 Py_INCREF(Py_None);
1196 return Py_None;
1199 PyDoc_STRVAR(settimeout_doc,
1200 "settimeout(timeout)\n\
1202 Set a timeout on socket operations. 'timeout' can be a float,\n\
1203 giving in seconds, or None. Setting a timeout of None disables\n\
1204 the timeout feature and is equivalent to setblocking(1).\n\
1205 Setting a timeout of zero is the same as setblocking(0).");
1207 /* s.gettimeout() method.
1208 Returns the timeout associated with a socket. */
1209 static PyObject *
1210 sock_gettimeout(PySocketSockObject *s)
1212 if (s->sock_timeout < 0.0) {
1213 Py_INCREF(Py_None);
1214 return Py_None;
1216 else
1217 return PyFloat_FromDouble(s->sock_timeout);
1220 PyDoc_STRVAR(gettimeout_doc,
1221 "gettimeout() -> timeout\n\
1223 Returns the timeout in floating seconds associated with socket \n\
1224 operations. A timeout of None indicates that timeouts on socket \n\
1225 operations are disabled.");
1227 #ifdef RISCOS
1228 /* s.sleeptaskw(1 | 0) method */
1230 static PyObject *
1231 sock_sleeptaskw(PySocketSockObject *s,PyObject *arg)
1233 int block;
1234 block = PyInt_AsLong(arg);
1235 if (block == -1 && PyErr_Occurred())
1236 return NULL;
1237 Py_BEGIN_ALLOW_THREADS
1238 socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
1239 Py_END_ALLOW_THREADS
1241 Py_INCREF(Py_None);
1242 return Py_None;
1244 PyDoc_STRVAR(sleeptaskw_doc,
1245 "sleeptaskw(flag)\n\
1247 Allow sleeps in taskwindows.");
1248 #endif
1251 /* s.setsockopt() method.
1252 With an integer third argument, sets an integer option.
1253 With a string third argument, sets an option from a buffer;
1254 use optional built-in module 'struct' to encode the string. */
1256 static PyObject *
1257 sock_setsockopt(PySocketSockObject *s, PyObject *args)
1259 int level;
1260 int optname;
1261 int res;
1262 char *buf;
1263 int buflen;
1264 int flag;
1266 if (PyArg_ParseTuple(args, "iii:setsockopt",
1267 &level, &optname, &flag)) {
1268 buf = (char *) &flag;
1269 buflen = sizeof flag;
1271 else {
1272 PyErr_Clear();
1273 if (!PyArg_ParseTuple(args, "iis#:setsockopt",
1274 &level, &optname, &buf, &buflen))
1275 return NULL;
1277 res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen);
1278 if (res < 0)
1279 return s->errorhandler();
1280 Py_INCREF(Py_None);
1281 return Py_None;
1284 PyDoc_STRVAR(setsockopt_doc,
1285 "setsockopt(level, option, value)\n\
1287 Set a socket option. See the Unix manual for level and option.\n\
1288 The value argument can either be an integer or a string.");
1291 /* s.getsockopt() method.
1292 With two arguments, retrieves an integer option.
1293 With a third integer argument, retrieves a string buffer of that size;
1294 use optional built-in module 'struct' to decode the string. */
1296 static PyObject *
1297 sock_getsockopt(PySocketSockObject *s, PyObject *args)
1299 int level;
1300 int optname;
1301 int res;
1302 PyObject *buf;
1303 socklen_t buflen = 0;
1305 #ifdef __BEOS__
1306 /* We have incomplete socket support. */
1307 PyErr_SetString(socket_error, "getsockopt not supported");
1308 return NULL;
1309 #else
1311 if (!PyArg_ParseTuple(args, "ii|i:getsockopt",
1312 &level, &optname, &buflen))
1313 return NULL;
1315 if (buflen == 0) {
1316 int flag = 0;
1317 socklen_t flagsize = sizeof flag;
1318 res = getsockopt(s->sock_fd, level, optname,
1319 (void *)&flag, &flagsize);
1320 if (res < 0)
1321 return s->errorhandler();
1322 return PyInt_FromLong(flag);
1324 #ifdef __VMS
1325 if (buflen > 1024) {
1326 #else
1327 if (buflen <= 0 || buflen > 1024) {
1328 #endif
1329 PyErr_SetString(socket_error,
1330 "getsockopt buflen out of range");
1331 return NULL;
1333 buf = PyString_FromStringAndSize((char *)NULL, buflen);
1334 if (buf == NULL)
1335 return NULL;
1336 res = getsockopt(s->sock_fd, level, optname,
1337 (void *)PyString_AS_STRING(buf), &buflen);
1338 if (res < 0) {
1339 Py_DECREF(buf);
1340 return s->errorhandler();
1342 _PyString_Resize(&buf, buflen);
1343 return buf;
1344 #endif /* __BEOS__ */
1347 PyDoc_STRVAR(getsockopt_doc,
1348 "getsockopt(level, option[, buffersize]) -> value\n\
1350 Get a socket option. See the Unix manual for level and option.\n\
1351 If a nonzero buffersize argument is given, the return value is a\n\
1352 string of that length; otherwise it is an integer.");
1355 /* s.bind(sockaddr) method */
1357 static PyObject *
1358 sock_bind(PySocketSockObject *s, PyObject *addro)
1360 struct sockaddr *addr;
1361 int addrlen;
1362 int res;
1364 if (!getsockaddrarg(s, addro, &addr, &addrlen))
1365 return NULL;
1366 Py_BEGIN_ALLOW_THREADS
1367 res = bind(s->sock_fd, addr, addrlen);
1368 Py_END_ALLOW_THREADS
1369 if (res < 0)
1370 return s->errorhandler();
1371 Py_INCREF(Py_None);
1372 return Py_None;
1375 PyDoc_STRVAR(bind_doc,
1376 "bind(address)\n\
1378 Bind the socket to a local address. For IP sockets, the address is a\n\
1379 pair (host, port); the host must refer to the local host. For raw packet\n\
1380 sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");
1383 /* s.close() method.
1384 Set the file descriptor to -1 so operations tried subsequently
1385 will surely fail. */
1387 static PyObject *
1388 sock_close(PySocketSockObject *s)
1390 SOCKET_T fd;
1392 if ((fd = s->sock_fd) != -1) {
1393 s->sock_fd = -1;
1394 Py_BEGIN_ALLOW_THREADS
1395 (void) SOCKETCLOSE(fd);
1396 Py_END_ALLOW_THREADS
1398 Py_INCREF(Py_None);
1399 return Py_None;
1402 PyDoc_STRVAR(close_doc,
1403 "close()\n\
1405 Close the socket. It cannot be used after this call.");
1407 static int
1408 internal_connect(PySocketSockObject *s, struct sockaddr *addr, int addrlen)
1410 int res;
1412 res = connect(s->sock_fd, addr, addrlen);
1414 #ifdef MS_WINDOWS
1416 if (s->sock_timeout > 0.0) {
1417 if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK) {
1418 /* This is a mess. Best solution: trust select */
1419 fd_set fds;
1420 struct timeval tv;
1421 tv.tv_sec = (int)s->sock_timeout;
1422 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1423 FD_ZERO(&fds);
1424 FD_SET(s->sock_fd, &fds);
1425 res = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1426 if (res == 0)
1427 res = WSAEWOULDBLOCK;
1428 else if (res > 0)
1429 res = 0;
1430 /* else if (res < 0) an error occurred */
1434 if (res < 0)
1435 res = WSAGetLastError();
1437 #else
1439 if (s->sock_timeout > 0.0) {
1440 if (res < 0 && errno == EINPROGRESS) {
1441 internal_select(s, 1);
1442 res = connect(s->sock_fd, addr, addrlen);
1443 if (res < 0 && errno == EISCONN)
1444 res = 0;
1448 if (res < 0)
1449 res = errno;
1451 #endif
1453 return res;
1456 /* s.connect(sockaddr) method */
1458 static PyObject *
1459 sock_connect(PySocketSockObject *s, PyObject *addro)
1461 struct sockaddr *addr;
1462 int addrlen;
1463 int res;
1465 if (!getsockaddrarg(s, addro, &addr, &addrlen))
1466 return NULL;
1468 Py_BEGIN_ALLOW_THREADS
1469 res = internal_connect(s, addr, addrlen);
1470 Py_END_ALLOW_THREADS
1472 if (res != 0)
1473 return s->errorhandler();
1474 Py_INCREF(Py_None);
1475 return Py_None;
1478 PyDoc_STRVAR(connect_doc,
1479 "connect(address)\n\
1481 Connect the socket to a remote address. For IP sockets, the address\n\
1482 is a pair (host, port).");
1485 /* s.connect_ex(sockaddr) method */
1487 static PyObject *
1488 sock_connect_ex(PySocketSockObject *s, PyObject *addro)
1490 struct sockaddr *addr;
1491 int addrlen;
1492 int res;
1494 if (!getsockaddrarg(s, addro, &addr, &addrlen))
1495 return NULL;
1497 Py_BEGIN_ALLOW_THREADS
1498 res = internal_connect(s, addr, addrlen);
1499 Py_END_ALLOW_THREADS
1501 return PyInt_FromLong((long) res);
1504 PyDoc_STRVAR(connect_ex_doc,
1505 "connect_ex(address) -> errno\n\
1507 This is like connect(address), but returns an error code (the errno value)\n\
1508 instead of raising an exception when an error occurs.");
1511 /* s.fileno() method */
1513 static PyObject *
1514 sock_fileno(PySocketSockObject *s)
1516 #if SIZEOF_SOCKET_T <= SIZEOF_LONG
1517 return PyInt_FromLong((long) s->sock_fd);
1518 #else
1519 return PyLong_FromLongLong((PY_LONG_LONG)s->sock_fd);
1520 #endif
1523 PyDoc_STRVAR(fileno_doc,
1524 "fileno() -> integer\n\
1526 Return the integer file descriptor of the socket.");
1529 #ifndef NO_DUP
1530 /* s.dup() method */
1532 static PyObject *
1533 sock_dup(PySocketSockObject *s)
1535 SOCKET_T newfd;
1536 PyObject *sock;
1538 newfd = dup(s->sock_fd);
1539 if (newfd < 0)
1540 return s->errorhandler();
1541 sock = (PyObject *) new_sockobject(newfd,
1542 s->sock_family,
1543 s->sock_type,
1544 s->sock_proto);
1545 if (sock == NULL)
1546 SOCKETCLOSE(newfd);
1547 return sock;
1550 PyDoc_STRVAR(dup_doc,
1551 "dup() -> socket object\n\
1553 Return a new socket object connected to the same system resource.");
1555 #endif
1558 /* s.getsockname() method */
1560 static PyObject *
1561 sock_getsockname(PySocketSockObject *s)
1563 char addrbuf[256];
1564 int res;
1565 socklen_t addrlen;
1567 if (!getsockaddrlen(s, &addrlen))
1568 return NULL;
1569 memset(addrbuf, 0, addrlen);
1570 Py_BEGIN_ALLOW_THREADS
1571 res = getsockname(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
1572 Py_END_ALLOW_THREADS
1573 if (res < 0)
1574 return s->errorhandler();
1575 return makesockaddr(s->sock_fd, (struct sockaddr *) addrbuf, addrlen);
1578 PyDoc_STRVAR(getsockname_doc,
1579 "getsockname() -> address info\n\
1581 Return the address of the local endpoint. For IP sockets, the address\n\
1582 info is a pair (hostaddr, port).");
1585 #ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
1586 /* s.getpeername() method */
1588 static PyObject *
1589 sock_getpeername(PySocketSockObject *s)
1591 char addrbuf[256];
1592 int res;
1593 socklen_t addrlen;
1595 if (!getsockaddrlen(s, &addrlen))
1596 return NULL;
1597 memset(addrbuf, 0, addrlen);
1598 Py_BEGIN_ALLOW_THREADS
1599 res = getpeername(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
1600 Py_END_ALLOW_THREADS
1601 if (res < 0)
1602 return s->errorhandler();
1603 return makesockaddr(s->sock_fd, (struct sockaddr *) addrbuf, addrlen);
1606 PyDoc_STRVAR(getpeername_doc,
1607 "getpeername() -> address info\n\
1609 Return the address of the remote endpoint. For IP sockets, the address\n\
1610 info is a pair (hostaddr, port).");
1612 #endif /* HAVE_GETPEERNAME */
1615 /* s.listen(n) method */
1617 static PyObject *
1618 sock_listen(PySocketSockObject *s, PyObject *arg)
1620 int backlog;
1621 int res;
1623 backlog = PyInt_AsLong(arg);
1624 if (backlog == -1 && PyErr_Occurred())
1625 return NULL;
1626 Py_BEGIN_ALLOW_THREADS
1627 if (backlog < 1)
1628 backlog = 1;
1629 res = listen(s->sock_fd, backlog);
1630 Py_END_ALLOW_THREADS
1631 if (res < 0)
1632 return s->errorhandler();
1633 Py_INCREF(Py_None);
1634 return Py_None;
1637 PyDoc_STRVAR(listen_doc,
1638 "listen(backlog)\n\
1640 Enable a server to accept connections. The backlog argument must be at\n\
1641 least 1; it specifies the number of unaccepted connection that the system\n\
1642 will allow before refusing new connections.");
1645 #ifndef NO_DUP
1646 /* s.makefile(mode) method.
1647 Create a new open file object referring to a dupped version of
1648 the socket's file descriptor. (The dup() call is necessary so
1649 that the open file and socket objects may be closed independent
1650 of each other.)
1651 The mode argument specifies 'r' or 'w' passed to fdopen(). */
1653 static PyObject *
1654 sock_makefile(PySocketSockObject *s, PyObject *args)
1656 extern int fclose(FILE *);
1657 char *mode = "r";
1658 int bufsize = -1;
1659 #ifdef MS_WIN32
1660 Py_intptr_t fd;
1661 #else
1662 int fd;
1663 #endif
1664 FILE *fp;
1665 PyObject *f;
1666 #ifdef __VMS
1667 char *mode_r = "r";
1668 char *mode_w = "w";
1669 #endif
1671 if (!PyArg_ParseTuple(args, "|si:makefile", &mode, &bufsize))
1672 return NULL;
1673 #ifdef __VMS
1674 if (strcmp(mode,"rb") == 0) {
1675 mode = mode_r;
1677 else {
1678 if (strcmp(mode,"wb") == 0) {
1679 mode = mode_w;
1682 #endif
1683 #ifdef MS_WIN32
1684 if (((fd = _open_osfhandle(s->sock_fd, _O_BINARY)) < 0) ||
1685 ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL))
1686 #else
1687 if ((fd = dup(s->sock_fd)) < 0 || (fp = fdopen(fd, mode)) == NULL)
1688 #endif
1690 if (fd >= 0)
1691 SOCKETCLOSE(fd);
1692 return s->errorhandler();
1694 #ifdef USE_GUSI2
1695 /* Workaround for bug in Metrowerks MSL vs. GUSI I/O library */
1696 if (strchr(mode, 'b') != NULL)
1697 bufsize = 0;
1698 #endif
1699 f = PyFile_FromFile(fp, "<socket>", mode, fclose);
1700 if (f != NULL)
1701 PyFile_SetBufSize(f, bufsize);
1702 return f;
1705 PyDoc_STRVAR(makefile_doc,
1706 "makefile([mode[, buffersize]]) -> file object\n\
1708 Return a regular file object corresponding to the socket.\n\
1709 The mode and buffersize arguments are as for the built-in open() function.");
1711 #endif /* NO_DUP */
1714 /* s.recv(nbytes [,flags]) method */
1716 static PyObject *
1717 sock_recv(PySocketSockObject *s, PyObject *args)
1719 int len, n, flags = 0;
1720 PyObject *buf;
1721 #ifdef __VMS
1722 int read_length;
1723 char *read_buf;
1724 #endif
1726 if (!PyArg_ParseTuple(args, "i|i:recv", &len, &flags))
1727 return NULL;
1729 if (len < 0) {
1730 PyErr_SetString(PyExc_ValueError,
1731 "negative buffersize in recv");
1732 return NULL;
1735 buf = PyString_FromStringAndSize((char *) 0, len);
1736 if (buf == NULL)
1737 return NULL;
1739 #ifndef __VMS
1740 Py_BEGIN_ALLOW_THREADS
1741 internal_select(s, 0);
1742 n = recv(s->sock_fd, PyString_AS_STRING(buf), len, flags);
1743 Py_END_ALLOW_THREADS
1745 if (n < 0) {
1746 Py_DECREF(buf);
1747 return s->errorhandler();
1749 if (n != len)
1750 _PyString_Resize(&buf, n);
1751 #else
1752 read_buf = PyString_AsString(buf);
1753 read_length = len;
1754 while (read_length != 0) {
1755 unsigned int segment;
1757 segment = read_length /SEGMENT_SIZE;
1758 if (segment != 0) {
1759 segment = SEGMENT_SIZE;
1761 else {
1762 segment = read_length;
1765 Py_BEGIN_ALLOW_THREADS
1766 internal_select(s, 0);
1767 n = recv(s->sock_fd, read_buf, segment, flags);
1768 Py_END_ALLOW_THREADS
1770 if (n < 0) {
1771 Py_DECREF(buf);
1772 return s->errorhandler();
1774 if (n != read_length) {
1775 read_buf += n;
1776 break;
1779 read_length -= segment;
1780 read_buf += segment;
1782 if (_PyString_Resize(&buf, (read_buf - PyString_AsString(buf))) < 0)
1784 return NULL;
1786 #endif /* !__VMS */
1787 return buf;
1790 PyDoc_STRVAR(recv_doc,
1791 "recv(buffersize[, flags]) -> data\n\
1793 Receive up to buffersize bytes from the socket. For the optional flags\n\
1794 argument, see the Unix manual. When no data is available, block until\n\
1795 at least one byte is available or until the remote end is closed. When\n\
1796 the remote end is closed and all data is read, return the empty string.");
1799 /* s.recvfrom(nbytes [,flags]) method */
1801 static PyObject *
1802 sock_recvfrom(PySocketSockObject *s, PyObject *args)
1804 char addrbuf[256];
1805 PyObject *buf = NULL;
1806 PyObject *addr = NULL;
1807 PyObject *ret = NULL;
1808 int len, n, flags = 0;
1809 socklen_t addrlen;
1811 if (!PyArg_ParseTuple(args, "i|i:recvfrom", &len, &flags))
1812 return NULL;
1814 if (!getsockaddrlen(s, &addrlen))
1815 return NULL;
1816 buf = PyString_FromStringAndSize((char *) 0, len);
1817 if (buf == NULL)
1818 return NULL;
1820 Py_BEGIN_ALLOW_THREADS
1821 memset(addrbuf, 0, addrlen);
1822 internal_select(s, 0);
1823 n = recvfrom(s->sock_fd, PyString_AS_STRING(buf), len, flags,
1824 #ifndef MS_WINDOWS
1825 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
1826 (struct sockaddr *)addrbuf, &addrlen
1827 #else
1828 (void *)addrbuf, &addrlen
1829 #endif
1830 #else
1831 (struct sockaddr *)addrbuf, &addrlen
1832 #endif
1834 Py_END_ALLOW_THREADS
1836 if (n < 0) {
1837 Py_DECREF(buf);
1838 return s->errorhandler();
1841 if (n != len && _PyString_Resize(&buf, n) < 0)
1842 return NULL;
1844 if (!(addr = makesockaddr(s->sock_fd, (struct sockaddr *)addrbuf,
1845 addrlen)))
1846 goto finally;
1848 ret = Py_BuildValue("OO", buf, addr);
1850 finally:
1851 Py_XDECREF(addr);
1852 Py_XDECREF(buf);
1853 return ret;
1856 PyDoc_STRVAR(recvfrom_doc,
1857 "recvfrom(buffersize[, flags]) -> (data, address info)\n\
1859 Like recv(buffersize, flags) but also return the sender's address info.");
1861 /* s.send(data [,flags]) method */
1863 static PyObject *
1864 sock_send(PySocketSockObject *s, PyObject *args)
1866 char *buf;
1867 int len, n, flags = 0;
1868 #ifdef __VMS
1869 int send_length;
1870 #endif
1872 if (!PyArg_ParseTuple(args, "s#|i:send", &buf, &len, &flags))
1873 return NULL;
1875 #ifndef __VMS
1876 Py_BEGIN_ALLOW_THREADS
1877 internal_select(s, 1);
1878 n = send(s->sock_fd, buf, len, flags);
1879 Py_END_ALLOW_THREADS
1881 if (n < 0)
1882 return s->errorhandler();
1883 #else
1884 /* Divide packet into smaller segments for */
1885 /* TCP/IP Services for OpenVMS */
1886 send_length = len;
1887 while (send_length != 0) {
1888 unsigned int segment;
1890 segment = send_length / SEGMENT_SIZE;
1891 if (segment != 0) {
1892 segment = SEGMENT_SIZE;
1894 else {
1895 segment = send_length;
1897 Py_BEGIN_ALLOW_THREADS
1898 internal_select(s, 1);
1899 n = send(s->sock_fd, buf, segment, flags);
1900 Py_END_ALLOW_THREADS
1901 if (n < 0) {
1902 return s->errorhandler();
1904 send_length -= segment;
1905 buf += segment;
1906 } /* end while */
1907 #endif /* !__VMS */
1908 return PyInt_FromLong((long)n);
1911 PyDoc_STRVAR(send_doc,
1912 "send(data[, flags]) -> count\n\
1914 Send a data string to the socket. For the optional flags\n\
1915 argument, see the Unix manual. Return the number of bytes\n\
1916 sent; this may be less than len(data) if the network is busy.");
1919 /* s.sendall(data [,flags]) method */
1921 static PyObject *
1922 sock_sendall(PySocketSockObject *s, PyObject *args)
1924 char *buf;
1925 int len, n, flags = 0;
1927 if (!PyArg_ParseTuple(args, "s#|i:sendall", &buf, &len, &flags))
1928 return NULL;
1930 Py_BEGIN_ALLOW_THREADS
1931 do {
1932 internal_select(s, 1);
1933 n = send(s->sock_fd, buf, len, flags);
1934 if (n < 0)
1935 break;
1936 buf += n;
1937 len -= n;
1938 } while (len > 0);
1939 Py_END_ALLOW_THREADS
1941 if (n < 0)
1942 return s->errorhandler();
1944 Py_INCREF(Py_None);
1945 return Py_None;
1948 PyDoc_STRVAR(sendall_doc,
1949 "sendall(data[, flags])\n\
1951 Send a data string to the socket. For the optional flags\n\
1952 argument, see the Unix manual. This calls send() repeatedly\n\
1953 until all data is sent. If an error occurs, it's impossible\n\
1954 to tell how much data has been sent.");
1957 /* s.sendto(data, [flags,] sockaddr) method */
1959 static PyObject *
1960 sock_sendto(PySocketSockObject *s, PyObject *args)
1962 PyObject *addro;
1963 char *buf;
1964 struct sockaddr *addr;
1965 int addrlen, len, n, flags;
1967 flags = 0;
1968 if (!PyArg_ParseTuple(args, "s#O:sendto", &buf, &len, &addro)) {
1969 PyErr_Clear();
1970 if (!PyArg_ParseTuple(args, "s#iO:sendto",
1971 &buf, &len, &flags, &addro))
1972 return NULL;
1975 if (!getsockaddrarg(s, addro, &addr, &addrlen))
1976 return NULL;
1978 Py_BEGIN_ALLOW_THREADS
1979 internal_select(s, 1);
1980 n = sendto(s->sock_fd, buf, len, flags, addr, addrlen);
1981 Py_END_ALLOW_THREADS
1983 if (n < 0)
1984 return s->errorhandler();
1985 return PyInt_FromLong((long)n);
1988 PyDoc_STRVAR(sendto_doc,
1989 "sendto(data[, flags], address) -> count\n\
1991 Like send(data, flags) but allows specifying the destination address.\n\
1992 For IP sockets, the address is a pair (hostaddr, port).");
1995 /* s.shutdown(how) method */
1997 static PyObject *
1998 sock_shutdown(PySocketSockObject *s, PyObject *arg)
2000 int how;
2001 int res;
2003 how = PyInt_AsLong(arg);
2004 if (how == -1 && PyErr_Occurred())
2005 return NULL;
2006 Py_BEGIN_ALLOW_THREADS
2007 res = shutdown(s->sock_fd, how);
2008 Py_END_ALLOW_THREADS
2009 if (res < 0)
2010 return s->errorhandler();
2011 Py_INCREF(Py_None);
2012 return Py_None;
2015 PyDoc_STRVAR(shutdown_doc,
2016 "shutdown(flag)\n\
2018 Shut down the reading side of the socket (flag == 0), the writing side\n\
2019 of the socket (flag == 1), or both ends (flag == 2).");
2022 /* List of methods for socket objects */
2024 static PyMethodDef sock_methods[] = {
2025 {"accept", (PyCFunction)sock_accept, METH_NOARGS,
2026 accept_doc},
2027 {"bind", (PyCFunction)sock_bind, METH_O,
2028 bind_doc},
2029 {"close", (PyCFunction)sock_close, METH_NOARGS,
2030 close_doc},
2031 {"connect", (PyCFunction)sock_connect, METH_O,
2032 connect_doc},
2033 {"connect_ex", (PyCFunction)sock_connect_ex, METH_O,
2034 connect_ex_doc},
2035 #ifndef NO_DUP
2036 {"dup", (PyCFunction)sock_dup, METH_NOARGS,
2037 dup_doc},
2038 #endif
2039 {"fileno", (PyCFunction)sock_fileno, METH_NOARGS,
2040 fileno_doc},
2041 #ifdef HAVE_GETPEERNAME
2042 {"getpeername", (PyCFunction)sock_getpeername,
2043 METH_NOARGS, getpeername_doc},
2044 #endif
2045 {"getsockname", (PyCFunction)sock_getsockname,
2046 METH_NOARGS, getsockname_doc},
2047 {"getsockopt", (PyCFunction)sock_getsockopt, METH_VARARGS,
2048 getsockopt_doc},
2049 {"listen", (PyCFunction)sock_listen, METH_O,
2050 listen_doc},
2051 #ifndef NO_DUP
2052 {"makefile", (PyCFunction)sock_makefile, METH_VARARGS,
2053 makefile_doc},
2054 #endif
2055 {"recv", (PyCFunction)sock_recv, METH_VARARGS,
2056 recv_doc},
2057 {"recvfrom", (PyCFunction)sock_recvfrom, METH_VARARGS,
2058 recvfrom_doc},
2059 {"send", (PyCFunction)sock_send, METH_VARARGS,
2060 send_doc},
2061 {"sendall", (PyCFunction)sock_sendall, METH_VARARGS,
2062 sendall_doc},
2063 {"sendto", (PyCFunction)sock_sendto, METH_VARARGS,
2064 sendto_doc},
2065 {"setblocking", (PyCFunction)sock_setblocking, METH_O,
2066 setblocking_doc},
2067 {"settimeout", (PyCFunction)sock_settimeout, METH_O,
2068 settimeout_doc},
2069 {"gettimeout", (PyCFunction)sock_gettimeout, METH_NOARGS,
2070 gettimeout_doc},
2071 {"setsockopt", (PyCFunction)sock_setsockopt, METH_VARARGS,
2072 setsockopt_doc},
2073 {"shutdown", (PyCFunction)sock_shutdown, METH_O,
2074 shutdown_doc},
2075 #ifdef RISCOS
2076 {"sleeptaskw", (PyCFunction)sock_sleeptaskw, METH_O,
2077 sleeptaskw_doc},
2078 #endif
2079 {NULL, NULL} /* sentinel */
2083 /* Deallocate a socket object in response to the last Py_DECREF().
2084 First close the file description. */
2086 static void
2087 sock_dealloc(PySocketSockObject *s)
2089 if (s->sock_fd != -1)
2090 (void) SOCKETCLOSE(s->sock_fd);
2091 s->ob_type->tp_free((PyObject *)s);
2095 static PyObject *
2096 sock_repr(PySocketSockObject *s)
2098 char buf[512];
2099 #if SIZEOF_SOCKET_T > SIZEOF_LONG
2100 if (s->sock_fd > LONG_MAX) {
2101 /* this can occur on Win64, and actually there is a special
2102 ugly printf formatter for decimal pointer length integer
2103 printing, only bother if necessary*/
2104 PyErr_SetString(PyExc_OverflowError,
2105 "no printf formatter to display "
2106 "the socket descriptor in decimal");
2107 return NULL;
2109 #endif
2110 PyOS_snprintf(
2111 buf, sizeof(buf),
2112 "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
2113 (long)s->sock_fd, s->sock_family,
2114 s->sock_type,
2115 s->sock_proto);
2116 return PyString_FromString(buf);
2120 /* Create a new, uninitialized socket object. */
2122 static PyObject *
2123 sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2125 PyObject *new;
2127 new = type->tp_alloc(type, 0);
2128 if (new != NULL) {
2129 ((PySocketSockObject *)new)->sock_fd = -1;
2130 ((PySocketSockObject *)new)->sock_timeout = -1.0;
2131 ((PySocketSockObject *)new)->errorhandler = &set_error;
2133 return new;
2137 /* Initialize a new socket object. */
2139 /*ARGSUSED*/
2140 static int
2141 sock_initobj(PyObject *self, PyObject *args, PyObject *kwds)
2143 PySocketSockObject *s = (PySocketSockObject *)self;
2144 SOCKET_T fd;
2145 int family = AF_INET, type = SOCK_STREAM, proto = 0;
2146 static char *keywords[] = {"family", "type", "proto", 0};
2148 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2149 "|iii:socket", keywords,
2150 &family, &type, &proto))
2151 return -1;
2153 Py_BEGIN_ALLOW_THREADS
2154 fd = socket(family, type, proto);
2155 Py_END_ALLOW_THREADS
2157 #ifdef MS_WINDOWS
2158 if (fd == INVALID_SOCKET)
2159 #else
2160 if (fd < 0)
2161 #endif
2163 set_error();
2164 return -1;
2166 init_sockobject(s, fd, family, type, proto);
2167 /* From now on, ignore SIGPIPE and let the error checking
2168 do the work. */
2169 #ifdef SIGPIPE
2170 (void) signal(SIGPIPE, SIG_IGN);
2171 #endif
2173 return 0;
2178 /* Type object for socket objects. */
2180 static PyTypeObject sock_type = {
2181 PyObject_HEAD_INIT(0) /* Must fill in type value later */
2182 0, /* ob_size */
2183 "_socket.socket", /* tp_name */
2184 sizeof(PySocketSockObject), /* tp_basicsize */
2185 0, /* tp_itemsize */
2186 (destructor)sock_dealloc, /* tp_dealloc */
2187 0, /* tp_print */
2188 0, /* tp_getattr */
2189 0, /* tp_setattr */
2190 0, /* tp_compare */
2191 (reprfunc)sock_repr, /* tp_repr */
2192 0, /* tp_as_number */
2193 0, /* tp_as_sequence */
2194 0, /* tp_as_mapping */
2195 0, /* tp_hash */
2196 0, /* tp_call */
2197 0, /* tp_str */
2198 PyObject_GenericGetAttr, /* tp_getattro */
2199 0, /* tp_setattro */
2200 0, /* tp_as_buffer */
2201 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2202 sock_doc, /* tp_doc */
2203 0, /* tp_traverse */
2204 0, /* tp_clear */
2205 0, /* tp_richcompare */
2206 0, /* tp_weaklistoffset */
2207 0, /* tp_iter */
2208 0, /* tp_iternext */
2209 sock_methods, /* tp_methods */
2210 0, /* tp_members */
2211 0, /* tp_getset */
2212 0, /* tp_base */
2213 0, /* tp_dict */
2214 0, /* tp_descr_get */
2215 0, /* tp_descr_set */
2216 0, /* tp_dictoffset */
2217 sock_initobj, /* tp_init */
2218 PyType_GenericAlloc, /* tp_alloc */
2219 sock_new, /* tp_new */
2220 PyObject_Del, /* tp_free */
2224 /* Python interface to gethostname(). */
2226 /*ARGSUSED*/
2227 static PyObject *
2228 socket_gethostname(PyObject *self, PyObject *args)
2230 char buf[1024];
2231 int res;
2232 if (!PyArg_ParseTuple(args, ":gethostname"))
2233 return NULL;
2234 Py_BEGIN_ALLOW_THREADS
2235 res = gethostname(buf, (int) sizeof buf - 1);
2236 Py_END_ALLOW_THREADS
2237 if (res < 0)
2238 return set_error();
2239 buf[sizeof buf - 1] = '\0';
2240 return PyString_FromString(buf);
2243 PyDoc_STRVAR(gethostname_doc,
2244 "gethostname() -> string\n\
2246 Return the current host name.");
2249 /* Python interface to gethostbyname(name). */
2251 /*ARGSUSED*/
2252 static PyObject *
2253 socket_gethostbyname(PyObject *self, PyObject *args)
2255 char *name;
2256 #ifdef ENABLE_IPV6
2257 struct sockaddr_storage addrbuf;
2258 #else
2259 struct sockaddr_in addrbuf;
2260 #endif
2262 if (!PyArg_ParseTuple(args, "s:gethostbyname", &name))
2263 return NULL;
2264 if (setipaddr(name, (struct sockaddr *)&addrbuf, sizeof(addrbuf), AF_INET) < 0)
2265 return NULL;
2266 return makeipaddr((struct sockaddr *)&addrbuf,
2267 sizeof(struct sockaddr_in));
2270 PyDoc_STRVAR(gethostbyname_doc,
2271 "gethostbyname(host) -> address\n\
2273 Return the IP address (a string of the form '255.255.255.255') for a host.");
2276 /* Convenience function common to gethostbyname_ex and gethostbyaddr */
2278 static PyObject *
2279 gethost_common(struct hostent *h, struct sockaddr *addr, int alen, int af)
2281 char **pch;
2282 PyObject *rtn_tuple = (PyObject *)NULL;
2283 PyObject *name_list = (PyObject *)NULL;
2284 PyObject *addr_list = (PyObject *)NULL;
2285 PyObject *tmp;
2287 if (h == NULL) {
2288 /* Let's get real error message to return */
2289 #ifndef RISCOS
2290 set_herror(h_errno);
2291 #else
2292 PyErr_SetString(socket_error, "host not found");
2293 #endif
2294 return NULL;
2297 if (h->h_addrtype != af) {
2298 #ifdef HAVE_STRERROR
2299 /* Let's get real error message to return */
2300 PyErr_SetString(socket_error,
2301 (char *)strerror(EAFNOSUPPORT));
2302 #else
2303 PyErr_SetString(
2304 socket_error,
2305 "Address family not supported by protocol family");
2306 #endif
2307 return NULL;
2310 switch (af) {
2312 case AF_INET:
2313 if (alen < sizeof(struct sockaddr_in))
2314 return NULL;
2315 break;
2317 #ifdef ENABLE_IPV6
2318 case AF_INET6:
2319 if (alen < sizeof(struct sockaddr_in6))
2320 return NULL;
2321 break;
2322 #endif
2326 if ((name_list = PyList_New(0)) == NULL)
2327 goto err;
2329 if ((addr_list = PyList_New(0)) == NULL)
2330 goto err;
2332 for (pch = h->h_aliases; *pch != NULL; pch++) {
2333 int status;
2334 tmp = PyString_FromString(*pch);
2335 if (tmp == NULL)
2336 goto err;
2338 status = PyList_Append(name_list, tmp);
2339 Py_DECREF(tmp);
2341 if (status)
2342 goto err;
2345 for (pch = h->h_addr_list; *pch != NULL; pch++) {
2346 int status;
2348 switch (af) {
2350 case AF_INET:
2352 struct sockaddr_in sin;
2353 memset(&sin, 0, sizeof(sin));
2354 sin.sin_family = af;
2355 #ifdef HAVE_SOCKADDR_SA_LEN
2356 sin.sin_len = sizeof(sin);
2357 #endif
2358 memcpy(&sin.sin_addr, *pch, sizeof(sin.sin_addr));
2359 tmp = makeipaddr((struct sockaddr *)&sin, sizeof(sin));
2361 if (pch == h->h_addr_list && alen >= sizeof(sin))
2362 memcpy((char *) addr, &sin, sizeof(sin));
2363 break;
2366 #ifdef ENABLE_IPV6
2367 case AF_INET6:
2369 struct sockaddr_in6 sin6;
2370 memset(&sin6, 0, sizeof(sin6));
2371 sin6.sin6_family = af;
2372 #ifdef HAVE_SOCKADDR_SA_LEN
2373 sin6.sin6_len = sizeof(sin6);
2374 #endif
2375 memcpy(&sin6.sin6_addr, *pch, sizeof(sin6.sin6_addr));
2376 tmp = makeipaddr((struct sockaddr *)&sin6,
2377 sizeof(sin6));
2379 if (pch == h->h_addr_list && alen >= sizeof(sin6))
2380 memcpy((char *) addr, &sin6, sizeof(sin6));
2381 break;
2383 #endif
2385 default: /* can't happen */
2386 PyErr_SetString(socket_error,
2387 "unsupported address family");
2388 return NULL;
2391 if (tmp == NULL)
2392 goto err;
2394 status = PyList_Append(addr_list, tmp);
2395 Py_DECREF(tmp);
2397 if (status)
2398 goto err;
2401 rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list);
2403 err:
2404 Py_XDECREF(name_list);
2405 Py_XDECREF(addr_list);
2406 return rtn_tuple;
2410 /* Python interface to gethostbyname_ex(name). */
2412 /*ARGSUSED*/
2413 static PyObject *
2414 socket_gethostbyname_ex(PyObject *self, PyObject *args)
2416 char *name;
2417 struct hostent *h;
2418 #ifdef ENABLE_IPV6
2419 struct sockaddr_storage addr;
2420 #else
2421 struct sockaddr_in addr;
2422 #endif
2423 struct sockaddr *sa;
2424 PyObject *ret;
2425 #ifdef HAVE_GETHOSTBYNAME_R
2426 struct hostent hp_allocated;
2427 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
2428 struct hostent_data data;
2429 #else
2430 char buf[16384];
2431 int buf_len = (sizeof buf) - 1;
2432 int errnop;
2433 #endif
2434 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2435 int result;
2436 #endif
2437 #endif /* HAVE_GETHOSTBYNAME_R */
2439 if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name))
2440 return NULL;
2441 if (setipaddr(name, (struct sockaddr *)&addr, sizeof(addr), AF_INET) < 0)
2442 return NULL;
2443 Py_BEGIN_ALLOW_THREADS
2444 #ifdef HAVE_GETHOSTBYNAME_R
2445 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2446 result = gethostbyname_r(name, &hp_allocated, buf, buf_len,
2447 &h, &errnop);
2448 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
2449 h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
2450 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
2451 memset((void *) &data, '\0', sizeof(data));
2452 result = gethostbyname_r(name, &hp_allocated, &data);
2453 h = (result != 0) ? NULL : &hp_allocated;
2454 #endif
2455 #else /* not HAVE_GETHOSTBYNAME_R */
2456 #ifdef USE_GETHOSTBYNAME_LOCK
2457 PyThread_acquire_lock(netdb_lock, 1);
2458 #endif
2459 h = gethostbyname(name);
2460 #endif /* HAVE_GETHOSTBYNAME_R */
2461 Py_END_ALLOW_THREADS
2462 /* Some C libraries would require addr.__ss_family instead of
2463 addr.ss_family.
2464 Therefore, we cast the sockaddr_storage into sockaddr to
2465 access sa_family. */
2466 sa = (struct sockaddr*)&addr;
2467 ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr),
2468 sa->sa_family);
2469 #ifdef USE_GETHOSTBYNAME_LOCK
2470 PyThread_release_lock(netdb_lock);
2471 #endif
2472 return ret;
2475 PyDoc_STRVAR(ghbn_ex_doc,
2476 "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
2478 Return the true host name, a list of aliases, and a list of IP addresses,\n\
2479 for a host. The host argument is a string giving a host name or IP number.");
2482 /* Python interface to gethostbyaddr(IP). */
2484 /*ARGSUSED*/
2485 static PyObject *
2486 socket_gethostbyaddr(PyObject *self, PyObject *args)
2488 #ifdef ENABLE_IPV6
2489 struct sockaddr_storage addr;
2490 #else
2491 struct sockaddr_in addr;
2492 #endif
2493 struct sockaddr *sa = (struct sockaddr *)&addr;
2494 char *ip_num;
2495 struct hostent *h;
2496 PyObject *ret;
2497 #ifdef HAVE_GETHOSTBYNAME_R
2498 struct hostent hp_allocated;
2499 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
2500 struct hostent_data data;
2501 #else
2502 char buf[16384];
2503 int buf_len = (sizeof buf) - 1;
2504 int errnop;
2505 #endif
2506 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2507 int result;
2508 #endif
2509 #endif /* HAVE_GETHOSTBYNAME_R */
2510 char *ap;
2511 int al;
2512 int af;
2514 if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num))
2515 return NULL;
2516 af = AF_UNSPEC;
2517 if (setipaddr(ip_num, sa, sizeof(addr), af) < 0)
2518 return NULL;
2519 af = sa->sa_family;
2520 ap = NULL;
2521 al = 0;
2522 switch (af) {
2523 case AF_INET:
2524 ap = (char *)&((struct sockaddr_in *)sa)->sin_addr;
2525 al = sizeof(((struct sockaddr_in *)sa)->sin_addr);
2526 break;
2527 #ifdef ENABLE_IPV6
2528 case AF_INET6:
2529 ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr;
2530 al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr);
2531 break;
2532 #endif
2533 default:
2534 PyErr_SetString(socket_error, "unsupported address family");
2535 return NULL;
2537 Py_BEGIN_ALLOW_THREADS
2538 #ifdef HAVE_GETHOSTBYNAME_R
2539 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2540 result = gethostbyaddr_r(ap, al, af,
2541 &hp_allocated, buf, buf_len,
2542 &h, &errnop);
2543 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
2544 h = gethostbyaddr_r(ap, al, af,
2545 &hp_allocated, buf, buf_len, &errnop);
2546 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
2547 memset((void *) &data, '\0', sizeof(data));
2548 result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data);
2549 h = (result != 0) ? NULL : &hp_allocated;
2550 #endif
2551 #else /* not HAVE_GETHOSTBYNAME_R */
2552 #ifdef USE_GETHOSTBYNAME_LOCK
2553 PyThread_acquire_lock(netdb_lock, 1);
2554 #endif
2555 h = gethostbyaddr(ap, al, af);
2556 #endif /* HAVE_GETHOSTBYNAME_R */
2557 Py_END_ALLOW_THREADS
2558 ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), af);
2559 #ifdef USE_GETHOSTBYNAME_LOCK
2560 PyThread_release_lock(netdb_lock);
2561 #endif
2562 return ret;
2565 PyDoc_STRVAR(gethostbyaddr_doc,
2566 "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
2568 Return the true host name, a list of aliases, and a list of IP addresses,\n\
2569 for a host. The host argument is a string giving a host name or IP number.");
2572 /* Python interface to getservbyname(name).
2573 This only returns the port number, since the other info is already
2574 known or not useful (like the list of aliases). */
2576 /*ARGSUSED*/
2577 static PyObject *
2578 socket_getservbyname(PyObject *self, PyObject *args)
2580 char *name, *proto;
2581 struct servent *sp;
2582 if (!PyArg_ParseTuple(args, "ss:getservbyname", &name, &proto))
2583 return NULL;
2584 Py_BEGIN_ALLOW_THREADS
2585 sp = getservbyname(name, proto);
2586 Py_END_ALLOW_THREADS
2587 if (sp == NULL) {
2588 PyErr_SetString(socket_error, "service/proto not found");
2589 return NULL;
2591 return PyInt_FromLong((long) ntohs(sp->s_port));
2594 PyDoc_STRVAR(getservbyname_doc,
2595 "getservbyname(servicename, protocolname) -> integer\n\
2597 Return a port number from a service name and protocol name.\n\
2598 The protocol name should be 'tcp' or 'udp'.");
2601 /* Python interface to getprotobyname(name).
2602 This only returns the protocol number, since the other info is
2603 already known or not useful (like the list of aliases). */
2605 /*ARGSUSED*/
2606 static PyObject *
2607 socket_getprotobyname(PyObject *self, PyObject *args)
2609 char *name;
2610 struct protoent *sp;
2611 #ifdef __BEOS__
2612 /* Not available in BeOS yet. - [cjh] */
2613 PyErr_SetString(socket_error, "getprotobyname not supported");
2614 return NULL;
2615 #else
2616 if (!PyArg_ParseTuple(args, "s:getprotobyname", &name))
2617 return NULL;
2618 Py_BEGIN_ALLOW_THREADS
2619 sp = getprotobyname(name);
2620 Py_END_ALLOW_THREADS
2621 if (sp == NULL) {
2622 PyErr_SetString(socket_error, "protocol not found");
2623 return NULL;
2625 return PyInt_FromLong((long) sp->p_proto);
2626 #endif
2629 PyDoc_STRVAR(getprotobyname_doc,
2630 "getprotobyname(name) -> integer\n\
2632 Return the protocol number for the named protocol. (Rarely used.)");
2635 #ifndef NO_DUP
2636 /* Create a socket object from a numeric file description.
2637 Useful e.g. if stdin is a socket.
2638 Additional arguments as for socket(). */
2640 /*ARGSUSED*/
2641 static PyObject *
2642 socket_fromfd(PyObject *self, PyObject *args)
2644 PySocketSockObject *s;
2645 SOCKET_T fd;
2646 int family, type, proto = 0;
2647 if (!PyArg_ParseTuple(args, "iii|i:fromfd",
2648 &fd, &family, &type, &proto))
2649 return NULL;
2650 /* Dup the fd so it and the socket can be closed independently */
2651 fd = dup(fd);
2652 if (fd < 0)
2653 return set_error();
2654 s = new_sockobject(fd, family, type, proto);
2655 /* From now on, ignore SIGPIPE and let the error checking
2656 do the work. */
2657 #ifdef SIGPIPE
2658 (void) signal(SIGPIPE, SIG_IGN);
2659 #endif
2660 return (PyObject *) s;
2663 PyDoc_STRVAR(fromfd_doc,
2664 "fromfd(fd, family, type[, proto]) -> socket object\n\
2666 Create a socket object from the given file descriptor.\n\
2667 The remaining arguments are the same as for socket().");
2669 #endif /* NO_DUP */
2672 static PyObject *
2673 socket_ntohs(PyObject *self, PyObject *args)
2675 int x1, x2;
2677 if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) {
2678 return NULL;
2680 x2 = (int)ntohs((short)x1);
2681 return PyInt_FromLong(x2);
2684 PyDoc_STRVAR(ntohs_doc,
2685 "ntohs(integer) -> integer\n\
2687 Convert a 16-bit integer from network to host byte order.");
2690 static PyObject *
2691 socket_ntohl(PyObject *self, PyObject *arg)
2693 unsigned long x;
2695 if (PyInt_Check(arg)) {
2696 x = PyInt_AS_LONG(arg);
2697 if (x == (unsigned long) -1 && PyErr_Occurred())
2698 return NULL;
2700 else if (PyLong_Check(arg)) {
2701 x = PyLong_AsUnsignedLong(arg);
2702 if (x == (unsigned long) -1 && PyErr_Occurred())
2703 return NULL;
2704 #if SIZEOF_LONG > 4
2706 unsigned long y;
2707 /* only want the trailing 32 bits */
2708 y = x & 0xFFFFFFFFUL;
2709 if (y ^ x)
2710 return PyErr_Format(PyExc_OverflowError,
2711 "long int larger than 32 bits");
2712 x = y;
2714 #endif
2716 else
2717 return PyErr_Format(PyExc_TypeError,
2718 "expected int/long, %s found",
2719 arg->ob_type->tp_name);
2720 if (x == (unsigned long) -1 && PyErr_Occurred())
2721 return NULL;
2722 return PyInt_FromLong(ntohl(x));
2725 PyDoc_STRVAR(ntohl_doc,
2726 "ntohl(integer) -> integer\n\
2728 Convert a 32-bit integer from network to host byte order.");
2731 static PyObject *
2732 socket_htons(PyObject *self, PyObject *args)
2734 unsigned long x1, x2;
2736 if (!PyArg_ParseTuple(args, "i:htons", &x1)) {
2737 return NULL;
2739 x2 = (int)htons((short)x1);
2740 return PyInt_FromLong(x2);
2743 PyDoc_STRVAR(htons_doc,
2744 "htons(integer) -> integer\n\
2746 Convert a 16-bit integer from host to network byte order.");
2749 static PyObject *
2750 socket_htonl(PyObject *self, PyObject *arg)
2752 unsigned long x;
2754 if (PyInt_Check(arg)) {
2755 x = PyInt_AS_LONG(arg);
2756 if (x == (unsigned long) -1 && PyErr_Occurred())
2757 return NULL;
2759 else if (PyLong_Check(arg)) {
2760 x = PyLong_AsUnsignedLong(arg);
2761 if (x == (unsigned long) -1 && PyErr_Occurred())
2762 return NULL;
2763 #if SIZEOF_LONG > 4
2765 unsigned long y;
2766 /* only want the trailing 32 bits */
2767 y = x & 0xFFFFFFFFUL;
2768 if (y ^ x)
2769 return PyErr_Format(PyExc_OverflowError,
2770 "long int larger than 32 bits");
2771 x = y;
2773 #endif
2775 else
2776 return PyErr_Format(PyExc_TypeError,
2777 "expected int/long, %s found",
2778 arg->ob_type->tp_name);
2779 return PyInt_FromLong(htonl(x));
2782 PyDoc_STRVAR(htonl_doc,
2783 "htonl(integer) -> integer\n\
2785 Convert a 32-bit integer from host to network byte order.");
2787 /* socket.inet_aton() and socket.inet_ntoa() functions. */
2789 PyDoc_STRVAR(inet_aton_doc,
2790 "inet_aton(string) -> packed 32-bit IP representation\n\
2792 Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
2793 binary format used in low-level network functions.");
2795 static PyObject*
2796 socket_inet_aton(PyObject *self, PyObject *args)
2798 #ifndef INADDR_NONE
2799 #define INADDR_NONE (-1)
2800 #endif
2801 #ifdef HAVE_INET_ATON
2802 struct in_addr buf;
2803 #else
2804 /* Have to use inet_addr() instead */
2805 unsigned long packed_addr;
2806 #endif
2807 char *ip_addr;
2809 if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr))
2810 return NULL;
2813 #ifdef HAVE_INET_ATON
2814 if (inet_aton(ip_addr, &buf))
2815 return PyString_FromStringAndSize((char *)(&buf),
2816 sizeof(buf));
2818 PyErr_SetString(socket_error,
2819 "illegal IP address string passed to inet_aton");
2820 return NULL;
2822 #else /* ! HAVE_INET_ATON */
2823 /* XXX Problem here: inet_aton('255.255.255.255') raises
2824 an exception while it should be a valid address. */
2825 packed_addr = inet_addr(ip_addr);
2827 if (packed_addr == INADDR_NONE) { /* invalid address */
2828 PyErr_SetString(socket_error,
2829 "illegal IP address string passed to inet_aton");
2830 return NULL;
2832 return PyString_FromStringAndSize((char *) &packed_addr,
2833 sizeof(packed_addr));
2834 #endif
2837 PyDoc_STRVAR(inet_ntoa_doc,
2838 "inet_ntoa(packed_ip) -> ip_address_string\n\
2840 Convert an IP address from 32-bit packed binary format to string format");
2842 static PyObject*
2843 socket_inet_ntoa(PyObject *self, PyObject *args)
2845 char *packed_str;
2846 int addr_len;
2847 struct in_addr packed_addr;
2849 if (!PyArg_ParseTuple(args, "s#:inet_ntoa", &packed_str, &addr_len)) {
2850 return NULL;
2853 if (addr_len != sizeof(packed_addr)) {
2854 PyErr_SetString(socket_error,
2855 "packed IP wrong length for inet_ntoa");
2856 return NULL;
2859 memcpy(&packed_addr, packed_str, addr_len);
2861 return PyString_FromString(inet_ntoa(packed_addr));
2864 #ifdef HAVE_INET_PTON
2866 PyDoc_STRVAR(inet_pton_doc,
2867 "inet_pton(af, ip) -> packed IP address string\n\
2869 Convert an IP address from string format to a packed string suitable\n\
2870 for use with low-level network functions.");
2872 static PyObject *
2873 socket_inet_pton(PyObject *self, PyObject *args)
2875 int af;
2876 char* ip;
2877 int retval;
2878 #ifdef ENABLE_IPV6
2879 char packed[MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
2880 #else
2881 char packed[sizeof(struct in_addr)];
2882 #endif
2883 if (!PyArg_ParseTuple(args, "is:inet_pton", &af, &ip)) {
2884 return NULL;
2887 retval = inet_pton(af, ip, packed);
2888 if (retval < 0) {
2889 PyErr_SetFromErrno(socket_error);
2890 return NULL;
2891 } else if (retval == 0) {
2892 PyErr_SetString(socket_error,
2893 "illegal IP address string passed to inet_pton");
2894 return NULL;
2895 } else if (af == AF_INET) {
2896 return PyString_FromStringAndSize(packed,
2897 sizeof(struct in_addr));
2898 #ifdef ENABLE_IPV6
2899 } else if (af == AF_INET6) {
2900 return PyString_FromStringAndSize(packed,
2901 sizeof(struct in6_addr));
2902 #endif
2903 } else {
2904 PyErr_SetString(socket_error, "unknown address family");
2905 return NULL;
2909 PyDoc_STRVAR(inet_ntop_doc,
2910 "inet_ntop(af, packed_ip) -> string formatted IP address\n\
2912 Convert a packed IP address of the given family to string format.");
2914 static PyObject *
2915 socket_inet_ntop(PyObject *self, PyObject *args)
2917 int af;
2918 char* packed;
2919 int len;
2920 const char* retval;
2921 #ifdef ENABLE_IPV6
2922 char ip[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) + 1];
2923 #else
2924 char ip[INET_ADDRSTRLEN + 1];
2925 #endif
2927 /* Guarantee NUL-termination for PyString_FromString() below */
2928 memset((void *) &ip[0], '\0', sizeof(ip) + 1);
2930 if (!PyArg_ParseTuple(args, "is#:inet_ntop", &af, &packed, &len)) {
2931 return NULL;
2934 if (af == AF_INET) {
2935 if (len != sizeof(struct in_addr)) {
2936 PyErr_SetString(PyExc_ValueError,
2937 "invalid length of packed IP address string");
2938 return NULL;
2940 #ifdef ENABLE_IPV6
2941 } else if (af == AF_INET6) {
2942 if (len != sizeof(struct in6_addr)) {
2943 PyErr_SetString(PyExc_ValueError,
2944 "invalid length of packed IP address string");
2945 return NULL;
2947 #endif
2948 } else {
2949 PyErr_Format(PyExc_ValueError,
2950 "unknown address family %d", af);
2951 return NULL;
2954 retval = inet_ntop(af, packed, ip, sizeof(ip));
2955 if (!retval) {
2956 PyErr_SetFromErrno(socket_error);
2957 return NULL;
2958 } else {
2959 return PyString_FromString(retval);
2962 /* NOTREACHED */
2963 PyErr_SetString(PyExc_RuntimeError, "invalid handling of inet_ntop");
2964 return NULL;
2967 #endif /* HAVE_INET_PTON */
2969 /* Python interface to getaddrinfo(host, port). */
2971 /*ARGSUSED*/
2972 static PyObject *
2973 socket_getaddrinfo(PyObject *self, PyObject *args)
2975 struct addrinfo hints, *res;
2976 struct addrinfo *res0 = NULL;
2977 PyObject *hobj = NULL;
2978 PyObject *pobj = (PyObject *)NULL;
2979 char pbuf[30];
2980 char *hptr, *pptr;
2981 int family, socktype, protocol, flags;
2982 int error;
2983 PyObject *all = (PyObject *)NULL;
2984 PyObject *single = (PyObject *)NULL;
2985 PyObject *idna = NULL;
2987 family = socktype = protocol = flags = 0;
2988 family = AF_UNSPEC;
2989 if (!PyArg_ParseTuple(args, "OO|iiii:getaddrinfo",
2990 &hobj, &pobj, &family, &socktype,
2991 &protocol, &flags)) {
2992 return NULL;
2994 if (hobj == Py_None) {
2995 hptr = NULL;
2996 } else if (PyUnicode_Check(hobj)) {
2997 idna = PyObject_CallMethod(hobj, "encode", "s", "idna");
2998 if (!idna)
2999 return NULL;
3000 hptr = PyString_AsString(idna);
3001 } else if (PyString_Check(hobj)) {
3002 hptr = PyString_AsString(hobj);
3003 } else {
3004 PyErr_SetString(PyExc_TypeError,
3005 "getaddrinfo() argument 1 must be string or None");
3006 return NULL;
3008 if (PyInt_Check(pobj)) {
3009 PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", PyInt_AsLong(pobj));
3010 pptr = pbuf;
3011 } else if (PyString_Check(pobj)) {
3012 pptr = PyString_AsString(pobj);
3013 } else if (pobj == Py_None) {
3014 pptr = (char *)NULL;
3015 } else {
3016 PyErr_SetString(socket_error, "Int or String expected");
3017 return NULL;
3019 memset(&hints, 0, sizeof(hints));
3020 hints.ai_family = family;
3021 hints.ai_socktype = socktype;
3022 hints.ai_protocol = protocol;
3023 hints.ai_flags = flags;
3024 Py_BEGIN_ALLOW_THREADS
3025 ACQUIRE_GETADDRINFO_LOCK
3026 error = getaddrinfo(hptr, pptr, &hints, &res0);
3027 Py_END_ALLOW_THREADS
3028 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
3029 if (error) {
3030 set_gaierror(error);
3031 return NULL;
3034 if ((all = PyList_New(0)) == NULL)
3035 goto err;
3036 for (res = res0; res; res = res->ai_next) {
3037 PyObject *addr =
3038 makesockaddr(-1, res->ai_addr, res->ai_addrlen);
3039 if (addr == NULL)
3040 goto err;
3041 single = Py_BuildValue("iiisO", res->ai_family,
3042 res->ai_socktype, res->ai_protocol,
3043 res->ai_canonname ? res->ai_canonname : "",
3044 addr);
3045 Py_DECREF(addr);
3046 if (single == NULL)
3047 goto err;
3049 if (PyList_Append(all, single))
3050 goto err;
3051 Py_XDECREF(single);
3053 Py_XDECREF(idna);
3054 if (res0)
3055 freeaddrinfo(res0);
3056 return all;
3057 err:
3058 Py_XDECREF(single);
3059 Py_XDECREF(all);
3060 Py_XDECREF(idna);
3061 if (res0)
3062 freeaddrinfo(res0);
3063 return (PyObject *)NULL;
3066 PyDoc_STRVAR(getaddrinfo_doc,
3067 "getaddrinfo(host, port [, family, socktype, proto, flags])\n\
3068 -> list of (family, socktype, proto, canonname, sockaddr)\n\
3070 Resolve host and port into addrinfo struct.");
3072 /* Python interface to getnameinfo(sa, flags). */
3074 /*ARGSUSED*/
3075 static PyObject *
3076 socket_getnameinfo(PyObject *self, PyObject *args)
3078 PyObject *sa = (PyObject *)NULL;
3079 int flags;
3080 char *hostp;
3081 int port, flowinfo, scope_id;
3082 char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
3083 struct addrinfo hints, *res = NULL;
3084 int error;
3085 PyObject *ret = (PyObject *)NULL;
3087 flags = flowinfo = scope_id = 0;
3088 if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags))
3089 return NULL;
3090 if (!PyArg_ParseTuple(sa, "si|ii",
3091 &hostp, &port, &flowinfo, &scope_id))
3092 return NULL;
3093 PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port);
3094 memset(&hints, 0, sizeof(hints));
3095 hints.ai_family = AF_UNSPEC;
3096 hints.ai_socktype = SOCK_DGRAM; /* make numeric port happy */
3097 Py_BEGIN_ALLOW_THREADS
3098 ACQUIRE_GETADDRINFO_LOCK
3099 error = getaddrinfo(hostp, pbuf, &hints, &res);
3100 Py_END_ALLOW_THREADS
3101 RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
3102 if (error) {
3103 set_gaierror(error);
3104 goto fail;
3106 if (res->ai_next) {
3107 PyErr_SetString(socket_error,
3108 "sockaddr resolved to multiple addresses");
3109 goto fail;
3111 switch (res->ai_family) {
3112 case AF_INET:
3114 char *t1;
3115 int t2;
3116 if (PyArg_ParseTuple(sa, "si", &t1, &t2) == 0) {
3117 PyErr_SetString(socket_error,
3118 "IPv4 sockaddr must be 2 tuple");
3119 goto fail;
3121 break;
3123 #ifdef ENABLE_IPV6
3124 case AF_INET6:
3126 struct sockaddr_in6 *sin6;
3127 sin6 = (struct sockaddr_in6 *)res->ai_addr;
3128 sin6->sin6_flowinfo = flowinfo;
3129 sin6->sin6_scope_id = scope_id;
3130 break;
3132 #endif
3134 error = getnameinfo(res->ai_addr, res->ai_addrlen,
3135 hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags);
3136 if (error) {
3137 set_gaierror(error);
3138 goto fail;
3140 ret = Py_BuildValue("ss", hbuf, pbuf);
3142 fail:
3143 if (res)
3144 freeaddrinfo(res);
3145 return ret;
3148 PyDoc_STRVAR(getnameinfo_doc,
3149 "getnameinfo(sockaddr, flags) --> (host, port)\n\
3151 Get host and port for a sockaddr.");
3154 /* Python API to getting and setting the default timeout value. */
3156 static PyObject *
3157 socket_getdefaulttimeout(PyObject *self)
3159 if (defaulttimeout < 0.0) {
3160 Py_INCREF(Py_None);
3161 return Py_None;
3163 else
3164 return PyFloat_FromDouble(defaulttimeout);
3167 PyDoc_STRVAR(getdefaulttimeout_doc,
3168 "getdefaulttimeout() -> timeout\n\
3170 Returns the default timeout in floating seconds for new socket objects.\n\
3171 A value of None indicates that new socket objects have no timeout.\n\
3172 When the socket module is first imported, the default is None.");
3174 static PyObject *
3175 socket_setdefaulttimeout(PyObject *self, PyObject *arg)
3177 double timeout;
3179 if (arg == Py_None)
3180 timeout = -1.0;
3181 else {
3182 timeout = PyFloat_AsDouble(arg);
3183 if (timeout < 0.0) {
3184 if (!PyErr_Occurred())
3185 PyErr_SetString(PyExc_ValueError,
3186 "Timeout value out of range");
3187 return NULL;
3191 defaulttimeout = timeout;
3193 Py_INCREF(Py_None);
3194 return Py_None;
3197 PyDoc_STRVAR(setdefaulttimeout_doc,
3198 "setdefaulttimeout(timeout)\n\
3200 Set the default timeout in floating seconds for new socket objects.\n\
3201 A value of None indicates that new socket objects have no timeout.\n\
3202 When the socket module is first imported, the default is None.");
3205 /* List of functions exported by this module. */
3207 static PyMethodDef socket_methods[] = {
3208 {"gethostbyname", socket_gethostbyname,
3209 METH_VARARGS, gethostbyname_doc},
3210 {"gethostbyname_ex", socket_gethostbyname_ex,
3211 METH_VARARGS, ghbn_ex_doc},
3212 {"gethostbyaddr", socket_gethostbyaddr,
3213 METH_VARARGS, gethostbyaddr_doc},
3214 {"gethostname", socket_gethostname,
3215 METH_VARARGS, gethostname_doc},
3216 {"getservbyname", socket_getservbyname,
3217 METH_VARARGS, getservbyname_doc},
3218 {"getprotobyname", socket_getprotobyname,
3219 METH_VARARGS,getprotobyname_doc},
3220 #ifndef NO_DUP
3221 {"fromfd", socket_fromfd,
3222 METH_VARARGS, fromfd_doc},
3223 #endif
3224 {"ntohs", socket_ntohs,
3225 METH_VARARGS, ntohs_doc},
3226 {"ntohl", socket_ntohl,
3227 METH_O, ntohl_doc},
3228 {"htons", socket_htons,
3229 METH_VARARGS, htons_doc},
3230 {"htonl", socket_htonl,
3231 METH_O, htonl_doc},
3232 {"inet_aton", socket_inet_aton,
3233 METH_VARARGS, inet_aton_doc},
3234 {"inet_ntoa", socket_inet_ntoa,
3235 METH_VARARGS, inet_ntoa_doc},
3236 #ifdef HAVE_INET_PTON
3237 {"inet_pton", socket_inet_pton,
3238 METH_VARARGS, inet_pton_doc},
3239 {"inet_ntop", socket_inet_ntop,
3240 METH_VARARGS, inet_ntop_doc},
3241 #endif
3242 {"getaddrinfo", socket_getaddrinfo,
3243 METH_VARARGS, getaddrinfo_doc},
3244 {"getnameinfo", socket_getnameinfo,
3245 METH_VARARGS, getnameinfo_doc},
3246 {"getdefaulttimeout", (PyCFunction)socket_getdefaulttimeout,
3247 METH_NOARGS, getdefaulttimeout_doc},
3248 {"setdefaulttimeout", socket_setdefaulttimeout,
3249 METH_O, setdefaulttimeout_doc},
3250 {NULL, NULL} /* Sentinel */
3254 #ifdef RISCOS
3255 #define OS_INIT_DEFINED
3257 static int
3258 os_init(void)
3260 _kernel_swi_regs r;
3262 r.r[0] = 0;
3263 _kernel_swi(0x43380, &r, &r);
3264 taskwindow = r.r[0];
3266 return 1;
3269 #endif /* RISCOS */
3272 #ifdef MS_WINDOWS
3273 #define OS_INIT_DEFINED
3275 /* Additional initialization and cleanup for Windows */
3277 static void
3278 os_cleanup(void)
3280 WSACleanup();
3283 static int
3284 os_init(void)
3286 WSADATA WSAData;
3287 int ret;
3288 char buf[100];
3289 ret = WSAStartup(0x0101, &WSAData);
3290 switch (ret) {
3291 case 0: /* No error */
3292 atexit(os_cleanup);
3293 return 1; /* Success */
3294 case WSASYSNOTREADY:
3295 PyErr_SetString(PyExc_ImportError,
3296 "WSAStartup failed: network not ready");
3297 break;
3298 case WSAVERNOTSUPPORTED:
3299 case WSAEINVAL:
3300 PyErr_SetString(
3301 PyExc_ImportError,
3302 "WSAStartup failed: requested version not supported");
3303 break;
3304 default:
3305 PyOS_snprintf(buf, sizeof(buf),
3306 "WSAStartup failed: error code %d", ret);
3307 PyErr_SetString(PyExc_ImportError, buf);
3308 break;
3310 return 0; /* Failure */
3313 #endif /* MS_WINDOWS */
3316 #ifdef PYOS_OS2
3317 #define OS_INIT_DEFINED
3319 /* Additional initialization for OS/2 */
3321 static int
3322 os_init(void)
3324 #ifndef PYCC_GCC
3325 char reason[64];
3326 int rc = sock_init();
3328 if (rc == 0) {
3329 return 1; /* Success */
3332 PyOS_snprintf(reason, sizeof(reason),
3333 "OS/2 TCP/IP Error# %d", sock_errno());
3334 PyErr_SetString(PyExc_ImportError, reason);
3336 return 0; /* Failure */
3337 #else
3338 /* No need to initialise sockets with GCC/EMX */
3339 return 1; /* Success */
3340 #endif
3343 #endif /* PYOS_OS2 */
3346 #ifndef OS_INIT_DEFINED
3347 static int
3348 os_init(void)
3350 return 1; /* Success */
3352 #endif
3355 /* C API table - always add new things to the end for binary
3356 compatibility. */
3357 static
3358 PySocketModule_APIObject PySocketModuleAPI =
3360 &sock_type,
3364 /* Initialize the _socket module.
3366 This module is actually called "_socket", and there's a wrapper
3367 "socket.py" which implements some additional functionality. On some
3368 platforms (e.g. Windows and OS/2), socket.py also implements a
3369 wrapper for the socket type that provides missing functionality such
3370 as makefile(), dup() and fromfd(). The import of "_socket" may fail
3371 with an ImportError exception if os-specific initialization fails.
3372 On Windows, this does WINSOCK initialization. When WINSOCK is
3373 initialized succesfully, a call to WSACleanup() is scheduled to be
3374 made at exit time.
3377 PyDoc_STRVAR(socket_doc,
3378 "Implementation module for socket operations.\n\
3380 See the socket module for documentation.");
3382 PyMODINIT_FUNC
3383 init_socket(void)
3385 PyObject *m, *has_ipv6;
3387 if (!os_init())
3388 return;
3390 sock_type.ob_type = &PyType_Type;
3391 m = Py_InitModule3(PySocket_MODULE_NAME,
3392 socket_methods,
3393 socket_doc);
3395 socket_error = PyErr_NewException("socket.error", NULL, NULL);
3396 if (socket_error == NULL)
3397 return;
3398 Py_INCREF(socket_error);
3399 PyModule_AddObject(m, "error", socket_error);
3400 socket_herror = PyErr_NewException("socket.herror",
3401 socket_error, NULL);
3402 if (socket_herror == NULL)
3403 return;
3404 Py_INCREF(socket_herror);
3405 PyModule_AddObject(m, "herror", socket_herror);
3406 socket_gaierror = PyErr_NewException("socket.gaierror", socket_error,
3407 NULL);
3408 if (socket_gaierror == NULL)
3409 return;
3410 Py_INCREF(socket_gaierror);
3411 PyModule_AddObject(m, "gaierror", socket_gaierror);
3412 Py_INCREF((PyObject *)&sock_type);
3413 if (PyModule_AddObject(m, "SocketType",
3414 (PyObject *)&sock_type) != 0)
3415 return;
3416 Py_INCREF((PyObject *)&sock_type);
3417 if (PyModule_AddObject(m, "socket",
3418 (PyObject *)&sock_type) != 0)
3419 return;
3421 #ifdef ENABLE_IPV6
3422 has_ipv6 = Py_True;
3423 #else
3424 has_ipv6 = Py_False;
3425 #endif
3426 Py_INCREF(has_ipv6);
3427 PyModule_AddObject(m, "has_ipv6", has_ipv6);
3429 /* Export C API */
3430 if (PyModule_AddObject(m, PySocket_CAPI_NAME,
3431 PyCObject_FromVoidPtr((void *)&PySocketModuleAPI, NULL)
3432 ) != 0)
3433 return;
3435 /* Address families (we only support AF_INET and AF_UNIX) */
3436 #ifdef AF_UNSPEC
3437 PyModule_AddIntConstant(m, "AF_UNSPEC", AF_UNSPEC);
3438 #endif
3439 PyModule_AddIntConstant(m, "AF_INET", AF_INET);
3440 #ifdef AF_INET6
3441 PyModule_AddIntConstant(m, "AF_INET6", AF_INET6);
3442 #endif /* AF_INET6 */
3443 #if defined(AF_UNIX) && !defined(PYOS_OS2)
3444 PyModule_AddIntConstant(m, "AF_UNIX", AF_UNIX);
3445 #endif /* AF_UNIX */
3446 #ifdef AF_AX25
3447 /* Amateur Radio AX.25 */
3448 PyModule_AddIntConstant(m, "AF_AX25", AF_AX25);
3449 #endif
3450 #ifdef AF_IPX
3451 PyModule_AddIntConstant(m, "AF_IPX", AF_IPX); /* Novell IPX */
3452 #endif
3453 #ifdef AF_APPLETALK
3454 /* Appletalk DDP */
3455 PyModule_AddIntConstant(m, "AF_APPLETALK", AF_APPLETALK);
3456 #endif
3457 #ifdef AF_NETROM
3458 /* Amateur radio NetROM */
3459 PyModule_AddIntConstant(m, "AF_NETROM", AF_NETROM);
3460 #endif
3461 #ifdef AF_BRIDGE
3462 /* Multiprotocol bridge */
3463 PyModule_AddIntConstant(m, "AF_BRIDGE", AF_BRIDGE);
3464 #endif
3465 #ifdef AF_AAL5
3466 /* Reserved for Werner's ATM */
3467 PyModule_AddIntConstant(m, "AF_AAL5", AF_AAL5);
3468 #endif
3469 #ifdef AF_X25
3470 /* Reserved for X.25 project */
3471 PyModule_AddIntConstant(m, "AF_X25", AF_X25);
3472 #endif
3473 #ifdef AF_INET6
3474 PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); /* IP version 6 */
3475 #endif
3476 #ifdef AF_ROSE
3477 /* Amateur Radio X.25 PLP */
3478 PyModule_AddIntConstant(m, "AF_ROSE", AF_ROSE);
3479 #endif
3480 #ifdef HAVE_NETPACKET_PACKET_H
3481 PyModule_AddIntConstant(m, "AF_PACKET", AF_PACKET);
3482 PyModule_AddIntConstant(m, "PF_PACKET", PF_PACKET);
3483 PyModule_AddIntConstant(m, "PACKET_HOST", PACKET_HOST);
3484 PyModule_AddIntConstant(m, "PACKET_BROADCAST", PACKET_BROADCAST);
3485 PyModule_AddIntConstant(m, "PACKET_MULTICAST", PACKET_MULTICAST);
3486 PyModule_AddIntConstant(m, "PACKET_OTHERHOST", PACKET_OTHERHOST);
3487 PyModule_AddIntConstant(m, "PACKET_OUTGOING", PACKET_OUTGOING);
3488 PyModule_AddIntConstant(m, "PACKET_LOOPBACK", PACKET_LOOPBACK);
3489 PyModule_AddIntConstant(m, "PACKET_FASTROUTE", PACKET_FASTROUTE);
3490 #endif
3492 /* Socket types */
3493 PyModule_AddIntConstant(m, "SOCK_STREAM", SOCK_STREAM);
3494 PyModule_AddIntConstant(m, "SOCK_DGRAM", SOCK_DGRAM);
3495 #ifndef __BEOS__
3496 /* We have incomplete socket support. */
3497 PyModule_AddIntConstant(m, "SOCK_RAW", SOCK_RAW);
3498 PyModule_AddIntConstant(m, "SOCK_SEQPACKET", SOCK_SEQPACKET);
3499 #if defined(SOCK_RDM)
3500 PyModule_AddIntConstant(m, "SOCK_RDM", SOCK_RDM);
3501 #endif
3502 #endif
3504 #ifdef SO_DEBUG
3505 PyModule_AddIntConstant(m, "SO_DEBUG", SO_DEBUG);
3506 #endif
3507 #ifdef SO_ACCEPTCONN
3508 PyModule_AddIntConstant(m, "SO_ACCEPTCONN", SO_ACCEPTCONN);
3509 #endif
3510 #ifdef SO_REUSEADDR
3511 PyModule_AddIntConstant(m, "SO_REUSEADDR", SO_REUSEADDR);
3512 #endif
3513 #ifdef SO_KEEPALIVE
3514 PyModule_AddIntConstant(m, "SO_KEEPALIVE", SO_KEEPALIVE);
3515 #endif
3516 #ifdef SO_DONTROUTE
3517 PyModule_AddIntConstant(m, "SO_DONTROUTE", SO_DONTROUTE);
3518 #endif
3519 #ifdef SO_BROADCAST
3520 PyModule_AddIntConstant(m, "SO_BROADCAST", SO_BROADCAST);
3521 #endif
3522 #ifdef SO_USELOOPBACK
3523 PyModule_AddIntConstant(m, "SO_USELOOPBACK", SO_USELOOPBACK);
3524 #endif
3525 #ifdef SO_LINGER
3526 PyModule_AddIntConstant(m, "SO_LINGER", SO_LINGER);
3527 #endif
3528 #ifdef SO_OOBINLINE
3529 PyModule_AddIntConstant(m, "SO_OOBINLINE", SO_OOBINLINE);
3530 #endif
3531 #ifdef SO_REUSEPORT
3532 PyModule_AddIntConstant(m, "SO_REUSEPORT", SO_REUSEPORT);
3533 #endif
3534 #ifdef SO_SNDBUF
3535 PyModule_AddIntConstant(m, "SO_SNDBUF", SO_SNDBUF);
3536 #endif
3537 #ifdef SO_RCVBUF
3538 PyModule_AddIntConstant(m, "SO_RCVBUF", SO_RCVBUF);
3539 #endif
3540 #ifdef SO_SNDLOWAT
3541 PyModule_AddIntConstant(m, "SO_SNDLOWAT", SO_SNDLOWAT);
3542 #endif
3543 #ifdef SO_RCVLOWAT
3544 PyModule_AddIntConstant(m, "SO_RCVLOWAT", SO_RCVLOWAT);
3545 #endif
3546 #ifdef SO_SNDTIMEO
3547 PyModule_AddIntConstant(m, "SO_SNDTIMEO", SO_SNDTIMEO);
3548 #endif
3549 #ifdef SO_RCVTIMEO
3550 PyModule_AddIntConstant(m, "SO_RCVTIMEO", SO_RCVTIMEO);
3551 #endif
3552 #ifdef SO_ERROR
3553 PyModule_AddIntConstant(m, "SO_ERROR", SO_ERROR);
3554 #endif
3555 #ifdef SO_TYPE
3556 PyModule_AddIntConstant(m, "SO_TYPE", SO_TYPE);
3557 #endif
3559 /* Maximum number of connections for "listen" */
3560 #ifdef SOMAXCONN
3561 PyModule_AddIntConstant(m, "SOMAXCONN", SOMAXCONN);
3562 #else
3563 PyModule_AddIntConstant(m, "SOMAXCONN", 5); /* Common value */
3564 #endif
3566 /* Flags for send, recv */
3567 #ifdef MSG_OOB
3568 PyModule_AddIntConstant(m, "MSG_OOB", MSG_OOB);
3569 #endif
3570 #ifdef MSG_PEEK
3571 PyModule_AddIntConstant(m, "MSG_PEEK", MSG_PEEK);
3572 #endif
3573 #ifdef MSG_DONTROUTE
3574 PyModule_AddIntConstant(m, "MSG_DONTROUTE", MSG_DONTROUTE);
3575 #endif
3576 #ifdef MSG_DONTWAIT
3577 PyModule_AddIntConstant(m, "MSG_DONTWAIT", MSG_DONTWAIT);
3578 #endif
3579 #ifdef MSG_EOR
3580 PyModule_AddIntConstant(m, "MSG_EOR", MSG_EOR);
3581 #endif
3582 #ifdef MSG_TRUNC
3583 PyModule_AddIntConstant(m, "MSG_TRUNC", MSG_TRUNC);
3584 #endif
3585 #ifdef MSG_CTRUNC
3586 PyModule_AddIntConstant(m, "MSG_CTRUNC", MSG_CTRUNC);
3587 #endif
3588 #ifdef MSG_WAITALL
3589 PyModule_AddIntConstant(m, "MSG_WAITALL", MSG_WAITALL);
3590 #endif
3591 #ifdef MSG_BTAG
3592 PyModule_AddIntConstant(m, "MSG_BTAG", MSG_BTAG);
3593 #endif
3594 #ifdef MSG_ETAG
3595 PyModule_AddIntConstant(m, "MSG_ETAG", MSG_ETAG);
3596 #endif
3598 /* Protocol level and numbers, usable for [gs]etsockopt */
3599 #ifdef SOL_SOCKET
3600 PyModule_AddIntConstant(m, "SOL_SOCKET", SOL_SOCKET);
3601 #endif
3602 #ifdef SOL_IP
3603 PyModule_AddIntConstant(m, "SOL_IP", SOL_IP);
3604 #else
3605 PyModule_AddIntConstant(m, "SOL_IP", 0);
3606 #endif
3607 #ifdef SOL_IPX
3608 PyModule_AddIntConstant(m, "SOL_IPX", SOL_IPX);
3609 #endif
3610 #ifdef SOL_AX25
3611 PyModule_AddIntConstant(m, "SOL_AX25", SOL_AX25);
3612 #endif
3613 #ifdef SOL_ATALK
3614 PyModule_AddIntConstant(m, "SOL_ATALK", SOL_ATALK);
3615 #endif
3616 #ifdef SOL_NETROM
3617 PyModule_AddIntConstant(m, "SOL_NETROM", SOL_NETROM);
3618 #endif
3619 #ifdef SOL_ROSE
3620 PyModule_AddIntConstant(m, "SOL_ROSE", SOL_ROSE);
3621 #endif
3622 #ifdef SOL_TCP
3623 PyModule_AddIntConstant(m, "SOL_TCP", SOL_TCP);
3624 #else
3625 PyModule_AddIntConstant(m, "SOL_TCP", 6);
3626 #endif
3627 #ifdef SOL_UDP
3628 PyModule_AddIntConstant(m, "SOL_UDP", SOL_UDP);
3629 #else
3630 PyModule_AddIntConstant(m, "SOL_UDP", 17);
3631 #endif
3632 #ifdef IPPROTO_IP
3633 PyModule_AddIntConstant(m, "IPPROTO_IP", IPPROTO_IP);
3634 #else
3635 PyModule_AddIntConstant(m, "IPPROTO_IP", 0);
3636 #endif
3637 #ifdef IPPROTO_HOPOPTS
3638 PyModule_AddIntConstant(m, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS);
3639 #endif
3640 #ifdef IPPROTO_ICMP
3641 PyModule_AddIntConstant(m, "IPPROTO_ICMP", IPPROTO_ICMP);
3642 #else
3643 PyModule_AddIntConstant(m, "IPPROTO_ICMP", 1);
3644 #endif
3645 #ifdef IPPROTO_IGMP
3646 PyModule_AddIntConstant(m, "IPPROTO_IGMP", IPPROTO_IGMP);
3647 #endif
3648 #ifdef IPPROTO_GGP
3649 PyModule_AddIntConstant(m, "IPPROTO_GGP", IPPROTO_GGP);
3650 #endif
3651 #ifdef IPPROTO_IPV4
3652 PyModule_AddIntConstant(m, "IPPROTO_IPV4", IPPROTO_IPV4);
3653 #endif
3654 #ifdef IPPROTO_IPIP
3655 PyModule_AddIntConstant(m, "IPPROTO_IPIP", IPPROTO_IPIP);
3656 #endif
3657 #ifdef IPPROTO_TCP
3658 PyModule_AddIntConstant(m, "IPPROTO_TCP", IPPROTO_TCP);
3659 #else
3660 PyModule_AddIntConstant(m, "IPPROTO_TCP", 6);
3661 #endif
3662 #ifdef IPPROTO_EGP
3663 PyModule_AddIntConstant(m, "IPPROTO_EGP", IPPROTO_EGP);
3664 #endif
3665 #ifdef IPPROTO_PUP
3666 PyModule_AddIntConstant(m, "IPPROTO_PUP", IPPROTO_PUP);
3667 #endif
3668 #ifdef IPPROTO_UDP
3669 PyModule_AddIntConstant(m, "IPPROTO_UDP", IPPROTO_UDP);
3670 #else
3671 PyModule_AddIntConstant(m, "IPPROTO_UDP", 17);
3672 #endif
3673 #ifdef IPPROTO_IDP
3674 PyModule_AddIntConstant(m, "IPPROTO_IDP", IPPROTO_IDP);
3675 #endif
3676 #ifdef IPPROTO_HELLO
3677 PyModule_AddIntConstant(m, "IPPROTO_HELLO", IPPROTO_HELLO);
3678 #endif
3679 #ifdef IPPROTO_ND
3680 PyModule_AddIntConstant(m, "IPPROTO_ND", IPPROTO_ND);
3681 #endif
3682 #ifdef IPPROTO_TP
3683 PyModule_AddIntConstant(m, "IPPROTO_TP", IPPROTO_TP);
3684 #endif
3685 #ifdef IPPROTO_IPV6
3686 PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
3687 #endif
3688 #ifdef IPPROTO_ROUTING
3689 PyModule_AddIntConstant(m, "IPPROTO_ROUTING", IPPROTO_ROUTING);
3690 #endif
3691 #ifdef IPPROTO_FRAGMENT
3692 PyModule_AddIntConstant(m, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT);
3693 #endif
3694 #ifdef IPPROTO_RSVP
3695 PyModule_AddIntConstant(m, "IPPROTO_RSVP", IPPROTO_RSVP);
3696 #endif
3697 #ifdef IPPROTO_GRE
3698 PyModule_AddIntConstant(m, "IPPROTO_GRE", IPPROTO_GRE);
3699 #endif
3700 #ifdef IPPROTO_ESP
3701 PyModule_AddIntConstant(m, "IPPROTO_ESP", IPPROTO_ESP);
3702 #endif
3703 #ifdef IPPROTO_AH
3704 PyModule_AddIntConstant(m, "IPPROTO_AH", IPPROTO_AH);
3705 #endif
3706 #ifdef IPPROTO_MOBILE
3707 PyModule_AddIntConstant(m, "IPPROTO_MOBILE", IPPROTO_MOBILE);
3708 #endif
3709 #ifdef IPPROTO_ICMPV6
3710 PyModule_AddIntConstant(m, "IPPROTO_ICMPV6", IPPROTO_ICMPV6);
3711 #endif
3712 #ifdef IPPROTO_NONE
3713 PyModule_AddIntConstant(m, "IPPROTO_NONE", IPPROTO_NONE);
3714 #endif
3715 #ifdef IPPROTO_DSTOPTS
3716 PyModule_AddIntConstant(m, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS);
3717 #endif
3718 #ifdef IPPROTO_XTP
3719 PyModule_AddIntConstant(m, "IPPROTO_XTP", IPPROTO_XTP);
3720 #endif
3721 #ifdef IPPROTO_EON
3722 PyModule_AddIntConstant(m, "IPPROTO_EON", IPPROTO_EON);
3723 #endif
3724 #ifdef IPPROTO_PIM
3725 PyModule_AddIntConstant(m, "IPPROTO_PIM", IPPROTO_PIM);
3726 #endif
3727 #ifdef IPPROTO_IPCOMP
3728 PyModule_AddIntConstant(m, "IPPROTO_IPCOMP", IPPROTO_IPCOMP);
3729 #endif
3730 #ifdef IPPROTO_VRRP
3731 PyModule_AddIntConstant(m, "IPPROTO_VRRP", IPPROTO_VRRP);
3732 #endif
3733 #ifdef IPPROTO_BIP
3734 PyModule_AddIntConstant(m, "IPPROTO_BIP", IPPROTO_BIP);
3735 #endif
3736 /**/
3737 #ifdef IPPROTO_RAW
3738 PyModule_AddIntConstant(m, "IPPROTO_RAW", IPPROTO_RAW);
3739 #else
3740 PyModule_AddIntConstant(m, "IPPROTO_RAW", 255);
3741 #endif
3742 #ifdef IPPROTO_MAX
3743 PyModule_AddIntConstant(m, "IPPROTO_MAX", IPPROTO_MAX);
3744 #endif
3746 /* Some port configuration */
3747 #ifdef IPPORT_RESERVED
3748 PyModule_AddIntConstant(m, "IPPORT_RESERVED", IPPORT_RESERVED);
3749 #else
3750 PyModule_AddIntConstant(m, "IPPORT_RESERVED", 1024);
3751 #endif
3752 #ifdef IPPORT_USERRESERVED
3753 PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", IPPORT_USERRESERVED);
3754 #else
3755 PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", 5000);
3756 #endif
3758 /* Some reserved IP v.4 addresses */
3759 #ifdef INADDR_ANY
3760 PyModule_AddIntConstant(m, "INADDR_ANY", INADDR_ANY);
3761 #else
3762 PyModule_AddIntConstant(m, "INADDR_ANY", 0x00000000);
3763 #endif
3764 #ifdef INADDR_BROADCAST
3765 PyModule_AddIntConstant(m, "INADDR_BROADCAST", INADDR_BROADCAST);
3766 #else
3767 PyModule_AddIntConstant(m, "INADDR_BROADCAST", 0xffffffff);
3768 #endif
3769 #ifdef INADDR_LOOPBACK
3770 PyModule_AddIntConstant(m, "INADDR_LOOPBACK", INADDR_LOOPBACK);
3771 #else
3772 PyModule_AddIntConstant(m, "INADDR_LOOPBACK", 0x7F000001);
3773 #endif
3774 #ifdef INADDR_UNSPEC_GROUP
3775 PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
3776 #else
3777 PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", 0xe0000000);
3778 #endif
3779 #ifdef INADDR_ALLHOSTS_GROUP
3780 PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP",
3781 INADDR_ALLHOSTS_GROUP);
3782 #else
3783 PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
3784 #endif
3785 #ifdef INADDR_MAX_LOCAL_GROUP
3786 PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP",
3787 INADDR_MAX_LOCAL_GROUP);
3788 #else
3789 PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
3790 #endif
3791 #ifdef INADDR_NONE
3792 PyModule_AddIntConstant(m, "INADDR_NONE", INADDR_NONE);
3793 #else
3794 PyModule_AddIntConstant(m, "INADDR_NONE", 0xffffffff);
3795 #endif
3797 /* IPv4 [gs]etsockopt options */
3798 #ifdef IP_OPTIONS
3799 PyModule_AddIntConstant(m, "IP_OPTIONS", IP_OPTIONS);
3800 #endif
3801 #ifdef IP_HDRINCL
3802 PyModule_AddIntConstant(m, "IP_HDRINCL", IP_HDRINCL);
3803 #endif
3804 #ifdef IP_TOS
3805 PyModule_AddIntConstant(m, "IP_TOS", IP_TOS);
3806 #endif
3807 #ifdef IP_TTL
3808 PyModule_AddIntConstant(m, "IP_TTL", IP_TTL);
3809 #endif
3810 #ifdef IP_RECVOPTS
3811 PyModule_AddIntConstant(m, "IP_RECVOPTS", IP_RECVOPTS);
3812 #endif
3813 #ifdef IP_RECVRETOPTS
3814 PyModule_AddIntConstant(m, "IP_RECVRETOPTS", IP_RECVRETOPTS);
3815 #endif
3816 #ifdef IP_RECVDSTADDR
3817 PyModule_AddIntConstant(m, "IP_RECVDSTADDR", IP_RECVDSTADDR);
3818 #endif
3819 #ifdef IP_RETOPTS
3820 PyModule_AddIntConstant(m, "IP_RETOPTS", IP_RETOPTS);
3821 #endif
3822 #ifdef IP_MULTICAST_IF
3823 PyModule_AddIntConstant(m, "IP_MULTICAST_IF", IP_MULTICAST_IF);
3824 #endif
3825 #ifdef IP_MULTICAST_TTL
3826 PyModule_AddIntConstant(m, "IP_MULTICAST_TTL", IP_MULTICAST_TTL);
3827 #endif
3828 #ifdef IP_MULTICAST_LOOP
3829 PyModule_AddIntConstant(m, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
3830 #endif
3831 #ifdef IP_ADD_MEMBERSHIP
3832 PyModule_AddIntConstant(m, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
3833 #endif
3834 #ifdef IP_DROP_MEMBERSHIP
3835 PyModule_AddIntConstant(m, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
3836 #endif
3837 #ifdef IP_DEFAULT_MULTICAST_TTL
3838 PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_TTL",
3839 IP_DEFAULT_MULTICAST_TTL);
3840 #endif
3841 #ifdef IP_DEFAULT_MULTICAST_LOOP
3842 PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_LOOP",
3843 IP_DEFAULT_MULTICAST_LOOP);
3844 #endif
3845 #ifdef IP_MAX_MEMBERSHIPS
3846 PyModule_AddIntConstant(m, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS);
3847 #endif
3849 /* IPv6 [gs]etsockopt options, defined in RFC2553 */
3850 #ifdef IPV6_JOIN_GROUP
3851 PyModule_AddIntConstant(m, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP);
3852 #endif
3853 #ifdef IPV6_LEAVE_GROUP
3854 PyModule_AddIntConstant(m, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP);
3855 #endif
3856 #ifdef IPV6_MULTICAST_HOPS
3857 PyModule_AddIntConstant(m, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS);
3858 #endif
3859 #ifdef IPV6_MULTICAST_IF
3860 PyModule_AddIntConstant(m, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF);
3861 #endif
3862 #ifdef IPV6_MULTICAST_LOOP
3863 PyModule_AddIntConstant(m, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP);
3864 #endif
3865 #ifdef IPV6_UNICAST_HOPS
3866 PyModule_AddIntConstant(m, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS);
3867 #endif
3869 /* TCP options */
3870 #ifdef TCP_NODELAY
3871 PyModule_AddIntConstant(m, "TCP_NODELAY", TCP_NODELAY);
3872 #endif
3873 #ifdef TCP_MAXSEG
3874 PyModule_AddIntConstant(m, "TCP_MAXSEG", TCP_MAXSEG);
3875 #endif
3876 #ifdef TCP_CORK
3877 PyModule_AddIntConstant(m, "TCP_CORK", TCP_CORK);
3878 #endif
3879 #ifdef TCP_KEEPIDLE
3880 PyModule_AddIntConstant(m, "TCP_KEEPIDLE", TCP_KEEPIDLE);
3881 #endif
3882 #ifdef TCP_KEEPINTVL
3883 PyModule_AddIntConstant(m, "TCP_KEEPINTVL", TCP_KEEPINTVL);
3884 #endif
3885 #ifdef TCP_KEEPCNT
3886 PyModule_AddIntConstant(m, "TCP_KEEPCNT", TCP_KEEPCNT);
3887 #endif
3888 #ifdef TCP_SYNCNT
3889 PyModule_AddIntConstant(m, "TCP_SYNCNT", TCP_SYNCNT);
3890 #endif
3891 #ifdef TCP_LINGER2
3892 PyModule_AddIntConstant(m, "TCP_LINGER2", TCP_LINGER2);
3893 #endif
3894 #ifdef TCP_DEFER_ACCEPT
3895 PyModule_AddIntConstant(m, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT);
3896 #endif
3897 #ifdef TCP_WINDOW_CLAMP
3898 PyModule_AddIntConstant(m, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP);
3899 #endif
3900 #ifdef TCP_INFO
3901 PyModule_AddIntConstant(m, "TCP_INFO", TCP_INFO);
3902 #endif
3903 #ifdef TCP_QUICKACK
3904 PyModule_AddIntConstant(m, "TCP_QUICKACK", TCP_QUICKACK);
3905 #endif
3908 /* IPX options */
3909 #ifdef IPX_TYPE
3910 PyModule_AddIntConstant(m, "IPX_TYPE", IPX_TYPE);
3911 #endif
3913 /* get{addr,name}info parameters */
3914 #ifdef EAI_ADDRFAMILY
3915 PyModule_AddIntConstant(m, "EAI_ADDRFAMILY", EAI_ADDRFAMILY);
3916 #endif
3917 #ifdef EAI_AGAIN
3918 PyModule_AddIntConstant(m, "EAI_AGAIN", EAI_AGAIN);
3919 #endif
3920 #ifdef EAI_BADFLAGS
3921 PyModule_AddIntConstant(m, "EAI_BADFLAGS", EAI_BADFLAGS);
3922 #endif
3923 #ifdef EAI_FAIL
3924 PyModule_AddIntConstant(m, "EAI_FAIL", EAI_FAIL);
3925 #endif
3926 #ifdef EAI_FAMILY
3927 PyModule_AddIntConstant(m, "EAI_FAMILY", EAI_FAMILY);
3928 #endif
3929 #ifdef EAI_MEMORY
3930 PyModule_AddIntConstant(m, "EAI_MEMORY", EAI_MEMORY);
3931 #endif
3932 #ifdef EAI_NODATA
3933 PyModule_AddIntConstant(m, "EAI_NODATA", EAI_NODATA);
3934 #endif
3935 #ifdef EAI_NONAME
3936 PyModule_AddIntConstant(m, "EAI_NONAME", EAI_NONAME);
3937 #endif
3938 #ifdef EAI_SERVICE
3939 PyModule_AddIntConstant(m, "EAI_SERVICE", EAI_SERVICE);
3940 #endif
3941 #ifdef EAI_SOCKTYPE
3942 PyModule_AddIntConstant(m, "EAI_SOCKTYPE", EAI_SOCKTYPE);
3943 #endif
3944 #ifdef EAI_SYSTEM
3945 PyModule_AddIntConstant(m, "EAI_SYSTEM", EAI_SYSTEM);
3946 #endif
3947 #ifdef EAI_BADHINTS
3948 PyModule_AddIntConstant(m, "EAI_BADHINTS", EAI_BADHINTS);
3949 #endif
3950 #ifdef EAI_PROTOCOL
3951 PyModule_AddIntConstant(m, "EAI_PROTOCOL", EAI_PROTOCOL);
3952 #endif
3953 #ifdef EAI_MAX
3954 PyModule_AddIntConstant(m, "EAI_MAX", EAI_MAX);
3955 #endif
3956 #ifdef AI_PASSIVE
3957 PyModule_AddIntConstant(m, "AI_PASSIVE", AI_PASSIVE);
3958 #endif
3959 #ifdef AI_CANONNAME
3960 PyModule_AddIntConstant(m, "AI_CANONNAME", AI_CANONNAME);
3961 #endif
3962 #ifdef AI_NUMERICHOST
3963 PyModule_AddIntConstant(m, "AI_NUMERICHOST", AI_NUMERICHOST);
3964 #endif
3965 #ifdef AI_MASK
3966 PyModule_AddIntConstant(m, "AI_MASK", AI_MASK);
3967 #endif
3968 #ifdef AI_ALL
3969 PyModule_AddIntConstant(m, "AI_ALL", AI_ALL);
3970 #endif
3971 #ifdef AI_V4MAPPED_CFG
3972 PyModule_AddIntConstant(m, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG);
3973 #endif
3974 #ifdef AI_ADDRCONFIG
3975 PyModule_AddIntConstant(m, "AI_ADDRCONFIG", AI_ADDRCONFIG);
3976 #endif
3977 #ifdef AI_V4MAPPED
3978 PyModule_AddIntConstant(m, "AI_V4MAPPED", AI_V4MAPPED);
3979 #endif
3980 #ifdef AI_DEFAULT
3981 PyModule_AddIntConstant(m, "AI_DEFAULT", AI_DEFAULT);
3982 #endif
3983 #ifdef NI_MAXHOST
3984 PyModule_AddIntConstant(m, "NI_MAXHOST", NI_MAXHOST);
3985 #endif
3986 #ifdef NI_MAXSERV
3987 PyModule_AddIntConstant(m, "NI_MAXSERV", NI_MAXSERV);
3988 #endif
3989 #ifdef NI_NOFQDN
3990 PyModule_AddIntConstant(m, "NI_NOFQDN", NI_NOFQDN);
3991 #endif
3992 #ifdef NI_NUMERICHOST
3993 PyModule_AddIntConstant(m, "NI_NUMERICHOST", NI_NUMERICHOST);
3994 #endif
3995 #ifdef NI_NAMEREQD
3996 PyModule_AddIntConstant(m, "NI_NAMEREQD", NI_NAMEREQD);
3997 #endif
3998 #ifdef NI_NUMERICSERV
3999 PyModule_AddIntConstant(m, "NI_NUMERICSERV", NI_NUMERICSERV);
4000 #endif
4001 #ifdef NI_DGRAM
4002 PyModule_AddIntConstant(m, "NI_DGRAM", NI_DGRAM);
4003 #endif
4005 /* Initialize gethostbyname lock */
4006 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
4007 netdb_lock = PyThread_allocate_lock();
4008 #endif
4012 #ifndef HAVE_INET_PTON
4014 /* Simplistic emulation code for inet_pton that only works for IPv4 */
4015 /* These are not exposed because they do not set errno properly */
4018 inet_pton(int af, const char *src, void *dst)
4020 if (af == AF_INET) {
4021 long packed_addr;
4022 packed_addr = inet_addr(src);
4023 if (packed_addr == INADDR_NONE)
4024 return 0;
4025 memcpy(dst, &packed_addr, 4);
4026 return 1;
4028 /* Should set errno to EAFNOSUPPORT */
4029 return -1;
4032 const char *
4033 inet_ntop(int af, const void *src, char *dst, socklen_t size)
4035 if (af == AF_INET) {
4036 struct in_addr packed_addr;
4037 if (size < 16)
4038 /* Should set errno to ENOSPC. */
4039 return NULL;
4040 memcpy(&packed_addr, src, sizeof(packed_addr));
4041 return strncpy(dst, inet_ntoa(packed_addr), size);
4043 /* Should set errno to EAFNOSUPPORT */
4044 return NULL;
4047 #endif