5 This module provides an interface to Berkeley socket IPC.
9 - Only AF_INET, AF_INET6 and AF_UNIX address families are supported in a
10 portable manner, though AF_PACKET and AF_NETLINK are supported under Linux.
11 - No read/write operations (use sendall/recv or makefile instead).
12 - Additional restrictions apply on some non-Unix platforms (compensated
17 - socket.error: exception raised for socket specific errors
18 - socket.gaierror: exception raised for getaddrinfo/getnameinfo errors,
19 a subclass of socket.error
20 - socket.herror: exception raised for gethostby* errors,
21 a subclass of socket.error
22 - socket.fromfd(fd, family, type[, proto]) --> new socket object (created
23 from an existing file descriptor)
24 - socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')
25 - socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])
26 - socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com')
27 - socket.getprotobyname(protocolname) --> protocol number
28 - socket.getservbyname(servicename[, protocolname]) --> port number
29 - socket.getservbyport(portnumber[, protocolname]) --> service name
30 - socket.socket([family[, type [, proto]]]) --> new socket object
31 - socket.socketpair([family[, type [, proto]]]) --> (socket, socket)
32 - socket.ntohs(16 bit value) --> new int object
33 - socket.ntohl(32 bit value) --> new int object
34 - socket.htons(16 bit value) --> new int object
35 - socket.htonl(32 bit value) --> new int object
36 - socket.getaddrinfo(host, port [, family, socktype, proto, flags])
37 --> List of (family, socktype, proto, canonname, sockaddr)
38 - socket.getnameinfo(sockaddr, flags) --> (host, port)
39 - socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
40 - socket.has_ipv6: boolean value indicating if IPv6 is supported
41 - socket.inet_aton(IP address) -> 32-bit packed IP representation
42 - socket.inet_ntoa(packed IP) -> IP address string
43 - socket.getdefaulttimeout() -> None | float
44 - socket.setdefaulttimeout(None | float)
45 - an Internet socket address is a pair (hostname, port)
46 where hostname can be anything recognized by gethostbyname()
47 (including the dd.dd.dd.dd notation) and port is in host byte order
48 - where a hostname is returned, the dd.dd.dd.dd notation is used
49 - a UNIX domain socket address is a string specifying the pathname
50 - an AF_PACKET socket address is a tuple containing a string
51 specifying the ethernet interface and an integer specifying
52 the Ethernet protocol number to be received. For example:
53 ("eth0",0x1234). Optional 3rd,4th,5th elements in the tuple
54 specify packet-type and ha-type/addr.
56 Local naming conventions:
58 - names starting with sock_ are socket object methods
59 - names starting with socket_ are module-level functions
60 - names starting with PySocket are exported through socketmodule.h
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\
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\
79 A socket object represents one endpoint of a network connection.\n\
81 Methods of socket objects (keyword arguments not allowed):\n\
83 accept() -- accept a connection, returning new socket and client address\n\
84 bind(addr) -- bind the socket to a local address\n\
85 close() -- close the socket\n\
86 connect(addr) -- connect the socket to a remote address\n\
87 connect_ex(addr) -- connect, return an error code instead of an exception\n\
88 dup() -- return a new socket object identical to the current one [*]\n\
89 fileno() -- return underlying file descriptor\n\
90 getpeername() -- return remote address [*]\n\
91 getsockname() -- return local address\n\
92 getsockopt(level, optname[, buflen]) -- get socket options\n\
93 gettimeout() -- return timeout or None\n\
94 listen(n) -- start listening for incoming connections\n\
95 makefile([mode, [bufsize]]) -- return a file object for the socket [*]\n\
96 recv(buflen[, flags]) -- receive data\n\
97 recvfrom(buflen[, flags]) -- receive data and sender's address\n\
98 sendall(data[, flags]) -- send all data\n\
99 send(data[, flags]) -- send data, may not send all of it\n\
100 sendto(data[, flags], addr) -- send data to a given address\n\
101 setblocking(0 | 1) -- set or clear the blocking I/O flag\n\
102 setsockopt(level, optname, value) -- set socket options\n\
103 settimeout(None | float) -- set or clear the timeout\n\
104 shutdown(how) -- shut down traffic in one or both directions\n\
106 [*] not available on all platforms!");
108 /* XXX This is a terrible mess of platform-dependent preprocessor hacks.
109 I hope some day someone can clean this up please... */
111 /* Hacks for gethostbyname_r(). On some non-Linux platforms, the configure
112 script doesn't get this right, so we hardcode some platform checks below.
113 On the other hand, not all Linux versions agree, so there the settings
114 computed by the configure script are needed! */
117 # undef HAVE_GETHOSTBYNAME_R_3_ARG
118 # undef HAVE_GETHOSTBYNAME_R_5_ARG
119 # undef HAVE_GETHOSTBYNAME_R_6_ARG
123 # undef HAVE_GETHOSTBYNAME_R
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 */
134 # undef HAVE_GETHOSTBYNAME_R
138 #if !defined(HAVE_GETHOSTBYNAME_R) && defined(WITH_THREAD) && \
140 # define USE_GETHOSTBYNAME_LOCK
143 /* To use __FreeBSD_version */
144 #ifdef HAVE_SYS_PARAM_H
145 #include <sys/param.h>
147 /* On systems on which getaddrinfo() is believed to not be thread-safe,
148 (this includes the getaddrinfo emulation) protect access with a lock. */
149 #if defined(WITH_THREAD) && (defined(__APPLE__) || \
150 (defined(__FreeBSD__) && __FreeBSD_version+0 < 503000) || \
151 defined(__OpenBSD__) || defined(__NetBSD__) || !defined(HAVE_GETADDRINFO))
152 #define USE_GETADDRINFO_LOCK
155 #ifdef USE_GETADDRINFO_LOCK
156 #define ACQUIRE_GETADDRINFO_LOCK PyThread_acquire_lock(netdb_lock, 1);
157 #define RELEASE_GETADDRINFO_LOCK PyThread_release_lock(netdb_lock);
159 #define ACQUIRE_GETADDRINFO_LOCK
160 #define RELEASE_GETADDRINFO_LOCK
163 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
164 # include "pythread.h"
167 #if defined(PYCC_VACPP)
170 # include <sys/ioctl.h>
176 #if ! defined(_SOCKADDR_LEN)
180 # include "TCPIP_IOCTL_ROUTINE"
186 #if defined(PYOS_OS2)
188 # define INCL_DOSERRORS
189 # define INCL_NOPMAPI
193 #if defined(__sgi) && _COMPILER_VERSION>700 && !_SGIAPI
194 /* make sure that the reentrant (gethostbyaddr_r etc)
195 functions are declared correctly if compiling with
196 MIPSPro 7.x in ANSI C mode (default) */
198 /* XXX Using _SGIAPI is the wrong thing,
199 but I don't know what the right thing is. */
200 #undef _SGIAPI /* to avoid warning */
204 #include <sys/socket.h>
205 #include <sys/types.h>
206 #include <netinet/in.h>
208 #define HAVE_GETADDRINFO 1
209 #define HAVE_GETNAMEINFO 1
212 #define HAVE_INET_PTON
216 /* Irix 6.5 fails to define this variable at all. This is needed
217 for both GCC and SGI's compiler. I'd say that the SGI headers
219 #if defined(__sgi) && !defined(INET_ADDRSTRLEN)
220 #define INET_ADDRSTRLEN 16
223 /* Generic includes */
224 #include <sys/types.h>
226 /* Generic socket object definitions and includes */
227 #define PySocket_BUILDING_SOCKET
228 #include "socketmodule.h"
230 /* Addressing includes */
234 /* Non-MS WINDOWS includes */
237 /* Headers needed for inet_ntoa() and inet_addr() */
239 # include <net/netdb.h>
240 # elif defined(PYOS_OS2) && defined(PYCC_VACPP)
242 typedef size_t socklen_t
;
244 # include <arpa/inet.h>
250 # include <sys/ioctl.h>
251 # include <socklib.h>
253 int h_errno
; /* not used */
254 # define INET_ADDRSTRLEN 16
259 /* MS_WINDOWS includes */
267 # define offsetof(type, member) ((size_t)(&((type *)0)->member))
271 # define O_NONBLOCK O_NDELAY
274 /* include Python's addrinfo.h unless it causes trouble */
275 #if defined(__sgi) && _COMPILER_VERSION>700 && defined(_SS_ALIGNSIZE)
276 /* Do not include addinfo.h on some newer IRIX versions.
277 * _SS_ALIGNSIZE is defined in sys/socket.h by 6.5.21,
278 * for example, but not by 6.5.10.
280 #elif defined(_MSC_VER) && _MSC_VER>1200
281 /* Do not include addrinfo.h for MSVC7 or greater. 'addrinfo' and
282 * EAI_* constants are defined in (the already included) ws2tcpip.h.
285 # include "addrinfo.h"
288 #ifndef HAVE_INET_PTON
289 int inet_pton(int af
, const char *src
, void *dst
);
290 const char *inet_ntop(int af
, const void *src
, char *dst
, socklen_t size
);
294 /* On OS X, getaddrinfo returns no error indication of lookup
295 failure, so we must use the emulation instead of the libinfo
296 implementation. Unfortunately, performing an autoconf test
297 for this bug would require DNS access for the machine performing
298 the configuration, which is not acceptable. Therefore, we
299 determine the bug just by checking for __APPLE__. If this bug
300 gets ever fixed, perhaps checking for sys/version.h would be
301 appropriate, which is 10/0 on the system with the bug. */
302 #ifndef HAVE_GETNAMEINFO
303 /* This bug seems to be fixed in Jaguar. Ths easiest way I could
304 Find to check for Jaguar is that it has getnameinfo(), which
305 older releases don't have */
306 #undef HAVE_GETADDRINFO
310 /* I know this is a bad practice, but it is the easiest... */
311 #if !defined(HAVE_GETADDRINFO)
312 /* avoid clashes with the C library definition of the symbol. */
313 #define getaddrinfo fake_getaddrinfo
314 #define gai_strerror fake_gai_strerror
315 #define freeaddrinfo fake_freeaddrinfo
316 #include "getaddrinfo.c"
318 #if !defined(HAVE_GETNAMEINFO)
319 #define getnameinfo fake_getnameinfo
320 #include "getnameinfo.c"
323 #if defined(MS_WINDOWS) || defined(__BEOS__)
324 /* BeOS suffers from the same socket dichotomy as Win32... - [cjh] */
325 /* seem to be a few differences in the API */
326 #define SOCKETCLOSE closesocket
327 #define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */
331 #define EAFNOSUPPORT WSAEAFNOSUPPORT
332 #define snprintf _snprintf
335 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
336 #define SOCKETCLOSE soclose
337 #define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
341 #define SOCKETCLOSE close
345 /* TCP/IP Services for VMS uses a maximum send/revc buffer length of 65535 */
346 #define SEGMENT_SIZE 65535
349 #if defined(HAVE_BLUETOOTH_H) || defined(HAVE_BLUETOOTH_BLUETOOTH_H)
350 #define USE_BLUETOOTH 1
351 #if defined(__FreeBSD__)
352 #define BTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP
353 #define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM
354 #define sockaddr_l2 sockaddr_l2cap
355 #define sockaddr_rc sockaddr_rfcomm
356 #define _BT_SOCKADDR_MEMB(s, proto) &((s)->sock_addr)
357 #define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb)
358 #define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)
360 #define _BT_SOCKADDR_MEMB(s, proto) (&((s)->sock_addr).bt_##proto)
361 #define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb)
362 #define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb)
363 #define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)
368 * Constants for getnameinfo()
370 #if !defined(NI_MAXHOST)
371 #define NI_MAXHOST 1025
373 #if !defined(NI_MAXSERV)
374 #define NI_MAXSERV 32
377 /* XXX There's a problem here: *static* functions are not supposed to have
378 a Py prefix (or use CapitalizedWords). Later... */
380 /* Global variable holding the exception type for errors detected
381 by this module (but not argument type or memory errors, etc.). */
382 static PyObject
*socket_error
;
383 static PyObject
*socket_herror
;
384 static PyObject
*socket_gaierror
;
385 static PyObject
*socket_timeout
;
388 /* Global variable which is !=0 if Python is running in a RISC OS taskwindow */
389 static int taskwindow
;
392 /* A forward reference to the socket type object.
393 The sock_type variable contains pointers to various functions,
394 some of which call new_sockobject(), which uses sock_type, so
395 there has to be a circular reference. */
396 static PyTypeObject sock_type
;
398 /* Convenience function to raise an error according to errno
399 and return a NULL pointer from a function. */
405 int err_no
= WSAGetLastError();
410 {WSAEINTR
, "Interrupted system call"},
411 {WSAEBADF
, "Bad file descriptor"},
412 {WSAEACCES
, "Permission denied"},
413 {WSAEFAULT
, "Bad address"},
414 {WSAEINVAL
, "Invalid argument"},
415 {WSAEMFILE
, "Too many open files"},
417 "The socket operation could not complete "
419 {WSAEINPROGRESS
, "Operation now in progress"},
420 {WSAEALREADY
, "Operation already in progress"},
421 {WSAENOTSOCK
, "Socket operation on non-socket"},
422 {WSAEDESTADDRREQ
, "Destination address required"},
423 {WSAEMSGSIZE
, "Message too long"},
424 {WSAEPROTOTYPE
, "Protocol wrong type for socket"},
425 {WSAENOPROTOOPT
, "Protocol not available"},
426 {WSAEPROTONOSUPPORT
, "Protocol not supported"},
427 {WSAESOCKTNOSUPPORT
, "Socket type not supported"},
428 {WSAEOPNOTSUPP
, "Operation not supported"},
429 {WSAEPFNOSUPPORT
, "Protocol family not supported"},
430 {WSAEAFNOSUPPORT
, "Address family not supported"},
431 {WSAEADDRINUSE
, "Address already in use"},
432 {WSAEADDRNOTAVAIL
, "Can't assign requested address"},
433 {WSAENETDOWN
, "Network is down"},
434 {WSAENETUNREACH
, "Network is unreachable"},
435 {WSAENETRESET
, "Network dropped connection on reset"},
436 {WSAECONNABORTED
, "Software caused connection abort"},
437 {WSAECONNRESET
, "Connection reset by peer"},
438 {WSAENOBUFS
, "No buffer space available"},
439 {WSAEISCONN
, "Socket is already connected"},
440 {WSAENOTCONN
, "Socket is not connected"},
441 {WSAESHUTDOWN
, "Can't send after socket shutdown"},
442 {WSAETOOMANYREFS
, "Too many references: can't splice"},
443 {WSAETIMEDOUT
, "Operation timed out"},
444 {WSAECONNREFUSED
, "Connection refused"},
445 {WSAELOOP
, "Too many levels of symbolic links"},
446 {WSAENAMETOOLONG
, "File name too long"},
447 {WSAEHOSTDOWN
, "Host is down"},
448 {WSAEHOSTUNREACH
, "No route to host"},
449 {WSAENOTEMPTY
, "Directory not empty"},
450 {WSAEPROCLIM
, "Too many processes"},
451 {WSAEUSERS
, "Too many users"},
452 {WSAEDQUOT
, "Disc quota exceeded"},
453 {WSAESTALE
, "Stale NFS file handle"},
454 {WSAEREMOTE
, "Too many levels of remote in path"},
455 {WSASYSNOTREADY
, "Network subsystem is unvailable"},
456 {WSAVERNOTSUPPORTED
, "WinSock version is not supported"},
458 "Successful WSAStartup() not yet performed"},
459 {WSAEDISCON
, "Graceful shutdown in progress"},
460 /* Resolver errors */
461 {WSAHOST_NOT_FOUND
, "No such host is known"},
462 {WSATRY_AGAIN
, "Host not found, or server failed"},
463 {WSANO_RECOVERY
, "Unexpected server error encountered"},
464 {WSANO_DATA
, "Valid name without requested data"},
465 {WSANO_ADDRESS
, "No address, look for MX record"},
470 const char *msg
= "winsock error";
472 for (msgp
= msgs
; msgp
->msg
; msgp
++) {
473 if (err_no
== msgp
->no
) {
479 v
= Py_BuildValue("(is)", err_no
, msg
);
481 PyErr_SetObject(socket_error
, v
);
489 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
490 if (sock_errno() != NO_ERROR
) {
494 int myerrorcode
= sock_errno();
496 /* Retrieve socket-related error message from MPTN.MSG file */
497 rc
= DosGetMessage(NULL
, 0, outbuf
, sizeof(outbuf
),
498 myerrorcode
- SOCBASEERR
+ 26,
501 if (rc
== NO_ERROR
) {
504 /* OS/2 doesn't guarantee a terminator */
505 outbuf
[msglen
] = '\0';
506 if (strlen(outbuf
) > 0) {
507 /* If non-empty msg, trim CRLF */
508 char *lastc
= &outbuf
[ strlen(outbuf
)-1 ];
509 while (lastc
> outbuf
&&
510 isspace(Py_CHARMASK(*lastc
))) {
511 /* Trim trailing whitespace (CRLF) */
515 v
= Py_BuildValue("(is)", myerrorcode
, outbuf
);
517 PyErr_SetObject(socket_error
, v
);
526 if (_inet_error
.errnum
!= NULL
) {
528 v
= Py_BuildValue("(is)", errno
, _inet_err());
530 PyErr_SetObject(socket_error
, v
);
537 return PyErr_SetFromErrno(socket_error
);
542 set_herror(int h_error
)
546 #ifdef HAVE_HSTRERROR
547 v
= Py_BuildValue("(is)", h_error
, (char *)hstrerror(h_error
));
549 v
= Py_BuildValue("(is)", h_error
, "host not found");
552 PyErr_SetObject(socket_herror
, v
);
561 set_gaierror(int error
)
566 /* EAI_SYSTEM is not available on Windows XP. */
567 if (error
== EAI_SYSTEM
)
571 #ifdef HAVE_GAI_STRERROR
572 v
= Py_BuildValue("(is)", error
, gai_strerror(error
));
574 v
= Py_BuildValue("(is)", error
, "getaddrinfo failed");
577 PyErr_SetObject(socket_gaierror
, v
);
584 /* Function to perform the setting of socket blocking mode
585 internally. block = (1 | 0). */
587 internal_setblocking(PySocketSockObject
*s
, int block
)
595 Py_BEGIN_ALLOW_THREADS
598 setsockopt(s
->sock_fd
, SOL_SOCKET
, SO_NONBLOCK
,
599 (void *)(&block
), sizeof(int));
603 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
605 ioctl(s
->sock_fd
, FIONBIO
, (caddr_t
)&block
, sizeof(block
));
608 ioctl(s
->sock_fd
, FIONBIO
, (char *)&block
);
609 #else /* !PYOS_OS2 && !_VMS */
610 delay_flag
= fcntl(s
->sock_fd
, F_GETFL
, 0);
612 delay_flag
&= (~O_NONBLOCK
);
614 delay_flag
|= O_NONBLOCK
;
615 fcntl(s
->sock_fd
, F_SETFL
, delay_flag
);
616 #endif /* !PYOS_OS2 */
617 #else /* MS_WINDOWS */
619 ioctlsocket(s
->sock_fd
, FIONBIO
, (u_long
*)&block
);
620 #endif /* MS_WINDOWS */
623 socketioctl(s
->sock_fd
, FIONBIO
, (u_long
*)&block
);
625 #endif /* __BEOS__ */
628 /* Since these don't return anything */
632 /* Do a select() on the socket, if necessary (sock_timeout > 0).
633 The argument writing indicates the direction.
634 This does not raise an exception; we'll let our caller do that
635 after they've reacquired the interpreter lock.
636 Returns 1 on timeout, 0 otherwise. */
638 internal_select(PySocketSockObject
*s
, int writing
)
644 /* Nothing to do unless we're in timeout mode (not non-blocking) */
645 if (s
->sock_timeout
<= 0.0)
648 /* Guard against closed socket */
652 /* Construct the arguments to select */
653 tv
.tv_sec
= (int)s
->sock_timeout
;
654 tv
.tv_usec
= (int)((s
->sock_timeout
- tv
.tv_sec
) * 1e6
);
656 FD_SET(s
->sock_fd
, &fds
);
658 /* See if the socket is ready */
660 n
= select(s
->sock_fd
+1, NULL
, &fds
, NULL
, &tv
);
662 n
= select(s
->sock_fd
+1, &fds
, NULL
, NULL
, &tv
);
668 /* Initialize a new socket object. */
670 static double defaulttimeout
= -1.0; /* Default timeout for new sockets */
673 init_sockobject(PySocketSockObject
*s
,
674 SOCKET_T fd
, int family
, int type
, int proto
)
680 s
->sock_family
= family
;
682 s
->sock_proto
= proto
;
683 s
->sock_timeout
= defaulttimeout
;
685 s
->errorhandler
= &set_error
;
687 if (defaulttimeout
>= 0.0)
688 internal_setblocking(s
, 0);
692 socketioctl(s
->sock_fd
, 0x80046679, (u_long
*)&block
);
697 /* Create a new socket object.
698 This just creates the object and initializes it.
699 If the creation fails, return NULL and set an exception (implicit
702 static PySocketSockObject
*
703 new_sockobject(SOCKET_T fd
, int family
, int type
, int proto
)
705 PySocketSockObject
*s
;
706 s
= (PySocketSockObject
*)
707 PyType_GenericNew(&sock_type
, NULL
, NULL
);
709 init_sockobject(s
, fd
, family
, type
, proto
);
714 /* Lock to allow python interpreter to continue, but only allow one
715 thread to be in gethostbyname or getaddrinfo */
716 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
717 PyThread_type_lock netdb_lock
;
721 /* Convert a string specifying a host name or one of a few symbolic
722 names to a numeric IP address. This usually calls gethostbyname()
723 to do the work; the names "" and "<broadcast>" are special.
724 Return the length (IPv4 should be 4 bytes), or negative if
725 an error occurred; then an exception is raised. */
728 setipaddr(char *name
, struct sockaddr
*addr_ret
, size_t addr_ret_size
, int af
)
730 struct addrinfo hints
, *res
;
735 memset((void *) addr_ret
, '\0', sizeof(*addr_ret
));
736 if (name
[0] == '\0') {
738 memset(&hints
, 0, sizeof(hints
));
739 hints
.ai_family
= af
;
740 hints
.ai_socktype
= SOCK_DGRAM
; /*dummy*/
741 hints
.ai_flags
= AI_PASSIVE
;
742 Py_BEGIN_ALLOW_THREADS
743 ACQUIRE_GETADDRINFO_LOCK
744 error
= getaddrinfo(NULL
, "0", &hints
, &res
);
746 /* We assume that those thread-unsafe getaddrinfo() versions
747 *are* safe regarding their return value, ie. that a
748 subsequent call to getaddrinfo() does not destroy the
749 outcome of the first call. */
750 RELEASE_GETADDRINFO_LOCK
755 switch (res
->ai_family
) {
766 PyErr_SetString(socket_error
,
767 "unsupported address family");
772 PyErr_SetString(socket_error
,
773 "wildcard resolved to multiple address");
776 if (res
->ai_addrlen
< addr_ret_size
)
777 addr_ret_size
= res
->ai_addrlen
;
778 memcpy(addr_ret
, res
->ai_addr
, addr_ret_size
);
782 if (name
[0] == '<' && strcmp(name
, "<broadcast>") == 0) {
783 struct sockaddr_in
*sin
;
784 if (af
!= AF_INET
&& af
!= AF_UNSPEC
) {
785 PyErr_SetString(socket_error
,
786 "address family mismatched");
789 sin
= (struct sockaddr_in
*)addr_ret
;
790 memset((void *) sin
, '\0', sizeof(*sin
));
791 sin
->sin_family
= AF_INET
;
792 #ifdef HAVE_SOCKADDR_SA_LEN
793 sin
->sin_len
= sizeof(*sin
);
795 sin
->sin_addr
.s_addr
= INADDR_BROADCAST
;
796 return sizeof(sin
->sin_addr
);
798 if (sscanf(name
, "%d.%d.%d.%d%c", &d1
, &d2
, &d3
, &d4
, &ch
) == 4 &&
799 0 <= d1
&& d1
<= 255 && 0 <= d2
&& d2
<= 255 &&
800 0 <= d3
&& d3
<= 255 && 0 <= d4
&& d4
<= 255) {
801 struct sockaddr_in
*sin
;
802 sin
= (struct sockaddr_in
*)addr_ret
;
803 sin
->sin_addr
.s_addr
= htonl(
804 ((long) d1
<< 24) | ((long) d2
<< 16) |
805 ((long) d3
<< 8) | ((long) d4
<< 0));
806 sin
->sin_family
= AF_INET
;
807 #ifdef HAVE_SOCKADDR_SA_LEN
808 sin
->sin_len
= sizeof(*sin
);
812 memset(&hints
, 0, sizeof(hints
));
813 hints
.ai_family
= af
;
814 Py_BEGIN_ALLOW_THREADS
815 ACQUIRE_GETADDRINFO_LOCK
816 error
= getaddrinfo(name
, NULL
, &hints
, &res
);
817 #if defined(__digital__) && defined(__unix__)
818 if (error
== EAI_NONAME
&& af
== AF_UNSPEC
) {
819 /* On Tru64 V5.1, numeric-to-addr conversion fails
820 if no address family is given. Assume IPv4 for now.*/
821 hints
.ai_family
= AF_INET
;
822 error
= getaddrinfo(name
, NULL
, &hints
, &res
);
826 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
831 if (res
->ai_addrlen
< addr_ret_size
)
832 addr_ret_size
= res
->ai_addrlen
;
833 memcpy((char *) addr_ret
, res
->ai_addr
, addr_ret_size
);
835 switch (addr_ret
->sa_family
) {
843 PyErr_SetString(socket_error
, "unknown address family");
849 /* Create a string object representing an IP address.
850 This is always a string of the form 'dd.dd.dd.dd' (with variable
854 makeipaddr(struct sockaddr
*addr
, int addrlen
)
856 char buf
[NI_MAXHOST
];
859 error
= getnameinfo(addr
, addrlen
, buf
, sizeof(buf
), NULL
, 0,
865 return PyString_FromString(buf
);
870 /* Convert a string representation of a Bluetooth address into a numeric
871 address. Returns the length (6), or raises an exception and returns -1 if
872 an error occurred. */
875 setbdaddr(char *name
, bdaddr_t
*bdaddr
)
877 unsigned int b0
, b1
, b2
, b3
, b4
, b5
;
881 n
= sscanf(name
, "%X:%X:%X:%X:%X:%X%c",
882 &b5
, &b4
, &b3
, &b2
, &b1
, &b0
, &ch
);
883 if (n
== 6 && (b0
| b1
| b2
| b3
| b4
| b5
) < 256) {
892 PyErr_SetString(socket_error
, "bad bluetooth address");
897 /* Create a string representation of the Bluetooth address. This is always a
898 string of the form 'XX:XX:XX:XX:XX:XX' where XX is a two digit hexadecimal
899 value (zero padded if necessary). */
902 makebdaddr(bdaddr_t
*bdaddr
)
904 char buf
[(6 * 2) + 5 + 1];
906 sprintf(buf
, "%02X:%02X:%02X:%02X:%02X:%02X",
907 bdaddr
->b
[5], bdaddr
->b
[4], bdaddr
->b
[3],
908 bdaddr
->b
[2], bdaddr
->b
[1], bdaddr
->b
[0]);
909 return PyString_FromString(buf
);
914 /* Create an object representing the given socket address,
915 suitable for passing it back to bind(), connect() etc.
916 The family field of the sockaddr structure is inspected
917 to determine what kind of address it really is. */
921 makesockaddr(int sockfd
, struct sockaddr
*addr
, int addrlen
, int proto
)
924 /* No address -- may be recvfrom() from known socket */
930 /* XXX: BeOS version of accept() doesn't set family correctly */
931 addr
->sa_family
= AF_INET
;
934 switch (addr
->sa_family
) {
938 struct sockaddr_in
*a
;
939 PyObject
*addrobj
= makeipaddr(addr
, sizeof(*a
));
940 PyObject
*ret
= NULL
;
942 a
= (struct sockaddr_in
*)addr
;
943 ret
= Py_BuildValue("Oi", addrobj
, ntohs(a
->sin_port
));
952 struct sockaddr_un
*a
= (struct sockaddr_un
*) addr
;
953 return PyString_FromString(a
->sun_path
);
957 #if defined(AF_NETLINK)
960 struct sockaddr_nl
*a
= (struct sockaddr_nl
*) addr
;
961 return Py_BuildValue("II", a
->nl_pid
, a
->nl_groups
);
963 #endif /* AF_NETLINK */
968 struct sockaddr_in6
*a
;
969 PyObject
*addrobj
= makeipaddr(addr
, sizeof(*a
));
970 PyObject
*ret
= NULL
;
972 a
= (struct sockaddr_in6
*)addr
;
973 ret
= Py_BuildValue("Oiii",
990 struct sockaddr_l2
*a
= (struct sockaddr_l2
*) addr
;
991 PyObject
*addrobj
= makebdaddr(&_BT_L2_MEMB(a
, bdaddr
));
992 PyObject
*ret
= NULL
;
994 ret
= Py_BuildValue("Oi",
996 _BT_L2_MEMB(a
, psm
));
1002 case BTPROTO_RFCOMM
:
1004 struct sockaddr_rc
*a
= (struct sockaddr_rc
*) addr
;
1005 PyObject
*addrobj
= makebdaddr(&_BT_RC_MEMB(a
, bdaddr
));
1006 PyObject
*ret
= NULL
;
1008 ret
= Py_BuildValue("Oi",
1010 _BT_RC_MEMB(a
, channel
));
1016 #if !defined(__FreeBSD__)
1019 struct sockaddr_sco
*a
= (struct sockaddr_sco
*) addr
;
1020 return makebdaddr(&_BT_SCO_MEMB(a
, bdaddr
));
1027 #ifdef HAVE_NETPACKET_PACKET_H
1030 struct sockaddr_ll
*a
= (struct sockaddr_ll
*)addr
;
1033 /* need to look up interface name give index */
1034 if (a
->sll_ifindex
) {
1035 ifr
.ifr_ifindex
= a
->sll_ifindex
;
1036 if (ioctl(sockfd
, SIOCGIFNAME
, &ifr
) == 0)
1037 ifname
= ifr
.ifr_name
;
1039 return Py_BuildValue("shbhs#",
1041 ntohs(a
->sll_protocol
),
1049 /* More cases here... */
1052 /* If we don't know the address family, don't raise an
1053 exception -- return it as a tuple. */
1054 return Py_BuildValue("is#",
1057 sizeof(addr
->sa_data
));
1063 /* Parse a socket address argument according to the socket object's
1064 address family. Return 1 if the address was in the proper format,
1065 0 of not. The address is returned through addr_ret, its length
1069 getsockaddrarg(PySocketSockObject
*s
, PyObject
*args
,
1070 struct sockaddr
**addr_ret
, int *len_ret
)
1072 switch (s
->sock_family
) {
1074 #if defined(AF_UNIX)
1077 struct sockaddr_un
* addr
;
1080 addr
= (struct sockaddr_un
*)&(s
->sock_addr
).un
;
1081 if (!PyArg_Parse(args
, "t#", &path
, &len
))
1083 if (len
> sizeof addr
->sun_path
) {
1084 PyErr_SetString(socket_error
,
1085 "AF_UNIX path too long");
1088 addr
->sun_family
= s
->sock_family
;
1089 memcpy(addr
->sun_path
, path
, len
);
1090 addr
->sun_path
[len
] = 0;
1091 *addr_ret
= (struct sockaddr
*) addr
;
1092 #if defined(PYOS_OS2)
1093 *len_ret
= sizeof(*addr
);
1095 *len_ret
= len
+ sizeof(*addr
) - sizeof(addr
->sun_path
);
1099 #endif /* AF_UNIX */
1101 #if defined(AF_NETLINK)
1104 struct sockaddr_nl
* addr
;
1106 addr
= (struct sockaddr_nl
*)&(s
->sock_addr
).nl
;
1107 if (!PyTuple_Check(args
)) {
1111 "AF_NETLINK address must be tuple, not %.500s",
1112 args
->ob_type
->tp_name
);
1115 if (!PyArg_ParseTuple(args
, "II:getsockaddrarg", &pid
, &groups
))
1117 addr
->nl_family
= AF_NETLINK
;
1119 addr
->nl_groups
= groups
;
1120 *addr_ret
= (struct sockaddr
*) addr
;
1121 *len_ret
= sizeof(*addr
);
1128 struct sockaddr_in
* addr
;
1131 addr
=(struct sockaddr_in
*)&(s
->sock_addr
).in
;
1132 if (!PyTuple_Check(args
)) {
1136 "AF_INET address must be tuple, not %.500s",
1137 args
->ob_type
->tp_name
);
1140 if (!PyArg_ParseTuple(args
, "eti:getsockaddrarg",
1141 "idna", &host
, &port
))
1143 result
= setipaddr(host
, (struct sockaddr
*)addr
,
1144 sizeof(*addr
), AF_INET
);
1148 addr
->sin_family
= AF_INET
;
1149 addr
->sin_port
= htons((short)port
);
1150 *addr_ret
= (struct sockaddr
*) addr
;
1151 *len_ret
= sizeof *addr
;
1158 struct sockaddr_in6
* addr
;
1160 int port
, flowinfo
, scope_id
, result
;
1161 addr
= (struct sockaddr_in6
*)&(s
->sock_addr
).in6
;
1162 flowinfo
= scope_id
= 0;
1163 if (!PyArg_ParseTuple(args
, "eti|ii",
1164 "idna", &host
, &port
, &flowinfo
,
1168 result
= setipaddr(host
, (struct sockaddr
*)addr
,
1169 sizeof(*addr
), AF_INET6
);
1173 addr
->sin6_family
= s
->sock_family
;
1174 addr
->sin6_port
= htons((short)port
);
1175 addr
->sin6_flowinfo
= flowinfo
;
1176 addr
->sin6_scope_id
= scope_id
;
1177 *addr_ret
= (struct sockaddr
*) addr
;
1178 *len_ret
= sizeof *addr
;
1183 #ifdef USE_BLUETOOTH
1186 switch (s
->sock_proto
) {
1189 struct sockaddr_l2
*addr
= (struct sockaddr_l2
*) _BT_SOCKADDR_MEMB(s
, l2
);
1192 _BT_L2_MEMB(addr
, family
) = AF_BLUETOOTH
;
1193 if (!PyArg_ParseTuple(args
, "si", &straddr
,
1194 &_BT_L2_MEMB(addr
, psm
))) {
1195 PyErr_SetString(socket_error
, "getsockaddrarg: "
1199 if (setbdaddr(straddr
, &_BT_L2_MEMB(addr
, bdaddr
)) < 0)
1202 *addr_ret
= (struct sockaddr
*) addr
;
1203 *len_ret
= sizeof *addr
;
1206 case BTPROTO_RFCOMM
:
1208 struct sockaddr_rc
*addr
= (struct sockaddr_rc
*) _BT_SOCKADDR_MEMB(s
, rc
);
1211 _BT_RC_MEMB(addr
, family
) = AF_BLUETOOTH
;
1212 if (!PyArg_ParseTuple(args
, "si", &straddr
,
1213 &_BT_RC_MEMB(addr
, channel
))) {
1214 PyErr_SetString(socket_error
, "getsockaddrarg: "
1218 if (setbdaddr(straddr
, &_BT_RC_MEMB(addr
, bdaddr
)) < 0)
1221 *addr_ret
= (struct sockaddr
*) addr
;
1222 *len_ret
= sizeof *addr
;
1225 #if !defined(__FreeBSD__)
1228 struct sockaddr_sco
*addr
= (struct sockaddr_sco
*) _BT_SOCKADDR_MEMB(s
, sco
);
1231 _BT_SCO_MEMB(addr
, family
) = AF_BLUETOOTH
;
1232 straddr
= PyString_AsString(args
);
1233 if (straddr
== NULL
) {
1234 PyErr_SetString(socket_error
, "getsockaddrarg: "
1238 if (setbdaddr(straddr
, &_BT_SCO_MEMB(addr
, bdaddr
)) < 0)
1241 *addr_ret
= (struct sockaddr
*) addr
;
1242 *len_ret
= sizeof *addr
;
1247 PyErr_SetString(socket_error
, "getsockaddrarg: unknown Bluetooth protocol");
1253 #ifdef HAVE_NETPACKET_PACKET_H
1256 struct sockaddr_ll
* addr
;
1258 char *interfaceName
;
1263 unsigned int halen
= 0;
1265 if (!PyArg_ParseTuple(args
, "si|iis#", &interfaceName
,
1266 &protoNumber
, &pkttype
, &hatype
,
1269 strncpy(ifr
.ifr_name
, interfaceName
, sizeof(ifr
.ifr_name
));
1270 ifr
.ifr_name
[(sizeof(ifr
.ifr_name
))-1] = '\0';
1271 if (ioctl(s
->sock_fd
, SIOCGIFINDEX
, &ifr
) < 0) {
1275 addr
= &(s
->sock_addr
.ll
);
1276 addr
->sll_family
= AF_PACKET
;
1277 addr
->sll_protocol
= htons((short)protoNumber
);
1278 addr
->sll_ifindex
= ifr
.ifr_ifindex
;
1279 addr
->sll_pkttype
= pkttype
;
1280 addr
->sll_hatype
= hatype
;
1282 PyErr_SetString(PyExc_ValueError
,
1283 "Hardware address must be 8 bytes or less");
1287 memcpy(&addr
->sll_addr
, haddr
, halen
);
1289 addr
->sll_halen
= halen
;
1290 *addr_ret
= (struct sockaddr
*) addr
;
1291 *len_ret
= sizeof *addr
;
1296 /* More cases here... */
1299 PyErr_SetString(socket_error
, "getsockaddrarg: bad family");
1306 /* Get the address length according to the socket object's address family.
1307 Return 1 if the family is known, 0 otherwise. The length is returned
1311 getsockaddrlen(PySocketSockObject
*s
, socklen_t
*len_ret
)
1313 switch (s
->sock_family
) {
1315 #if defined(AF_UNIX)
1318 *len_ret
= sizeof (struct sockaddr_un
);
1321 #endif /* AF_UNIX */
1322 #if defined(AF_NETLINK)
1325 *len_ret
= sizeof (struct sockaddr_nl
);
1332 *len_ret
= sizeof (struct sockaddr_in
);
1339 *len_ret
= sizeof (struct sockaddr_in6
);
1344 #ifdef USE_BLUETOOTH
1347 switch(s
->sock_proto
)
1351 *len_ret
= sizeof (struct sockaddr_l2
);
1353 case BTPROTO_RFCOMM
:
1354 *len_ret
= sizeof (struct sockaddr_rc
);
1356 #if !defined(__FreeBSD__)
1358 *len_ret
= sizeof (struct sockaddr_sco
);
1362 PyErr_SetString(socket_error
, "getsockaddrlen: "
1363 "unknown BT protocol");
1370 #ifdef HAVE_NETPACKET_PACKET_H
1373 *len_ret
= sizeof (struct sockaddr_ll
);
1378 /* More cases here... */
1381 PyErr_SetString(socket_error
, "getsockaddrlen: bad family");
1388 /* s.accept() method */
1391 sock_accept(PySocketSockObject
*s
)
1393 sock_addr_t addrbuf
;
1396 PyObject
*sock
= NULL
;
1397 PyObject
*addr
= NULL
;
1398 PyObject
*res
= NULL
;
1401 if (!getsockaddrlen(s
, &addrlen
))
1403 memset(&addrbuf
, 0, addrlen
);
1406 newfd
= INVALID_SOCKET
;
1411 Py_BEGIN_ALLOW_THREADS
1412 timeout
= internal_select(s
, 0);
1414 newfd
= accept(s
->sock_fd
, (struct sockaddr
*) &addrbuf
,
1416 Py_END_ALLOW_THREADS
1419 PyErr_SetString(socket_timeout
, "timed out");
1424 if (newfd
== INVALID_SOCKET
)
1428 return s
->errorhandler();
1430 /* Create the new object with unspecified family,
1431 to avoid calls to bind() etc. on it. */
1432 sock
= (PyObject
*) new_sockobject(newfd
,
1441 addr
= makesockaddr(s
->sock_fd
, (struct sockaddr
*) &addrbuf
,
1442 addrlen
, s
->sock_proto
);
1446 res
= PyTuple_Pack(2, sock
, addr
);
1454 PyDoc_STRVAR(accept_doc
,
1455 "accept() -> (socket object, address info)\n\
1457 Wait for an incoming connection. Return a new socket representing the\n\
1458 connection, and the address of the client. For IP sockets, the address\n\
1459 info is a pair (hostaddr, port).");
1461 /* s.setblocking(flag) method. Argument:
1462 False -- non-blocking mode; same as settimeout(0)
1463 True -- blocking mode; same as settimeout(None)
1467 sock_setblocking(PySocketSockObject
*s
, PyObject
*arg
)
1471 block
= PyInt_AsLong(arg
);
1472 if (block
== -1 && PyErr_Occurred())
1475 s
->sock_timeout
= block
? -1.0 : 0.0;
1476 internal_setblocking(s
, block
);
1482 PyDoc_STRVAR(setblocking_doc
,
1483 "setblocking(flag)\n\
1485 Set the socket to blocking (flag is true) or non-blocking (false).\n\
1486 setblocking(True) is equivalent to settimeout(None);\n\
1487 setblocking(False) is equivalent to settimeout(0.0).");
1489 /* s.settimeout(timeout) method. Argument:
1490 None -- no timeout, blocking mode; same as setblocking(True)
1491 0.0 -- non-blocking mode; same as setblocking(False)
1492 > 0 -- timeout mode; operations time out after timeout seconds
1493 < 0 -- illegal; raises an exception
1496 sock_settimeout(PySocketSockObject
*s
, PyObject
*arg
)
1503 timeout
= PyFloat_AsDouble(arg
);
1504 if (timeout
< 0.0) {
1505 if (!PyErr_Occurred())
1506 PyErr_SetString(PyExc_ValueError
,
1507 "Timeout value out of range");
1512 s
->sock_timeout
= timeout
;
1513 internal_setblocking(s
, timeout
< 0.0);
1519 PyDoc_STRVAR(settimeout_doc
,
1520 "settimeout(timeout)\n\
1522 Set a timeout on socket operations. 'timeout' can be a float,\n\
1523 giving in seconds, or None. Setting a timeout of None disables\n\
1524 the timeout feature and is equivalent to setblocking(1).\n\
1525 Setting a timeout of zero is the same as setblocking(0).");
1527 /* s.gettimeout() method.
1528 Returns the timeout associated with a socket. */
1530 sock_gettimeout(PySocketSockObject
*s
)
1532 if (s
->sock_timeout
< 0.0) {
1537 return PyFloat_FromDouble(s
->sock_timeout
);
1540 PyDoc_STRVAR(gettimeout_doc
,
1541 "gettimeout() -> timeout\n\
1543 Returns the timeout in floating seconds associated with socket \n\
1544 operations. A timeout of None indicates that timeouts on socket \n\
1545 operations are disabled.");
1548 /* s.sleeptaskw(1 | 0) method */
1551 sock_sleeptaskw(PySocketSockObject
*s
,PyObject
*arg
)
1554 block
= PyInt_AsLong(arg
);
1555 if (block
== -1 && PyErr_Occurred())
1557 Py_BEGIN_ALLOW_THREADS
1558 socketioctl(s
->sock_fd
, 0x80046679, (u_long
*)&block
);
1559 Py_END_ALLOW_THREADS
1564 PyDoc_STRVAR(sleeptaskw_doc
,
1565 "sleeptaskw(flag)\n\
1567 Allow sleeps in taskwindows.");
1571 /* s.setsockopt() method.
1572 With an integer third argument, sets an integer option.
1573 With a string third argument, sets an option from a buffer;
1574 use optional built-in module 'struct' to encode the string. */
1577 sock_setsockopt(PySocketSockObject
*s
, PyObject
*args
)
1586 if (PyArg_ParseTuple(args
, "iii:setsockopt",
1587 &level
, &optname
, &flag
)) {
1588 buf
= (char *) &flag
;
1589 buflen
= sizeof flag
;
1593 if (!PyArg_ParseTuple(args
, "iis#:setsockopt",
1594 &level
, &optname
, &buf
, &buflen
))
1597 res
= setsockopt(s
->sock_fd
, level
, optname
, (void *)buf
, buflen
);
1599 return s
->errorhandler();
1604 PyDoc_STRVAR(setsockopt_doc
,
1605 "setsockopt(level, option, value)\n\
1607 Set a socket option. See the Unix manual for level and option.\n\
1608 The value argument can either be an integer or a string.");
1611 /* s.getsockopt() method.
1612 With two arguments, retrieves an integer option.
1613 With a third integer argument, retrieves a string buffer of that size;
1614 use optional built-in module 'struct' to decode the string. */
1617 sock_getsockopt(PySocketSockObject
*s
, PyObject
*args
)
1623 socklen_t buflen
= 0;
1626 /* We have incomplete socket support. */
1627 PyErr_SetString(socket_error
, "getsockopt not supported");
1631 if (!PyArg_ParseTuple(args
, "ii|i:getsockopt",
1632 &level
, &optname
, &buflen
))
1637 socklen_t flagsize
= sizeof flag
;
1638 res
= getsockopt(s
->sock_fd
, level
, optname
,
1639 (void *)&flag
, &flagsize
);
1641 return s
->errorhandler();
1642 return PyInt_FromLong(flag
);
1645 if (buflen
> 1024) {
1647 if (buflen
<= 0 || buflen
> 1024) {
1649 PyErr_SetString(socket_error
,
1650 "getsockopt buflen out of range");
1653 buf
= PyString_FromStringAndSize((char *)NULL
, buflen
);
1656 res
= getsockopt(s
->sock_fd
, level
, optname
,
1657 (void *)PyString_AS_STRING(buf
), &buflen
);
1660 return s
->errorhandler();
1662 _PyString_Resize(&buf
, buflen
);
1664 #endif /* __BEOS__ */
1667 PyDoc_STRVAR(getsockopt_doc
,
1668 "getsockopt(level, option[, buffersize]) -> value\n\
1670 Get a socket option. See the Unix manual for level and option.\n\
1671 If a nonzero buffersize argument is given, the return value is a\n\
1672 string of that length; otherwise it is an integer.");
1675 /* s.bind(sockaddr) method */
1678 sock_bind(PySocketSockObject
*s
, PyObject
*addro
)
1680 struct sockaddr
*addr
;
1684 if (!getsockaddrarg(s
, addro
, &addr
, &addrlen
))
1686 Py_BEGIN_ALLOW_THREADS
1687 res
= bind(s
->sock_fd
, addr
, addrlen
);
1688 Py_END_ALLOW_THREADS
1690 return s
->errorhandler();
1695 PyDoc_STRVAR(bind_doc
,
1698 Bind the socket to a local address. For IP sockets, the address is a\n\
1699 pair (host, port); the host must refer to the local host. For raw packet\n\
1700 sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");
1703 /* s.close() method.
1704 Set the file descriptor to -1 so operations tried subsequently
1705 will surely fail. */
1708 sock_close(PySocketSockObject
*s
)
1712 if ((fd
= s
->sock_fd
) != -1) {
1714 Py_BEGIN_ALLOW_THREADS
1715 (void) SOCKETCLOSE(fd
);
1716 Py_END_ALLOW_THREADS
1722 PyDoc_STRVAR(close_doc
,
1725 Close the socket. It cannot be used after this call.");
1728 internal_connect(PySocketSockObject
*s
, struct sockaddr
*addr
, int addrlen
,
1734 res
= connect(s
->sock_fd
, addr
, addrlen
);
1738 if (s
->sock_timeout
> 0.0) {
1739 if (res
< 0 && WSAGetLastError() == WSAEWOULDBLOCK
) {
1740 /* This is a mess. Best solution: trust select */
1744 tv
.tv_sec
= (int)s
->sock_timeout
;
1745 tv
.tv_usec
= (int)((s
->sock_timeout
- tv
.tv_sec
) * 1e6
);
1747 FD_SET(s
->sock_fd
, &fds
);
1749 FD_SET(s
->sock_fd
, &fds_exc
);
1750 res
= select(s
->sock_fd
+1, NULL
, &fds
, &fds_exc
, &tv
);
1752 res
= WSAEWOULDBLOCK
;
1754 } else if (res
> 0) {
1755 if (FD_ISSET(s
->sock_fd
, &fds
))
1756 /* The socket is in the writeable set - this
1760 /* As per MS docs, we need to call getsockopt()
1761 to get the underlying error */
1762 int res_size
= sizeof res
;
1763 /* It must be in the exception set */
1764 assert(FD_ISSET(s
->sock_fd
, &fds_exc
));
1765 if (0 == getsockopt(s
->sock_fd
, SOL_SOCKET
, SO_ERROR
,
1766 (char *)&res
, &res_size
))
1767 /* getsockopt also clears WSAGetLastError,
1768 so reset it back. */
1769 WSASetLastError(res
);
1771 res
= WSAGetLastError();
1774 /* else if (res < 0) an error occurred */
1779 res
= WSAGetLastError();
1783 if (s
->sock_timeout
> 0.0) {
1784 if (res
< 0 && errno
== EINPROGRESS
) {
1785 timeout
= internal_select(s
, 1);
1786 res
= connect(s
->sock_fd
, addr
, addrlen
);
1787 if (res
< 0 && errno
== EISCONN
)
1796 *timeoutp
= timeout
;
1801 /* s.connect(sockaddr) method */
1804 sock_connect(PySocketSockObject
*s
, PyObject
*addro
)
1806 struct sockaddr
*addr
;
1811 if (!getsockaddrarg(s
, addro
, &addr
, &addrlen
))
1814 Py_BEGIN_ALLOW_THREADS
1815 res
= internal_connect(s
, addr
, addrlen
, &timeout
);
1816 Py_END_ALLOW_THREADS
1819 PyErr_SetString(socket_timeout
, "timed out");
1823 return s
->errorhandler();
1828 PyDoc_STRVAR(connect_doc
,
1829 "connect(address)\n\
1831 Connect the socket to a remote address. For IP sockets, the address\n\
1832 is a pair (host, port).");
1835 /* s.connect_ex(sockaddr) method */
1838 sock_connect_ex(PySocketSockObject
*s
, PyObject
*addro
)
1840 struct sockaddr
*addr
;
1845 if (!getsockaddrarg(s
, addro
, &addr
, &addrlen
))
1848 Py_BEGIN_ALLOW_THREADS
1849 res
= internal_connect(s
, addr
, addrlen
, &timeout
);
1850 Py_END_ALLOW_THREADS
1852 return PyInt_FromLong((long) res
);
1855 PyDoc_STRVAR(connect_ex_doc
,
1856 "connect_ex(address) -> errno\n\
1858 This is like connect(address), but returns an error code (the errno value)\n\
1859 instead of raising an exception when an error occurs.");
1862 /* s.fileno() method */
1865 sock_fileno(PySocketSockObject
*s
)
1867 #if SIZEOF_SOCKET_T <= SIZEOF_LONG
1868 return PyInt_FromLong((long) s
->sock_fd
);
1870 return PyLong_FromLongLong((PY_LONG_LONG
)s
->sock_fd
);
1874 PyDoc_STRVAR(fileno_doc
,
1875 "fileno() -> integer\n\
1877 Return the integer file descriptor of the socket.");
1881 /* s.dup() method */
1884 sock_dup(PySocketSockObject
*s
)
1889 newfd
= dup(s
->sock_fd
);
1891 return s
->errorhandler();
1892 sock
= (PyObject
*) new_sockobject(newfd
,
1901 PyDoc_STRVAR(dup_doc
,
1902 "dup() -> socket object\n\
1904 Return a new socket object connected to the same system resource.");
1909 /* s.getsockname() method */
1912 sock_getsockname(PySocketSockObject
*s
)
1914 sock_addr_t addrbuf
;
1918 if (!getsockaddrlen(s
, &addrlen
))
1920 memset(&addrbuf
, 0, addrlen
);
1921 Py_BEGIN_ALLOW_THREADS
1922 res
= getsockname(s
->sock_fd
, (struct sockaddr
*) &addrbuf
, &addrlen
);
1923 Py_END_ALLOW_THREADS
1925 return s
->errorhandler();
1926 return makesockaddr(s
->sock_fd
, (struct sockaddr
*) &addrbuf
, addrlen
,
1930 PyDoc_STRVAR(getsockname_doc
,
1931 "getsockname() -> address info\n\
1933 Return the address of the local endpoint. For IP sockets, the address\n\
1934 info is a pair (hostaddr, port).");
1937 #ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
1938 /* s.getpeername() method */
1941 sock_getpeername(PySocketSockObject
*s
)
1943 sock_addr_t addrbuf
;
1947 if (!getsockaddrlen(s
, &addrlen
))
1949 memset(&addrbuf
, 0, addrlen
);
1950 Py_BEGIN_ALLOW_THREADS
1951 res
= getpeername(s
->sock_fd
, (struct sockaddr
*) &addrbuf
, &addrlen
);
1952 Py_END_ALLOW_THREADS
1954 return s
->errorhandler();
1955 return makesockaddr(s
->sock_fd
, (struct sockaddr
*) &addrbuf
, addrlen
,
1959 PyDoc_STRVAR(getpeername_doc
,
1960 "getpeername() -> address info\n\
1962 Return the address of the remote endpoint. For IP sockets, the address\n\
1963 info is a pair (hostaddr, port).");
1965 #endif /* HAVE_GETPEERNAME */
1968 /* s.listen(n) method */
1971 sock_listen(PySocketSockObject
*s
, PyObject
*arg
)
1976 backlog
= PyInt_AsLong(arg
);
1977 if (backlog
== -1 && PyErr_Occurred())
1979 Py_BEGIN_ALLOW_THREADS
1982 res
= listen(s
->sock_fd
, backlog
);
1983 Py_END_ALLOW_THREADS
1985 return s
->errorhandler();
1990 PyDoc_STRVAR(listen_doc
,
1993 Enable a server to accept connections. The backlog argument must be at\n\
1994 least 1; it specifies the number of unaccepted connection that the system\n\
1995 will allow before refusing new connections.");
1999 /* s.makefile(mode) method.
2000 Create a new open file object referring to a dupped version of
2001 the socket's file descriptor. (The dup() call is necessary so
2002 that the open file and socket objects may be closed independent
2004 The mode argument specifies 'r' or 'w' passed to fdopen(). */
2007 sock_makefile(PySocketSockObject
*s
, PyObject
*args
)
2009 extern int fclose(FILE *);
2024 if (!PyArg_ParseTuple(args
, "|si:makefile", &mode
, &bufsize
))
2027 if (strcmp(mode
,"rb") == 0) {
2031 if (strcmp(mode
,"wb") == 0) {
2037 if (((fd
= _open_osfhandle(s
->sock_fd
, _O_BINARY
)) < 0) ||
2038 ((fd
= dup(fd
)) < 0) || ((fp
= fdopen(fd
, mode
)) == NULL
))
2040 if ((fd
= dup(s
->sock_fd
)) < 0 || (fp
= fdopen(fd
, mode
)) == NULL
)
2045 return s
->errorhandler();
2047 f
= PyFile_FromFile(fp
, "<socket>", mode
, fclose
);
2049 PyFile_SetBufSize(f
, bufsize
);
2053 PyDoc_STRVAR(makefile_doc
,
2054 "makefile([mode[, buffersize]]) -> file object\n\
2056 Return a regular file object corresponding to the socket.\n\
2057 The mode and buffersize arguments are as for the built-in open() function.");
2062 /* s.recv(nbytes [,flags]) method */
2065 sock_recv(PySocketSockObject
*s
, PyObject
*args
)
2067 int len
, n
= 0, flags
= 0, timeout
;
2074 if (!PyArg_ParseTuple(args
, "i|i:recv", &len
, &flags
))
2078 PyErr_SetString(PyExc_ValueError
,
2079 "negative buffersize in recv");
2083 buf
= PyString_FromStringAndSize((char *) 0, len
);
2088 Py_BEGIN_ALLOW_THREADS
2089 timeout
= internal_select(s
, 0);
2091 n
= recv(s
->sock_fd
, PyString_AS_STRING(buf
), len
, flags
);
2092 Py_END_ALLOW_THREADS
2096 PyErr_SetString(socket_timeout
, "timed out");
2101 return s
->errorhandler();
2104 _PyString_Resize(&buf
, n
);
2106 read_buf
= PyString_AsString(buf
);
2108 while (read_length
!= 0) {
2109 unsigned int segment
;
2111 segment
= read_length
/SEGMENT_SIZE
;
2113 segment
= SEGMENT_SIZE
;
2116 segment
= read_length
;
2119 Py_BEGIN_ALLOW_THREADS
2120 timeout
= internal_select(s
, 0);
2122 n
= recv(s
->sock_fd
, read_buf
, segment
, flags
);
2123 Py_END_ALLOW_THREADS
2127 PyErr_SetString(socket_timeout
, "timed out");
2132 return s
->errorhandler();
2134 if (n
!= read_length
) {
2139 read_length
-= segment
;
2140 read_buf
+= segment
;
2142 if (_PyString_Resize(&buf
, (read_buf
- PyString_AsString(buf
))) < 0)
2150 PyDoc_STRVAR(recv_doc
,
2151 "recv(buffersize[, flags]) -> data\n\
2153 Receive up to buffersize bytes from the socket. For the optional flags\n\
2154 argument, see the Unix manual. When no data is available, block until\n\
2155 at least one byte is available or until the remote end is closed. When\n\
2156 the remote end is closed and all data is read, return the empty string.");
2159 /* s.recvfrom(nbytes [,flags]) method */
2162 sock_recvfrom(PySocketSockObject
*s
, PyObject
*args
)
2164 sock_addr_t addrbuf
;
2165 PyObject
*buf
= NULL
;
2166 PyObject
*addr
= NULL
;
2167 PyObject
*ret
= NULL
;
2168 int len
, n
= 0, flags
= 0, timeout
;
2171 if (!PyArg_ParseTuple(args
, "i|i:recvfrom", &len
, &flags
))
2174 if (!getsockaddrlen(s
, &addrlen
))
2176 buf
= PyString_FromStringAndSize((char *) 0, len
);
2180 Py_BEGIN_ALLOW_THREADS
2181 memset(&addrbuf
, 0, addrlen
);
2182 timeout
= internal_select(s
, 0);
2184 n
= recvfrom(s
->sock_fd
, PyString_AS_STRING(buf
), len
, flags
,
2186 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
2187 (struct sockaddr
*) &addrbuf
, &addrlen
2189 (void *) &addrbuf
, &addrlen
2192 (struct sockaddr
*) &addrbuf
, &addrlen
2195 Py_END_ALLOW_THREADS
2199 PyErr_SetString(socket_timeout
, "timed out");
2204 return s
->errorhandler();
2207 if (n
!= len
&& _PyString_Resize(&buf
, n
) < 0)
2210 if (!(addr
= makesockaddr(s
->sock_fd
, (struct sockaddr
*) &addrbuf
,
2211 addrlen
, s
->sock_proto
)))
2214 ret
= PyTuple_Pack(2, buf
, addr
);
2222 PyDoc_STRVAR(recvfrom_doc
,
2223 "recvfrom(buffersize[, flags]) -> (data, address info)\n\
2225 Like recv(buffersize, flags) but also return the sender's address info.");
2227 /* s.send(data [,flags]) method */
2230 sock_send(PySocketSockObject
*s
, PyObject
*args
)
2233 int len
, n
= 0, flags
= 0, timeout
;
2238 if (!PyArg_ParseTuple(args
, "s#|i:send", &buf
, &len
, &flags
))
2242 Py_BEGIN_ALLOW_THREADS
2243 timeout
= internal_select(s
, 1);
2245 n
= send(s
->sock_fd
, buf
, len
, flags
);
2246 Py_END_ALLOW_THREADS
2249 PyErr_SetString(socket_timeout
, "timed out");
2253 return s
->errorhandler();
2255 /* Divide packet into smaller segments for */
2256 /* TCP/IP Services for OpenVMS */
2258 while (send_length
!= 0) {
2259 unsigned int segment
;
2261 segment
= send_length
/ SEGMENT_SIZE
;
2263 segment
= SEGMENT_SIZE
;
2266 segment
= send_length
;
2268 Py_BEGIN_ALLOW_THREADS
2269 timeout
= internal_select(s
, 1);
2271 n
= send(s
->sock_fd
, buf
, segment
, flags
);
2272 Py_END_ALLOW_THREADS
2274 PyErr_SetString(socket_timeout
, "timed out");
2278 return s
->errorhandler();
2280 send_length
-= segment
;
2284 return PyInt_FromLong((long)n
);
2287 PyDoc_STRVAR(send_doc
,
2288 "send(data[, flags]) -> count\n\
2290 Send a data string to the socket. For the optional flags\n\
2291 argument, see the Unix manual. Return the number of bytes\n\
2292 sent; this may be less than len(data) if the network is busy.");
2295 /* s.sendall(data [,flags]) method */
2298 sock_sendall(PySocketSockObject
*s
, PyObject
*args
)
2301 int len
, n
= 0, flags
= 0, timeout
;
2303 if (!PyArg_ParseTuple(args
, "s#|i:sendall", &buf
, &len
, &flags
))
2306 Py_BEGIN_ALLOW_THREADS
2308 timeout
= internal_select(s
, 1);
2311 n
= send(s
->sock_fd
, buf
, len
, flags
);
2317 Py_END_ALLOW_THREADS
2320 PyErr_SetString(socket_timeout
, "timed out");
2324 return s
->errorhandler();
2330 PyDoc_STRVAR(sendall_doc
,
2331 "sendall(data[, flags])\n\
2333 Send a data string to the socket. For the optional flags\n\
2334 argument, see the Unix manual. This calls send() repeatedly\n\
2335 until all data is sent. If an error occurs, it's impossible\n\
2336 to tell how much data has been sent.");
2339 /* s.sendto(data, [flags,] sockaddr) method */
2342 sock_sendto(PySocketSockObject
*s
, PyObject
*args
)
2346 struct sockaddr
*addr
;
2347 int addrlen
, len
, n
= 0, flags
, timeout
;
2350 if (!PyArg_ParseTuple(args
, "s#O:sendto", &buf
, &len
, &addro
)) {
2352 if (!PyArg_ParseTuple(args
, "s#iO:sendto",
2353 &buf
, &len
, &flags
, &addro
))
2357 if (!getsockaddrarg(s
, addro
, &addr
, &addrlen
))
2360 Py_BEGIN_ALLOW_THREADS
2361 timeout
= internal_select(s
, 1);
2363 n
= sendto(s
->sock_fd
, buf
, len
, flags
, addr
, addrlen
);
2364 Py_END_ALLOW_THREADS
2367 PyErr_SetString(socket_timeout
, "timed out");
2371 return s
->errorhandler();
2372 return PyInt_FromLong((long)n
);
2375 PyDoc_STRVAR(sendto_doc
,
2376 "sendto(data[, flags], address) -> count\n\
2378 Like send(data, flags) but allows specifying the destination address.\n\
2379 For IP sockets, the address is a pair (hostaddr, port).");
2382 /* s.shutdown(how) method */
2385 sock_shutdown(PySocketSockObject
*s
, PyObject
*arg
)
2390 how
= PyInt_AsLong(arg
);
2391 if (how
== -1 && PyErr_Occurred())
2393 Py_BEGIN_ALLOW_THREADS
2394 res
= shutdown(s
->sock_fd
, how
);
2395 Py_END_ALLOW_THREADS
2397 return s
->errorhandler();
2402 PyDoc_STRVAR(shutdown_doc
,
2405 Shut down the reading side of the socket (flag == SHUT_RD), the writing side\n\
2406 of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).");
2409 /* List of methods for socket objects */
2411 static PyMethodDef sock_methods
[] = {
2412 {"accept", (PyCFunction
)sock_accept
, METH_NOARGS
,
2414 {"bind", (PyCFunction
)sock_bind
, METH_O
,
2416 {"close", (PyCFunction
)sock_close
, METH_NOARGS
,
2418 {"connect", (PyCFunction
)sock_connect
, METH_O
,
2420 {"connect_ex", (PyCFunction
)sock_connect_ex
, METH_O
,
2423 {"dup", (PyCFunction
)sock_dup
, METH_NOARGS
,
2426 {"fileno", (PyCFunction
)sock_fileno
, METH_NOARGS
,
2428 #ifdef HAVE_GETPEERNAME
2429 {"getpeername", (PyCFunction
)sock_getpeername
,
2430 METH_NOARGS
, getpeername_doc
},
2432 {"getsockname", (PyCFunction
)sock_getsockname
,
2433 METH_NOARGS
, getsockname_doc
},
2434 {"getsockopt", (PyCFunction
)sock_getsockopt
, METH_VARARGS
,
2436 {"listen", (PyCFunction
)sock_listen
, METH_O
,
2439 {"makefile", (PyCFunction
)sock_makefile
, METH_VARARGS
,
2442 {"recv", (PyCFunction
)sock_recv
, METH_VARARGS
,
2444 {"recvfrom", (PyCFunction
)sock_recvfrom
, METH_VARARGS
,
2446 {"send", (PyCFunction
)sock_send
, METH_VARARGS
,
2448 {"sendall", (PyCFunction
)sock_sendall
, METH_VARARGS
,
2450 {"sendto", (PyCFunction
)sock_sendto
, METH_VARARGS
,
2452 {"setblocking", (PyCFunction
)sock_setblocking
, METH_O
,
2454 {"settimeout", (PyCFunction
)sock_settimeout
, METH_O
,
2456 {"gettimeout", (PyCFunction
)sock_gettimeout
, METH_NOARGS
,
2458 {"setsockopt", (PyCFunction
)sock_setsockopt
, METH_VARARGS
,
2460 {"shutdown", (PyCFunction
)sock_shutdown
, METH_O
,
2463 {"sleeptaskw", (PyCFunction
)sock_sleeptaskw
, METH_O
,
2466 {NULL
, NULL
} /* sentinel */
2470 /* Deallocate a socket object in response to the last Py_DECREF().
2471 First close the file description. */
2474 sock_dealloc(PySocketSockObject
*s
)
2476 if (s
->sock_fd
!= -1)
2477 (void) SOCKETCLOSE(s
->sock_fd
);
2478 s
->ob_type
->tp_free((PyObject
*)s
);
2483 sock_repr(PySocketSockObject
*s
)
2486 #if SIZEOF_SOCKET_T > SIZEOF_LONG
2487 if (s
->sock_fd
> LONG_MAX
) {
2488 /* this can occur on Win64, and actually there is a special
2489 ugly printf formatter for decimal pointer length integer
2490 printing, only bother if necessary*/
2491 PyErr_SetString(PyExc_OverflowError
,
2492 "no printf formatter to display "
2493 "the socket descriptor in decimal");
2499 "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
2500 (long)s
->sock_fd
, s
->sock_family
,
2503 return PyString_FromString(buf
);
2507 /* Create a new, uninitialized socket object. */
2510 sock_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
2514 new = type
->tp_alloc(type
, 0);
2516 ((PySocketSockObject
*)new)->sock_fd
= -1;
2517 ((PySocketSockObject
*)new)->sock_timeout
= -1.0;
2518 ((PySocketSockObject
*)new)->errorhandler
= &set_error
;
2524 /* Initialize a new socket object. */
2528 sock_initobj(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
2530 PySocketSockObject
*s
= (PySocketSockObject
*)self
;
2532 int family
= AF_INET
, type
= SOCK_STREAM
, proto
= 0;
2533 static const char *keywords
[] = {"family", "type", "proto", 0};
2535 if (!PyArg_ParseTupleAndKeywords(args
, kwds
,
2536 "|iii:socket", keywords
,
2537 &family
, &type
, &proto
))
2540 Py_BEGIN_ALLOW_THREADS
2541 fd
= socket(family
, type
, proto
);
2542 Py_END_ALLOW_THREADS
2545 if (fd
== INVALID_SOCKET
)
2553 init_sockobject(s
, fd
, family
, type
, proto
);
2560 /* Type object for socket objects. */
2562 static PyTypeObject sock_type
= {
2563 PyObject_HEAD_INIT(0) /* Must fill in type value later */
2565 "_socket.socket", /* tp_name */
2566 sizeof(PySocketSockObject
), /* tp_basicsize */
2567 0, /* tp_itemsize */
2568 (destructor
)sock_dealloc
, /* tp_dealloc */
2573 (reprfunc
)sock_repr
, /* tp_repr */
2574 0, /* tp_as_number */
2575 0, /* tp_as_sequence */
2576 0, /* tp_as_mapping */
2580 PyObject_GenericGetAttr
, /* tp_getattro */
2581 0, /* tp_setattro */
2582 0, /* tp_as_buffer */
2583 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
2584 sock_doc
, /* tp_doc */
2585 0, /* tp_traverse */
2587 0, /* tp_richcompare */
2588 0, /* tp_weaklistoffset */
2590 0, /* tp_iternext */
2591 sock_methods
, /* tp_methods */
2596 0, /* tp_descr_get */
2597 0, /* tp_descr_set */
2598 0, /* tp_dictoffset */
2599 sock_initobj
, /* tp_init */
2600 PyType_GenericAlloc
, /* tp_alloc */
2601 sock_new
, /* tp_new */
2602 PyObject_Del
, /* tp_free */
2606 /* Python interface to gethostname(). */
2610 socket_gethostname(PyObject
*self
, PyObject
*args
)
2614 if (!PyArg_ParseTuple(args
, ":gethostname"))
2616 Py_BEGIN_ALLOW_THREADS
2617 res
= gethostname(buf
, (int) sizeof buf
- 1);
2618 Py_END_ALLOW_THREADS
2621 buf
[sizeof buf
- 1] = '\0';
2622 return PyString_FromString(buf
);
2625 PyDoc_STRVAR(gethostname_doc
,
2626 "gethostname() -> string\n\
2628 Return the current host name.");
2631 /* Python interface to gethostbyname(name). */
2635 socket_gethostbyname(PyObject
*self
, PyObject
*args
)
2638 sock_addr_t addrbuf
;
2640 if (!PyArg_ParseTuple(args
, "s:gethostbyname", &name
))
2642 if (setipaddr(name
, (struct sockaddr
*)&addrbuf
, sizeof(addrbuf
), AF_INET
) < 0)
2644 return makeipaddr((struct sockaddr
*)&addrbuf
,
2645 sizeof(struct sockaddr_in
));
2648 PyDoc_STRVAR(gethostbyname_doc
,
2649 "gethostbyname(host) -> address\n\
2651 Return the IP address (a string of the form '255.255.255.255') for a host.");
2654 /* Convenience function common to gethostbyname_ex and gethostbyaddr */
2657 gethost_common(struct hostent
*h
, struct sockaddr
*addr
, int alen
, int af
)
2660 PyObject
*rtn_tuple
= (PyObject
*)NULL
;
2661 PyObject
*name_list
= (PyObject
*)NULL
;
2662 PyObject
*addr_list
= (PyObject
*)NULL
;
2666 /* Let's get real error message to return */
2668 set_herror(h_errno
);
2670 PyErr_SetString(socket_error
, "host not found");
2675 if (h
->h_addrtype
!= af
) {
2676 #ifdef HAVE_STRERROR
2677 /* Let's get real error message to return */
2678 PyErr_SetString(socket_error
,
2679 (char *)strerror(EAFNOSUPPORT
));
2683 "Address family not supported by protocol family");
2691 if (alen
< sizeof(struct sockaddr_in
))
2697 if (alen
< sizeof(struct sockaddr_in6
))
2704 if ((name_list
= PyList_New(0)) == NULL
)
2707 if ((addr_list
= PyList_New(0)) == NULL
)
2710 for (pch
= h
->h_aliases
; *pch
!= NULL
; pch
++) {
2712 tmp
= PyString_FromString(*pch
);
2716 status
= PyList_Append(name_list
, tmp
);
2723 for (pch
= h
->h_addr_list
; *pch
!= NULL
; pch
++) {
2730 struct sockaddr_in sin
;
2731 memset(&sin
, 0, sizeof(sin
));
2732 sin
.sin_family
= af
;
2733 #ifdef HAVE_SOCKADDR_SA_LEN
2734 sin
.sin_len
= sizeof(sin
);
2736 memcpy(&sin
.sin_addr
, *pch
, sizeof(sin
.sin_addr
));
2737 tmp
= makeipaddr((struct sockaddr
*)&sin
, sizeof(sin
));
2739 if (pch
== h
->h_addr_list
&& alen
>= sizeof(sin
))
2740 memcpy((char *) addr
, &sin
, sizeof(sin
));
2747 struct sockaddr_in6 sin6
;
2748 memset(&sin6
, 0, sizeof(sin6
));
2749 sin6
.sin6_family
= af
;
2750 #ifdef HAVE_SOCKADDR_SA_LEN
2751 sin6
.sin6_len
= sizeof(sin6
);
2753 memcpy(&sin6
.sin6_addr
, *pch
, sizeof(sin6
.sin6_addr
));
2754 tmp
= makeipaddr((struct sockaddr
*)&sin6
,
2757 if (pch
== h
->h_addr_list
&& alen
>= sizeof(sin6
))
2758 memcpy((char *) addr
, &sin6
, sizeof(sin6
));
2763 default: /* can't happen */
2764 PyErr_SetString(socket_error
,
2765 "unsupported address family");
2772 status
= PyList_Append(addr_list
, tmp
);
2779 rtn_tuple
= Py_BuildValue("sOO", h
->h_name
, name_list
, addr_list
);
2782 Py_XDECREF(name_list
);
2783 Py_XDECREF(addr_list
);
2788 /* Python interface to gethostbyname_ex(name). */
2792 socket_gethostbyname_ex(PyObject
*self
, PyObject
*args
)
2797 struct sockaddr_storage addr
;
2799 struct sockaddr_in addr
;
2801 struct sockaddr
*sa
;
2803 #ifdef HAVE_GETHOSTBYNAME_R
2804 struct hostent hp_allocated
;
2805 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
2806 struct hostent_data data
;
2809 int buf_len
= (sizeof buf
) - 1;
2812 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2815 #endif /* HAVE_GETHOSTBYNAME_R */
2817 if (!PyArg_ParseTuple(args
, "s:gethostbyname_ex", &name
))
2819 if (setipaddr(name
, (struct sockaddr
*)&addr
, sizeof(addr
), AF_INET
) < 0)
2821 Py_BEGIN_ALLOW_THREADS
2822 #ifdef HAVE_GETHOSTBYNAME_R
2823 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2824 result
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
,
2826 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
2827 h
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
, &errnop
);
2828 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
2829 memset((void *) &data
, '\0', sizeof(data
));
2830 result
= gethostbyname_r(name
, &hp_allocated
, &data
);
2831 h
= (result
!= 0) ? NULL
: &hp_allocated
;
2833 #else /* not HAVE_GETHOSTBYNAME_R */
2834 #ifdef USE_GETHOSTBYNAME_LOCK
2835 PyThread_acquire_lock(netdb_lock
, 1);
2837 h
= gethostbyname(name
);
2838 #endif /* HAVE_GETHOSTBYNAME_R */
2839 Py_END_ALLOW_THREADS
2840 /* Some C libraries would require addr.__ss_family instead of
2842 Therefore, we cast the sockaddr_storage into sockaddr to
2843 access sa_family. */
2844 sa
= (struct sockaddr
*)&addr
;
2845 ret
= gethost_common(h
, (struct sockaddr
*)&addr
, sizeof(addr
),
2847 #ifdef USE_GETHOSTBYNAME_LOCK
2848 PyThread_release_lock(netdb_lock
);
2853 PyDoc_STRVAR(ghbn_ex_doc
,
2854 "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
2856 Return the true host name, a list of aliases, and a list of IP addresses,\n\
2857 for a host. The host argument is a string giving a host name or IP number.");
2860 /* Python interface to gethostbyaddr(IP). */
2864 socket_gethostbyaddr(PyObject
*self
, PyObject
*args
)
2867 struct sockaddr_storage addr
;
2869 struct sockaddr_in addr
;
2871 struct sockaddr
*sa
= (struct sockaddr
*)&addr
;
2875 #ifdef HAVE_GETHOSTBYNAME_R
2876 struct hostent hp_allocated
;
2877 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
2878 struct hostent_data data
;
2881 int buf_len
= (sizeof buf
) - 1;
2884 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2887 #endif /* HAVE_GETHOSTBYNAME_R */
2892 if (!PyArg_ParseTuple(args
, "s:gethostbyaddr", &ip_num
))
2895 if (setipaddr(ip_num
, sa
, sizeof(addr
), af
) < 0)
2902 ap
= (char *)&((struct sockaddr_in
*)sa
)->sin_addr
;
2903 al
= sizeof(((struct sockaddr_in
*)sa
)->sin_addr
);
2907 ap
= (char *)&((struct sockaddr_in6
*)sa
)->sin6_addr
;
2908 al
= sizeof(((struct sockaddr_in6
*)sa
)->sin6_addr
);
2912 PyErr_SetString(socket_error
, "unsupported address family");
2915 Py_BEGIN_ALLOW_THREADS
2916 #ifdef HAVE_GETHOSTBYNAME_R
2917 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2918 result
= gethostbyaddr_r(ap
, al
, af
,
2919 &hp_allocated
, buf
, buf_len
,
2921 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
2922 h
= gethostbyaddr_r(ap
, al
, af
,
2923 &hp_allocated
, buf
, buf_len
, &errnop
);
2924 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
2925 memset((void *) &data
, '\0', sizeof(data
));
2926 result
= gethostbyaddr_r(ap
, al
, af
, &hp_allocated
, &data
);
2927 h
= (result
!= 0) ? NULL
: &hp_allocated
;
2929 #else /* not HAVE_GETHOSTBYNAME_R */
2930 #ifdef USE_GETHOSTBYNAME_LOCK
2931 PyThread_acquire_lock(netdb_lock
, 1);
2933 h
= gethostbyaddr(ap
, al
, af
);
2934 #endif /* HAVE_GETHOSTBYNAME_R */
2935 Py_END_ALLOW_THREADS
2936 ret
= gethost_common(h
, (struct sockaddr
*)&addr
, sizeof(addr
), af
);
2937 #ifdef USE_GETHOSTBYNAME_LOCK
2938 PyThread_release_lock(netdb_lock
);
2943 PyDoc_STRVAR(gethostbyaddr_doc
,
2944 "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
2946 Return the true host name, a list of aliases, and a list of IP addresses,\n\
2947 for a host. The host argument is a string giving a host name or IP number.");
2950 /* Python interface to getservbyname(name).
2951 This only returns the port number, since the other info is already
2952 known or not useful (like the list of aliases). */
2956 socket_getservbyname(PyObject
*self
, PyObject
*args
)
2958 char *name
, *proto
=NULL
;
2960 if (!PyArg_ParseTuple(args
, "s|s:getservbyname", &name
, &proto
))
2962 Py_BEGIN_ALLOW_THREADS
2963 sp
= getservbyname(name
, proto
);
2964 Py_END_ALLOW_THREADS
2966 PyErr_SetString(socket_error
, "service/proto not found");
2969 return PyInt_FromLong((long) ntohs(sp
->s_port
));
2972 PyDoc_STRVAR(getservbyname_doc
,
2973 "getservbyname(servicename[, protocolname]) -> integer\n\
2975 Return a port number from a service name and protocol name.\n\
2976 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
2977 otherwise any protocol will match.");
2980 /* Python interface to getservbyport(port).
2981 This only returns the service name, since the other info is already
2982 known or not useful (like the list of aliases). */
2986 socket_getservbyport(PyObject
*self
, PyObject
*args
)
2988 unsigned short port
;
2991 if (!PyArg_ParseTuple(args
, "H|s:getservbyport", &port
, &proto
))
2993 Py_BEGIN_ALLOW_THREADS
2994 sp
= getservbyport(htons(port
), proto
);
2995 Py_END_ALLOW_THREADS
2997 PyErr_SetString(socket_error
, "port/proto not found");
3000 return PyString_FromString(sp
->s_name
);
3003 PyDoc_STRVAR(getservbyport_doc
,
3004 "getservbyport(port[, protocolname]) -> string\n\
3006 Return the service name from a port number and protocol name.\n\
3007 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3008 otherwise any protocol will match.");
3010 /* Python interface to getprotobyname(name).
3011 This only returns the protocol number, since the other info is
3012 already known or not useful (like the list of aliases). */
3016 socket_getprotobyname(PyObject
*self
, PyObject
*args
)
3019 struct protoent
*sp
;
3021 /* Not available in BeOS yet. - [cjh] */
3022 PyErr_SetString(socket_error
, "getprotobyname not supported");
3025 if (!PyArg_ParseTuple(args
, "s:getprotobyname", &name
))
3027 Py_BEGIN_ALLOW_THREADS
3028 sp
= getprotobyname(name
);
3029 Py_END_ALLOW_THREADS
3031 PyErr_SetString(socket_error
, "protocol not found");
3034 return PyInt_FromLong((long) sp
->p_proto
);
3038 PyDoc_STRVAR(getprotobyname_doc
,
3039 "getprotobyname(name) -> integer\n\
3041 Return the protocol number for the named protocol. (Rarely used.)");
3044 #ifdef HAVE_SOCKETPAIR
3045 /* Create a pair of sockets using the socketpair() function.
3046 Arguments as for socket() except the default family is AF_UNIX if
3047 defined on the platform; otherwise, the default is AF_INET. */
3051 socket_socketpair(PyObject
*self
, PyObject
*args
)
3053 PySocketSockObject
*s0
= NULL
, *s1
= NULL
;
3055 int family
, type
= SOCK_STREAM
, proto
= 0;
3056 PyObject
*res
= NULL
;
3058 #if defined(AF_UNIX)
3063 if (!PyArg_ParseTuple(args
, "|iii:socketpair",
3064 &family
, &type
, &proto
))
3066 /* Create a pair of socket fds */
3067 if (socketpair(family
, type
, proto
, sv
) < 0)
3069 s0
= new_sockobject(sv
[0], family
, type
, proto
);
3072 s1
= new_sockobject(sv
[1], family
, type
, proto
);
3075 res
= PyTuple_Pack(2, s0
, s1
);
3089 PyDoc_STRVAR(socketpair_doc
,
3090 "socketpair([family[, type[, proto]]]) -> (socket object, socket object)\n\
3092 Create a pair of socket objects from the sockets returned by the platform\n\
3093 socketpair() function.\n\
3094 The arguments are the same as for socket() except the default family is\n\
3095 AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");
3097 #endif /* HAVE_SOCKETPAIR */
3101 /* Create a socket object from a numeric file description.
3102 Useful e.g. if stdin is a socket.
3103 Additional arguments as for socket(). */
3107 socket_fromfd(PyObject
*self
, PyObject
*args
)
3109 PySocketSockObject
*s
;
3111 int family
, type
, proto
= 0;
3112 if (!PyArg_ParseTuple(args
, "iii|i:fromfd",
3113 &fd
, &family
, &type
, &proto
))
3115 /* Dup the fd so it and the socket can be closed independently */
3119 s
= new_sockobject(fd
, family
, type
, proto
);
3120 return (PyObject
*) s
;
3123 PyDoc_STRVAR(fromfd_doc
,
3124 "fromfd(fd, family, type[, proto]) -> socket object\n\
3126 Create a socket object from the given file descriptor.\n\
3127 The remaining arguments are the same as for socket().");
3133 socket_ntohs(PyObject
*self
, PyObject
*args
)
3137 if (!PyArg_ParseTuple(args
, "i:ntohs", &x1
)) {
3140 x2
= (int)ntohs((short)x1
);
3141 return PyInt_FromLong(x2
);
3144 PyDoc_STRVAR(ntohs_doc
,
3145 "ntohs(integer) -> integer\n\
3147 Convert a 16-bit integer from network to host byte order.");
3151 socket_ntohl(PyObject
*self
, PyObject
*arg
)
3155 if (PyInt_Check(arg
)) {
3156 x
= PyInt_AS_LONG(arg
);
3157 if (x
== (unsigned long) -1 && PyErr_Occurred())
3160 else if (PyLong_Check(arg
)) {
3161 x
= PyLong_AsUnsignedLong(arg
);
3162 if (x
== (unsigned long) -1 && PyErr_Occurred())
3167 /* only want the trailing 32 bits */
3168 y
= x
& 0xFFFFFFFFUL
;
3170 return PyErr_Format(PyExc_OverflowError
,
3171 "long int larger than 32 bits");
3177 return PyErr_Format(PyExc_TypeError
,
3178 "expected int/long, %s found",
3179 arg
->ob_type
->tp_name
);
3180 if (x
== (unsigned long) -1 && PyErr_Occurred())
3182 return PyInt_FromLong(ntohl(x
));
3185 PyDoc_STRVAR(ntohl_doc
,
3186 "ntohl(integer) -> integer\n\
3188 Convert a 32-bit integer from network to host byte order.");
3192 socket_htons(PyObject
*self
, PyObject
*args
)
3196 if (!PyArg_ParseTuple(args
, "i:htons", &x1
)) {
3199 x2
= (int)htons((short)x1
);
3200 return PyInt_FromLong(x2
);
3203 PyDoc_STRVAR(htons_doc
,
3204 "htons(integer) -> integer\n\
3206 Convert a 16-bit integer from host to network byte order.");
3210 socket_htonl(PyObject
*self
, PyObject
*arg
)
3214 if (PyInt_Check(arg
)) {
3215 x
= PyInt_AS_LONG(arg
);
3216 if (x
== (unsigned long) -1 && PyErr_Occurred())
3219 else if (PyLong_Check(arg
)) {
3220 x
= PyLong_AsUnsignedLong(arg
);
3221 if (x
== (unsigned long) -1 && PyErr_Occurred())
3226 /* only want the trailing 32 bits */
3227 y
= x
& 0xFFFFFFFFUL
;
3229 return PyErr_Format(PyExc_OverflowError
,
3230 "long int larger than 32 bits");
3236 return PyErr_Format(PyExc_TypeError
,
3237 "expected int/long, %s found",
3238 arg
->ob_type
->tp_name
);
3239 return PyInt_FromLong(htonl(x
));
3242 PyDoc_STRVAR(htonl_doc
,
3243 "htonl(integer) -> integer\n\
3245 Convert a 32-bit integer from host to network byte order.");
3247 /* socket.inet_aton() and socket.inet_ntoa() functions. */
3249 PyDoc_STRVAR(inet_aton_doc
,
3250 "inet_aton(string) -> packed 32-bit IP representation\n\
3252 Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
3253 binary format used in low-level network functions.");
3256 socket_inet_aton(PyObject
*self
, PyObject
*args
)
3259 #define INADDR_NONE (-1)
3261 #ifdef HAVE_INET_ATON
3264 /* Have to use inet_addr() instead */
3265 unsigned long packed_addr
;
3269 if (!PyArg_ParseTuple(args
, "s:inet_aton", &ip_addr
))
3273 #ifdef HAVE_INET_ATON
3274 if (inet_aton(ip_addr
, &buf
))
3275 return PyString_FromStringAndSize((char *)(&buf
),
3278 PyErr_SetString(socket_error
,
3279 "illegal IP address string passed to inet_aton");
3282 #else /* ! HAVE_INET_ATON */
3283 /* special-case this address as inet_addr might return INADDR_NONE
3285 if (strcmp(ip_addr
, "255.255.255.255") == 0) {
3286 packed_addr
= 0xFFFFFFFF;
3289 packed_addr
= inet_addr(ip_addr
);
3291 if (packed_addr
== INADDR_NONE
) { /* invalid address */
3292 PyErr_SetString(socket_error
,
3293 "illegal IP address string passed to inet_aton");
3297 return PyString_FromStringAndSize((char *) &packed_addr
,
3298 sizeof(packed_addr
));
3302 PyDoc_STRVAR(inet_ntoa_doc
,
3303 "inet_ntoa(packed_ip) -> ip_address_string\n\
3305 Convert an IP address from 32-bit packed binary format to string format");
3308 socket_inet_ntoa(PyObject
*self
, PyObject
*args
)
3312 struct in_addr packed_addr
;
3314 if (!PyArg_ParseTuple(args
, "s#:inet_ntoa", &packed_str
, &addr_len
)) {
3318 if (addr_len
!= sizeof(packed_addr
)) {
3319 PyErr_SetString(socket_error
,
3320 "packed IP wrong length for inet_ntoa");
3324 memcpy(&packed_addr
, packed_str
, addr_len
);
3326 return PyString_FromString(inet_ntoa(packed_addr
));
3329 #ifdef HAVE_INET_PTON
3331 PyDoc_STRVAR(inet_pton_doc
,
3332 "inet_pton(af, ip) -> packed IP address string\n\
3334 Convert an IP address from string format to a packed string suitable\n\
3335 for use with low-level network functions.");
3338 socket_inet_pton(PyObject
*self
, PyObject
*args
)
3344 char packed
[MAX(sizeof(struct in_addr
), sizeof(struct in6_addr
))];
3346 char packed
[sizeof(struct in_addr
)];
3348 if (!PyArg_ParseTuple(args
, "is:inet_pton", &af
, &ip
)) {
3352 #if !defined(ENABLE_IPV6) && defined(AF_INET6)
3353 if(af
== AF_INET6
) {
3354 PyErr_SetString(socket_error
,
3355 "can't use AF_INET6, IPv6 is disabled");
3360 retval
= inet_pton(af
, ip
, packed
);
3362 PyErr_SetFromErrno(socket_error
);
3364 } else if (retval
== 0) {
3365 PyErr_SetString(socket_error
,
3366 "illegal IP address string passed to inet_pton");
3368 } else if (af
== AF_INET
) {
3369 return PyString_FromStringAndSize(packed
,
3370 sizeof(struct in_addr
));
3372 } else if (af
== AF_INET6
) {
3373 return PyString_FromStringAndSize(packed
,
3374 sizeof(struct in6_addr
));
3377 PyErr_SetString(socket_error
, "unknown address family");
3382 PyDoc_STRVAR(inet_ntop_doc
,
3383 "inet_ntop(af, packed_ip) -> string formatted IP address\n\
3385 Convert a packed IP address of the given family to string format.");
3388 socket_inet_ntop(PyObject
*self
, PyObject
*args
)
3395 char ip
[MAX(INET_ADDRSTRLEN
, INET6_ADDRSTRLEN
) + 1];
3397 char ip
[INET_ADDRSTRLEN
+ 1];
3400 /* Guarantee NUL-termination for PyString_FromString() below */
3401 memset((void *) &ip
[0], '\0', sizeof(ip
));
3403 if (!PyArg_ParseTuple(args
, "is#:inet_ntop", &af
, &packed
, &len
)) {
3407 if (af
== AF_INET
) {
3408 if (len
!= sizeof(struct in_addr
)) {
3409 PyErr_SetString(PyExc_ValueError
,
3410 "invalid length of packed IP address string");
3414 } else if (af
== AF_INET6
) {
3415 if (len
!= sizeof(struct in6_addr
)) {
3416 PyErr_SetString(PyExc_ValueError
,
3417 "invalid length of packed IP address string");
3422 PyErr_Format(PyExc_ValueError
,
3423 "unknown address family %d", af
);
3427 retval
= inet_ntop(af
, packed
, ip
, sizeof(ip
));
3429 PyErr_SetFromErrno(socket_error
);
3432 return PyString_FromString(retval
);
3436 PyErr_SetString(PyExc_RuntimeError
, "invalid handling of inet_ntop");
3440 #endif /* HAVE_INET_PTON */
3442 /* Python interface to getaddrinfo(host, port). */
3446 socket_getaddrinfo(PyObject
*self
, PyObject
*args
)
3448 struct addrinfo hints
, *res
;
3449 struct addrinfo
*res0
= NULL
;
3450 PyObject
*hobj
= NULL
;
3451 PyObject
*pobj
= (PyObject
*)NULL
;
3454 int family
, socktype
, protocol
, flags
;
3456 PyObject
*all
= (PyObject
*)NULL
;
3457 PyObject
*single
= (PyObject
*)NULL
;
3458 PyObject
*idna
= NULL
;
3460 family
= socktype
= protocol
= flags
= 0;
3462 if (!PyArg_ParseTuple(args
, "OO|iiii:getaddrinfo",
3463 &hobj
, &pobj
, &family
, &socktype
,
3464 &protocol
, &flags
)) {
3467 if (hobj
== Py_None
) {
3469 } else if (PyUnicode_Check(hobj
)) {
3470 idna
= PyObject_CallMethod(hobj
, "encode", "s", "idna");
3473 hptr
= PyString_AsString(idna
);
3474 } else if (PyString_Check(hobj
)) {
3475 hptr
= PyString_AsString(hobj
);
3477 PyErr_SetString(PyExc_TypeError
,
3478 "getaddrinfo() argument 1 must be string or None");
3481 if (PyInt_Check(pobj
)) {
3482 PyOS_snprintf(pbuf
, sizeof(pbuf
), "%ld", PyInt_AsLong(pobj
));
3484 } else if (PyString_Check(pobj
)) {
3485 pptr
= PyString_AsString(pobj
);
3486 } else if (pobj
== Py_None
) {
3487 pptr
= (char *)NULL
;
3489 PyErr_SetString(socket_error
, "Int or String expected");
3492 memset(&hints
, 0, sizeof(hints
));
3493 hints
.ai_family
= family
;
3494 hints
.ai_socktype
= socktype
;
3495 hints
.ai_protocol
= protocol
;
3496 hints
.ai_flags
= flags
;
3497 Py_BEGIN_ALLOW_THREADS
3498 ACQUIRE_GETADDRINFO_LOCK
3499 error
= getaddrinfo(hptr
, pptr
, &hints
, &res0
);
3500 Py_END_ALLOW_THREADS
3501 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
3503 set_gaierror(error
);
3507 if ((all
= PyList_New(0)) == NULL
)
3509 for (res
= res0
; res
; res
= res
->ai_next
) {
3511 makesockaddr(-1, res
->ai_addr
, res
->ai_addrlen
, protocol
);
3514 single
= Py_BuildValue("iiisO", res
->ai_family
,
3515 res
->ai_socktype
, res
->ai_protocol
,
3516 res
->ai_canonname
? res
->ai_canonname
: "",
3522 if (PyList_Append(all
, single
))
3536 return (PyObject
*)NULL
;
3539 PyDoc_STRVAR(getaddrinfo_doc
,
3540 "getaddrinfo(host, port [, family, socktype, proto, flags])\n\
3541 -> list of (family, socktype, proto, canonname, sockaddr)\n\
3543 Resolve host and port into addrinfo struct.");
3545 /* Python interface to getnameinfo(sa, flags). */
3549 socket_getnameinfo(PyObject
*self
, PyObject
*args
)
3551 PyObject
*sa
= (PyObject
*)NULL
;
3554 int port
, flowinfo
, scope_id
;
3555 char hbuf
[NI_MAXHOST
], pbuf
[NI_MAXSERV
];
3556 struct addrinfo hints
, *res
= NULL
;
3558 PyObject
*ret
= (PyObject
*)NULL
;
3560 flags
= flowinfo
= scope_id
= 0;
3561 if (!PyArg_ParseTuple(args
, "Oi:getnameinfo", &sa
, &flags
))
3563 if (!PyArg_ParseTuple(sa
, "si|ii",
3564 &hostp
, &port
, &flowinfo
, &scope_id
))
3566 PyOS_snprintf(pbuf
, sizeof(pbuf
), "%d", port
);
3567 memset(&hints
, 0, sizeof(hints
));
3568 hints
.ai_family
= AF_UNSPEC
;
3569 hints
.ai_socktype
= SOCK_DGRAM
; /* make numeric port happy */
3570 Py_BEGIN_ALLOW_THREADS
3571 ACQUIRE_GETADDRINFO_LOCK
3572 error
= getaddrinfo(hostp
, pbuf
, &hints
, &res
);
3573 Py_END_ALLOW_THREADS
3574 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
3576 set_gaierror(error
);
3580 PyErr_SetString(socket_error
,
3581 "sockaddr resolved to multiple addresses");
3584 switch (res
->ai_family
) {
3589 if (PyArg_ParseTuple(sa
, "si", &t1
, &t2
) == 0) {
3590 PyErr_SetString(socket_error
,
3591 "IPv4 sockaddr must be 2 tuple");
3599 struct sockaddr_in6
*sin6
;
3600 sin6
= (struct sockaddr_in6
*)res
->ai_addr
;
3601 sin6
->sin6_flowinfo
= flowinfo
;
3602 sin6
->sin6_scope_id
= scope_id
;
3607 error
= getnameinfo(res
->ai_addr
, res
->ai_addrlen
,
3608 hbuf
, sizeof(hbuf
), pbuf
, sizeof(pbuf
), flags
);
3610 set_gaierror(error
);
3613 ret
= Py_BuildValue("ss", hbuf
, pbuf
);
3621 PyDoc_STRVAR(getnameinfo_doc
,
3622 "getnameinfo(sockaddr, flags) --> (host, port)\n\
3624 Get host and port for a sockaddr.");
3627 /* Python API to getting and setting the default timeout value. */
3630 socket_getdefaulttimeout(PyObject
*self
)
3632 if (defaulttimeout
< 0.0) {
3637 return PyFloat_FromDouble(defaulttimeout
);
3640 PyDoc_STRVAR(getdefaulttimeout_doc
,
3641 "getdefaulttimeout() -> timeout\n\
3643 Returns the default timeout in floating seconds for new socket objects.\n\
3644 A value of None indicates that new socket objects have no timeout.\n\
3645 When the socket module is first imported, the default is None.");
3648 socket_setdefaulttimeout(PyObject
*self
, PyObject
*arg
)
3655 timeout
= PyFloat_AsDouble(arg
);
3656 if (timeout
< 0.0) {
3657 if (!PyErr_Occurred())
3658 PyErr_SetString(PyExc_ValueError
,
3659 "Timeout value out of range");
3664 defaulttimeout
= timeout
;
3670 PyDoc_STRVAR(setdefaulttimeout_doc
,
3671 "setdefaulttimeout(timeout)\n\
3673 Set the default timeout in floating seconds for new socket objects.\n\
3674 A value of None indicates that new socket objects have no timeout.\n\
3675 When the socket module is first imported, the default is None.");
3678 /* List of functions exported by this module. */
3680 static PyMethodDef socket_methods
[] = {
3681 {"gethostbyname", socket_gethostbyname
,
3682 METH_VARARGS
, gethostbyname_doc
},
3683 {"gethostbyname_ex", socket_gethostbyname_ex
,
3684 METH_VARARGS
, ghbn_ex_doc
},
3685 {"gethostbyaddr", socket_gethostbyaddr
,
3686 METH_VARARGS
, gethostbyaddr_doc
},
3687 {"gethostname", socket_gethostname
,
3688 METH_VARARGS
, gethostname_doc
},
3689 {"getservbyname", socket_getservbyname
,
3690 METH_VARARGS
, getservbyname_doc
},
3691 {"getservbyport", socket_getservbyport
,
3692 METH_VARARGS
, getservbyport_doc
},
3693 {"getprotobyname", socket_getprotobyname
,
3694 METH_VARARGS
,getprotobyname_doc
},
3696 {"fromfd", socket_fromfd
,
3697 METH_VARARGS
, fromfd_doc
},
3699 #ifdef HAVE_SOCKETPAIR
3700 {"socketpair", socket_socketpair
,
3701 METH_VARARGS
, socketpair_doc
},
3703 {"ntohs", socket_ntohs
,
3704 METH_VARARGS
, ntohs_doc
},
3705 {"ntohl", socket_ntohl
,
3707 {"htons", socket_htons
,
3708 METH_VARARGS
, htons_doc
},
3709 {"htonl", socket_htonl
,
3711 {"inet_aton", socket_inet_aton
,
3712 METH_VARARGS
, inet_aton_doc
},
3713 {"inet_ntoa", socket_inet_ntoa
,
3714 METH_VARARGS
, inet_ntoa_doc
},
3715 #ifdef HAVE_INET_PTON
3716 {"inet_pton", socket_inet_pton
,
3717 METH_VARARGS
, inet_pton_doc
},
3718 {"inet_ntop", socket_inet_ntop
,
3719 METH_VARARGS
, inet_ntop_doc
},
3721 {"getaddrinfo", socket_getaddrinfo
,
3722 METH_VARARGS
, getaddrinfo_doc
},
3723 {"getnameinfo", socket_getnameinfo
,
3724 METH_VARARGS
, getnameinfo_doc
},
3725 {"getdefaulttimeout", (PyCFunction
)socket_getdefaulttimeout
,
3726 METH_NOARGS
, getdefaulttimeout_doc
},
3727 {"setdefaulttimeout", socket_setdefaulttimeout
,
3728 METH_O
, setdefaulttimeout_doc
},
3729 {NULL
, NULL
} /* Sentinel */
3734 #define OS_INIT_DEFINED
3742 _kernel_swi(0x43380, &r
, &r
);
3743 taskwindow
= r
.r
[0];
3752 #define OS_INIT_DEFINED
3754 /* Additional initialization and cleanup for Windows */
3768 ret
= WSAStartup(0x0101, &WSAData
);
3770 case 0: /* No error */
3771 Py_AtExit(os_cleanup
);
3772 return 1; /* Success */
3773 case WSASYSNOTREADY
:
3774 PyErr_SetString(PyExc_ImportError
,
3775 "WSAStartup failed: network not ready");
3777 case WSAVERNOTSUPPORTED
:
3781 "WSAStartup failed: requested version not supported");
3784 PyOS_snprintf(buf
, sizeof(buf
),
3785 "WSAStartup failed: error code %d", ret
);
3786 PyErr_SetString(PyExc_ImportError
, buf
);
3789 return 0; /* Failure */
3792 #endif /* MS_WINDOWS */
3796 #define OS_INIT_DEFINED
3798 /* Additional initialization for OS/2 */
3805 int rc
= sock_init();
3808 return 1; /* Success */
3811 PyOS_snprintf(reason
, sizeof(reason
),
3812 "OS/2 TCP/IP Error# %d", sock_errno());
3813 PyErr_SetString(PyExc_ImportError
, reason
);
3815 return 0; /* Failure */
3817 /* No need to initialise sockets with GCC/EMX */
3818 return 1; /* Success */
3822 #endif /* PYOS_OS2 */
3825 #ifndef OS_INIT_DEFINED
3829 return 1; /* Success */
3834 /* C API table - always add new things to the end for binary
3837 PySocketModule_APIObject PySocketModuleAPI
=
3844 /* Initialize the _socket module.
3846 This module is actually called "_socket", and there's a wrapper
3847 "socket.py" which implements some additional functionality. On some
3848 platforms (e.g. Windows and OS/2), socket.py also implements a
3849 wrapper for the socket type that provides missing functionality such
3850 as makefile(), dup() and fromfd(). The import of "_socket" may fail
3851 with an ImportError exception if os-specific initialization fails.
3852 On Windows, this does WINSOCK initialization. When WINSOCK is
3853 initialized succesfully, a call to WSACleanup() is scheduled to be
3857 PyDoc_STRVAR(socket_doc
,
3858 "Implementation module for socket operations.\n\
3860 See the socket module for documentation.");
3865 PyObject
*m
, *has_ipv6
;
3870 sock_type
.ob_type
= &PyType_Type
;
3871 m
= Py_InitModule3(PySocket_MODULE_NAME
,
3875 socket_error
= PyErr_NewException("socket.error", NULL
, NULL
);
3876 if (socket_error
== NULL
)
3878 PySocketModuleAPI
.error
= socket_error
;
3879 Py_INCREF(socket_error
);
3880 PyModule_AddObject(m
, "error", socket_error
);
3881 socket_herror
= PyErr_NewException("socket.herror",
3882 socket_error
, NULL
);
3883 if (socket_herror
== NULL
)
3885 Py_INCREF(socket_herror
);
3886 PyModule_AddObject(m
, "herror", socket_herror
);
3887 socket_gaierror
= PyErr_NewException("socket.gaierror", socket_error
,
3889 if (socket_gaierror
== NULL
)
3891 Py_INCREF(socket_gaierror
);
3892 PyModule_AddObject(m
, "gaierror", socket_gaierror
);
3893 socket_timeout
= PyErr_NewException("socket.timeout",
3894 socket_error
, NULL
);
3895 if (socket_timeout
== NULL
)
3897 Py_INCREF(socket_timeout
);
3898 PyModule_AddObject(m
, "timeout", socket_timeout
);
3899 Py_INCREF((PyObject
*)&sock_type
);
3900 if (PyModule_AddObject(m
, "SocketType",
3901 (PyObject
*)&sock_type
) != 0)
3903 Py_INCREF((PyObject
*)&sock_type
);
3904 if (PyModule_AddObject(m
, "socket",
3905 (PyObject
*)&sock_type
) != 0)
3911 has_ipv6
= Py_False
;
3913 Py_INCREF(has_ipv6
);
3914 PyModule_AddObject(m
, "has_ipv6", has_ipv6
);
3917 if (PyModule_AddObject(m
, PySocket_CAPI_NAME
,
3918 PyCObject_FromVoidPtr((void *)&PySocketModuleAPI
, NULL
)
3922 /* Address families (we only support AF_INET and AF_UNIX) */
3924 PyModule_AddIntConstant(m
, "AF_UNSPEC", AF_UNSPEC
);
3926 PyModule_AddIntConstant(m
, "AF_INET", AF_INET
);
3928 PyModule_AddIntConstant(m
, "AF_INET6", AF_INET6
);
3929 #endif /* AF_INET6 */
3930 #if defined(AF_UNIX)
3931 PyModule_AddIntConstant(m
, "AF_UNIX", AF_UNIX
);
3932 #endif /* AF_UNIX */
3934 /* Amateur Radio AX.25 */
3935 PyModule_AddIntConstant(m
, "AF_AX25", AF_AX25
);
3938 PyModule_AddIntConstant(m
, "AF_IPX", AF_IPX
); /* Novell IPX */
3942 PyModule_AddIntConstant(m
, "AF_APPLETALK", AF_APPLETALK
);
3945 /* Amateur radio NetROM */
3946 PyModule_AddIntConstant(m
, "AF_NETROM", AF_NETROM
);
3949 /* Multiprotocol bridge */
3950 PyModule_AddIntConstant(m
, "AF_BRIDGE", AF_BRIDGE
);
3954 PyModule_AddIntConstant(m
, "AF_ATMPVC", AF_ATMPVC
);
3957 /* Reserved for Werner's ATM */
3958 PyModule_AddIntConstant(m
, "AF_AAL5", AF_AAL5
);
3961 /* Reserved for X.25 project */
3962 PyModule_AddIntConstant(m
, "AF_X25", AF_X25
);
3965 PyModule_AddIntConstant(m
, "AF_INET6", AF_INET6
); /* IP version 6 */
3968 /* Amateur Radio X.25 PLP */
3969 PyModule_AddIntConstant(m
, "AF_ROSE", AF_ROSE
);
3972 /* Reserved for DECnet project */
3973 PyModule_AddIntConstant(m
, "AF_DECnet", AF_DECnet
);
3976 /* Reserved for 802.2LLC project */
3977 PyModule_AddIntConstant(m
, "AF_NETBEUI", AF_NETBEUI
);
3980 /* Security callback pseudo AF */
3981 PyModule_AddIntConstant(m
, "AF_SECURITY", AF_SECURITY
);
3984 /* PF_KEY key management API */
3985 PyModule_AddIntConstant(m
, "AF_KEY", AF_KEY
);
3989 PyModule_AddIntConstant(m
, "AF_NETLINK", AF_NETLINK
);
3990 PyModule_AddIntConstant(m
, "NETLINK_ROUTE", NETLINK_ROUTE
);
3991 PyModule_AddIntConstant(m
, "NETLINK_SKIP", NETLINK_SKIP
);
3992 PyModule_AddIntConstant(m
, "NETLINK_USERSOCK", NETLINK_USERSOCK
);
3993 PyModule_AddIntConstant(m
, "NETLINK_FIREWALL", NETLINK_FIREWALL
);
3994 PyModule_AddIntConstant(m
, "NETLINK_TCPDIAG", NETLINK_TCPDIAG
);
3995 PyModule_AddIntConstant(m
, "NETLINK_NFLOG", NETLINK_NFLOG
);
3997 PyModule_AddIntConstant(m
, "NETLINK_XFRM", NETLINK_XFRM
);
3999 PyModule_AddIntConstant(m
, "NETLINK_ARPD", NETLINK_ARPD
);
4000 PyModule_AddIntConstant(m
, "NETLINK_ROUTE6", NETLINK_ROUTE6
);
4001 PyModule_AddIntConstant(m
, "NETLINK_IP6_FW", NETLINK_IP6_FW
);
4002 PyModule_AddIntConstant(m
, "NETLINK_DNRTMSG", NETLINK_DNRTMSG
);
4003 PyModule_AddIntConstant(m
, "NETLINK_TAPBASE", NETLINK_TAPBASE
);
4006 /* Alias to emulate 4.4BSD */
4007 PyModule_AddIntConstant(m
, "AF_ROUTE", AF_ROUTE
);
4011 PyModule_AddIntConstant(m
, "AF_ASH", AF_ASH
);
4015 PyModule_AddIntConstant(m
, "AF_ECONET", AF_ECONET
);
4019 PyModule_AddIntConstant(m
, "AF_ATMSVC", AF_ATMSVC
);
4022 /* Linux SNA Project (nutters!) */
4023 PyModule_AddIntConstant(m
, "AF_SNA", AF_SNA
);
4027 PyModule_AddIntConstant(m
, "AF_IRDA", AF_IRDA
);
4031 PyModule_AddIntConstant(m
, "AF_PPPOX", AF_PPPOX
);
4034 /* Wanpipe API Sockets */
4035 PyModule_AddIntConstant(m
, "AF_WANPIPE", AF_WANPIPE
);
4039 PyModule_AddIntConstant(m
, "AF_LLC", AF_LLC
);
4042 #ifdef USE_BLUETOOTH
4043 PyModule_AddIntConstant(m
, "AF_BLUETOOTH", AF_BLUETOOTH
);
4044 PyModule_AddIntConstant(m
, "BTPROTO_L2CAP", BTPROTO_L2CAP
);
4045 #if !defined(__FreeBSD__)
4046 PyModule_AddIntConstant(m
, "BTPROTO_SCO", BTPROTO_SCO
);
4048 PyModule_AddIntConstant(m
, "BTPROTO_RFCOMM", BTPROTO_RFCOMM
);
4049 PyModule_AddObject(m
, "BDADDR_ANY", Py_BuildValue("s", "00:00:00:00:00:00"));
4050 PyModule_AddObject(m
, "BDADDR_LOCAL", Py_BuildValue("s", "00:00:00:FF:FF:FF"));
4053 #ifdef HAVE_NETPACKET_PACKET_H
4054 PyModule_AddIntConstant(m
, "AF_PACKET", AF_PACKET
);
4055 PyModule_AddIntConstant(m
, "PF_PACKET", PF_PACKET
);
4056 PyModule_AddIntConstant(m
, "PACKET_HOST", PACKET_HOST
);
4057 PyModule_AddIntConstant(m
, "PACKET_BROADCAST", PACKET_BROADCAST
);
4058 PyModule_AddIntConstant(m
, "PACKET_MULTICAST", PACKET_MULTICAST
);
4059 PyModule_AddIntConstant(m
, "PACKET_OTHERHOST", PACKET_OTHERHOST
);
4060 PyModule_AddIntConstant(m
, "PACKET_OUTGOING", PACKET_OUTGOING
);
4061 PyModule_AddIntConstant(m
, "PACKET_LOOPBACK", PACKET_LOOPBACK
);
4062 PyModule_AddIntConstant(m
, "PACKET_FASTROUTE", PACKET_FASTROUTE
);
4066 PyModule_AddIntConstant(m
, "SOCK_STREAM", SOCK_STREAM
);
4067 PyModule_AddIntConstant(m
, "SOCK_DGRAM", SOCK_DGRAM
);
4069 /* We have incomplete socket support. */
4070 PyModule_AddIntConstant(m
, "SOCK_RAW", SOCK_RAW
);
4071 PyModule_AddIntConstant(m
, "SOCK_SEQPACKET", SOCK_SEQPACKET
);
4072 #if defined(SOCK_RDM)
4073 PyModule_AddIntConstant(m
, "SOCK_RDM", SOCK_RDM
);
4078 PyModule_AddIntConstant(m
, "SO_DEBUG", SO_DEBUG
);
4080 #ifdef SO_ACCEPTCONN
4081 PyModule_AddIntConstant(m
, "SO_ACCEPTCONN", SO_ACCEPTCONN
);
4084 PyModule_AddIntConstant(m
, "SO_REUSEADDR", SO_REUSEADDR
);
4086 #ifdef SO_EXCLUSIVEADDRUSE
4087 PyModule_AddIntConstant(m
, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE
);
4091 PyModule_AddIntConstant(m
, "SO_KEEPALIVE", SO_KEEPALIVE
);
4094 PyModule_AddIntConstant(m
, "SO_DONTROUTE", SO_DONTROUTE
);
4097 PyModule_AddIntConstant(m
, "SO_BROADCAST", SO_BROADCAST
);
4099 #ifdef SO_USELOOPBACK
4100 PyModule_AddIntConstant(m
, "SO_USELOOPBACK", SO_USELOOPBACK
);
4103 PyModule_AddIntConstant(m
, "SO_LINGER", SO_LINGER
);
4106 PyModule_AddIntConstant(m
, "SO_OOBINLINE", SO_OOBINLINE
);
4109 PyModule_AddIntConstant(m
, "SO_REUSEPORT", SO_REUSEPORT
);
4112 PyModule_AddIntConstant(m
, "SO_SNDBUF", SO_SNDBUF
);
4115 PyModule_AddIntConstant(m
, "SO_RCVBUF", SO_RCVBUF
);
4118 PyModule_AddIntConstant(m
, "SO_SNDLOWAT", SO_SNDLOWAT
);
4121 PyModule_AddIntConstant(m
, "SO_RCVLOWAT", SO_RCVLOWAT
);
4124 PyModule_AddIntConstant(m
, "SO_SNDTIMEO", SO_SNDTIMEO
);
4127 PyModule_AddIntConstant(m
, "SO_RCVTIMEO", SO_RCVTIMEO
);
4130 PyModule_AddIntConstant(m
, "SO_ERROR", SO_ERROR
);
4133 PyModule_AddIntConstant(m
, "SO_TYPE", SO_TYPE
);
4136 /* Maximum number of connections for "listen" */
4138 PyModule_AddIntConstant(m
, "SOMAXCONN", SOMAXCONN
);
4140 PyModule_AddIntConstant(m
, "SOMAXCONN", 5); /* Common value */
4143 /* Flags for send, recv */
4145 PyModule_AddIntConstant(m
, "MSG_OOB", MSG_OOB
);
4148 PyModule_AddIntConstant(m
, "MSG_PEEK", MSG_PEEK
);
4150 #ifdef MSG_DONTROUTE
4151 PyModule_AddIntConstant(m
, "MSG_DONTROUTE", MSG_DONTROUTE
);
4154 PyModule_AddIntConstant(m
, "MSG_DONTWAIT", MSG_DONTWAIT
);
4157 PyModule_AddIntConstant(m
, "MSG_EOR", MSG_EOR
);
4160 PyModule_AddIntConstant(m
, "MSG_TRUNC", MSG_TRUNC
);
4163 PyModule_AddIntConstant(m
, "MSG_CTRUNC", MSG_CTRUNC
);
4166 PyModule_AddIntConstant(m
, "MSG_WAITALL", MSG_WAITALL
);
4169 PyModule_AddIntConstant(m
, "MSG_BTAG", MSG_BTAG
);
4172 PyModule_AddIntConstant(m
, "MSG_ETAG", MSG_ETAG
);
4175 /* Protocol level and numbers, usable for [gs]etsockopt */
4177 PyModule_AddIntConstant(m
, "SOL_SOCKET", SOL_SOCKET
);
4180 PyModule_AddIntConstant(m
, "SOL_IP", SOL_IP
);
4182 PyModule_AddIntConstant(m
, "SOL_IP", 0);
4185 PyModule_AddIntConstant(m
, "SOL_IPX", SOL_IPX
);
4188 PyModule_AddIntConstant(m
, "SOL_AX25", SOL_AX25
);
4191 PyModule_AddIntConstant(m
, "SOL_ATALK", SOL_ATALK
);
4194 PyModule_AddIntConstant(m
, "SOL_NETROM", SOL_NETROM
);
4197 PyModule_AddIntConstant(m
, "SOL_ROSE", SOL_ROSE
);
4200 PyModule_AddIntConstant(m
, "SOL_TCP", SOL_TCP
);
4202 PyModule_AddIntConstant(m
, "SOL_TCP", 6);
4205 PyModule_AddIntConstant(m
, "SOL_UDP", SOL_UDP
);
4207 PyModule_AddIntConstant(m
, "SOL_UDP", 17);
4210 PyModule_AddIntConstant(m
, "IPPROTO_IP", IPPROTO_IP
);
4212 PyModule_AddIntConstant(m
, "IPPROTO_IP", 0);
4214 #ifdef IPPROTO_HOPOPTS
4215 PyModule_AddIntConstant(m
, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS
);
4218 PyModule_AddIntConstant(m
, "IPPROTO_ICMP", IPPROTO_ICMP
);
4220 PyModule_AddIntConstant(m
, "IPPROTO_ICMP", 1);
4223 PyModule_AddIntConstant(m
, "IPPROTO_IGMP", IPPROTO_IGMP
);
4226 PyModule_AddIntConstant(m
, "IPPROTO_GGP", IPPROTO_GGP
);
4229 PyModule_AddIntConstant(m
, "IPPROTO_IPV4", IPPROTO_IPV4
);
4232 PyModule_AddIntConstant(m
, "IPPROTO_IPV6", IPPROTO_IPV6
);
4235 PyModule_AddIntConstant(m
, "IPPROTO_IPIP", IPPROTO_IPIP
);
4238 PyModule_AddIntConstant(m
, "IPPROTO_TCP", IPPROTO_TCP
);
4240 PyModule_AddIntConstant(m
, "IPPROTO_TCP", 6);
4243 PyModule_AddIntConstant(m
, "IPPROTO_EGP", IPPROTO_EGP
);
4246 PyModule_AddIntConstant(m
, "IPPROTO_PUP", IPPROTO_PUP
);
4249 PyModule_AddIntConstant(m
, "IPPROTO_UDP", IPPROTO_UDP
);
4251 PyModule_AddIntConstant(m
, "IPPROTO_UDP", 17);
4254 PyModule_AddIntConstant(m
, "IPPROTO_IDP", IPPROTO_IDP
);
4256 #ifdef IPPROTO_HELLO
4257 PyModule_AddIntConstant(m
, "IPPROTO_HELLO", IPPROTO_HELLO
);
4260 PyModule_AddIntConstant(m
, "IPPROTO_ND", IPPROTO_ND
);
4263 PyModule_AddIntConstant(m
, "IPPROTO_TP", IPPROTO_TP
);
4266 PyModule_AddIntConstant(m
, "IPPROTO_IPV6", IPPROTO_IPV6
);
4268 #ifdef IPPROTO_ROUTING
4269 PyModule_AddIntConstant(m
, "IPPROTO_ROUTING", IPPROTO_ROUTING
);
4271 #ifdef IPPROTO_FRAGMENT
4272 PyModule_AddIntConstant(m
, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT
);
4275 PyModule_AddIntConstant(m
, "IPPROTO_RSVP", IPPROTO_RSVP
);
4278 PyModule_AddIntConstant(m
, "IPPROTO_GRE", IPPROTO_GRE
);
4281 PyModule_AddIntConstant(m
, "IPPROTO_ESP", IPPROTO_ESP
);
4284 PyModule_AddIntConstant(m
, "IPPROTO_AH", IPPROTO_AH
);
4286 #ifdef IPPROTO_MOBILE
4287 PyModule_AddIntConstant(m
, "IPPROTO_MOBILE", IPPROTO_MOBILE
);
4289 #ifdef IPPROTO_ICMPV6
4290 PyModule_AddIntConstant(m
, "IPPROTO_ICMPV6", IPPROTO_ICMPV6
);
4293 PyModule_AddIntConstant(m
, "IPPROTO_NONE", IPPROTO_NONE
);
4295 #ifdef IPPROTO_DSTOPTS
4296 PyModule_AddIntConstant(m
, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS
);
4299 PyModule_AddIntConstant(m
, "IPPROTO_XTP", IPPROTO_XTP
);
4302 PyModule_AddIntConstant(m
, "IPPROTO_EON", IPPROTO_EON
);
4305 PyModule_AddIntConstant(m
, "IPPROTO_PIM", IPPROTO_PIM
);
4307 #ifdef IPPROTO_IPCOMP
4308 PyModule_AddIntConstant(m
, "IPPROTO_IPCOMP", IPPROTO_IPCOMP
);
4311 PyModule_AddIntConstant(m
, "IPPROTO_VRRP", IPPROTO_VRRP
);
4314 PyModule_AddIntConstant(m
, "IPPROTO_BIP", IPPROTO_BIP
);
4318 PyModule_AddIntConstant(m
, "IPPROTO_RAW", IPPROTO_RAW
);
4320 PyModule_AddIntConstant(m
, "IPPROTO_RAW", 255);
4323 PyModule_AddIntConstant(m
, "IPPROTO_MAX", IPPROTO_MAX
);
4326 /* Some port configuration */
4327 #ifdef IPPORT_RESERVED
4328 PyModule_AddIntConstant(m
, "IPPORT_RESERVED", IPPORT_RESERVED
);
4330 PyModule_AddIntConstant(m
, "IPPORT_RESERVED", 1024);
4332 #ifdef IPPORT_USERRESERVED
4333 PyModule_AddIntConstant(m
, "IPPORT_USERRESERVED", IPPORT_USERRESERVED
);
4335 PyModule_AddIntConstant(m
, "IPPORT_USERRESERVED", 5000);
4338 /* Some reserved IP v.4 addresses */
4340 PyModule_AddIntConstant(m
, "INADDR_ANY", INADDR_ANY
);
4342 PyModule_AddIntConstant(m
, "INADDR_ANY", 0x00000000);
4344 #ifdef INADDR_BROADCAST
4345 PyModule_AddIntConstant(m
, "INADDR_BROADCAST", INADDR_BROADCAST
);
4347 PyModule_AddIntConstant(m
, "INADDR_BROADCAST", 0xffffffff);
4349 #ifdef INADDR_LOOPBACK
4350 PyModule_AddIntConstant(m
, "INADDR_LOOPBACK", INADDR_LOOPBACK
);
4352 PyModule_AddIntConstant(m
, "INADDR_LOOPBACK", 0x7F000001);
4354 #ifdef INADDR_UNSPEC_GROUP
4355 PyModule_AddIntConstant(m
, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP
);
4357 PyModule_AddIntConstant(m
, "INADDR_UNSPEC_GROUP", 0xe0000000);
4359 #ifdef INADDR_ALLHOSTS_GROUP
4360 PyModule_AddIntConstant(m
, "INADDR_ALLHOSTS_GROUP",
4361 INADDR_ALLHOSTS_GROUP
);
4363 PyModule_AddIntConstant(m
, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
4365 #ifdef INADDR_MAX_LOCAL_GROUP
4366 PyModule_AddIntConstant(m
, "INADDR_MAX_LOCAL_GROUP",
4367 INADDR_MAX_LOCAL_GROUP
);
4369 PyModule_AddIntConstant(m
, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
4372 PyModule_AddIntConstant(m
, "INADDR_NONE", INADDR_NONE
);
4374 PyModule_AddIntConstant(m
, "INADDR_NONE", 0xffffffff);
4377 /* IPv4 [gs]etsockopt options */
4379 PyModule_AddIntConstant(m
, "IP_OPTIONS", IP_OPTIONS
);
4382 PyModule_AddIntConstant(m
, "IP_HDRINCL", IP_HDRINCL
);
4385 PyModule_AddIntConstant(m
, "IP_TOS", IP_TOS
);
4388 PyModule_AddIntConstant(m
, "IP_TTL", IP_TTL
);
4391 PyModule_AddIntConstant(m
, "IP_RECVOPTS", IP_RECVOPTS
);
4393 #ifdef IP_RECVRETOPTS
4394 PyModule_AddIntConstant(m
, "IP_RECVRETOPTS", IP_RECVRETOPTS
);
4396 #ifdef IP_RECVDSTADDR
4397 PyModule_AddIntConstant(m
, "IP_RECVDSTADDR", IP_RECVDSTADDR
);
4400 PyModule_AddIntConstant(m
, "IP_RETOPTS", IP_RETOPTS
);
4402 #ifdef IP_MULTICAST_IF
4403 PyModule_AddIntConstant(m
, "IP_MULTICAST_IF", IP_MULTICAST_IF
);
4405 #ifdef IP_MULTICAST_TTL
4406 PyModule_AddIntConstant(m
, "IP_MULTICAST_TTL", IP_MULTICAST_TTL
);
4408 #ifdef IP_MULTICAST_LOOP
4409 PyModule_AddIntConstant(m
, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP
);
4411 #ifdef IP_ADD_MEMBERSHIP
4412 PyModule_AddIntConstant(m
, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP
);
4414 #ifdef IP_DROP_MEMBERSHIP
4415 PyModule_AddIntConstant(m
, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP
);
4417 #ifdef IP_DEFAULT_MULTICAST_TTL
4418 PyModule_AddIntConstant(m
, "IP_DEFAULT_MULTICAST_TTL",
4419 IP_DEFAULT_MULTICAST_TTL
);
4421 #ifdef IP_DEFAULT_MULTICAST_LOOP
4422 PyModule_AddIntConstant(m
, "IP_DEFAULT_MULTICAST_LOOP",
4423 IP_DEFAULT_MULTICAST_LOOP
);
4425 #ifdef IP_MAX_MEMBERSHIPS
4426 PyModule_AddIntConstant(m
, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS
);
4429 /* IPv6 [gs]etsockopt options, defined in RFC2553 */
4430 #ifdef IPV6_JOIN_GROUP
4431 PyModule_AddIntConstant(m
, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP
);
4433 #ifdef IPV6_LEAVE_GROUP
4434 PyModule_AddIntConstant(m
, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP
);
4436 #ifdef IPV6_MULTICAST_HOPS
4437 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS
);
4439 #ifdef IPV6_MULTICAST_IF
4440 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF
);
4442 #ifdef IPV6_MULTICAST_LOOP
4443 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP
);
4445 #ifdef IPV6_UNICAST_HOPS
4446 PyModule_AddIntConstant(m
, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS
);
4448 /* Additional IPV6 socket options, defined in RFC 3493 */
4450 PyModule_AddIntConstant(m
, "IPV6_V6ONLY", IPV6_V6ONLY
);
4452 /* Advanced IPV6 socket options, from RFC 3542 */
4453 #ifdef IPV6_CHECKSUM
4454 PyModule_AddIntConstant(m
, "IPV6_CHECKSUM", IPV6_CHECKSUM
);
4456 #ifdef IPV6_DONTFRAG
4457 PyModule_AddIntConstant(m
, "IPV6_DONTFRAG", IPV6_DONTFRAG
);
4460 PyModule_AddIntConstant(m
, "IPV6_DSTOPTS", IPV6_DSTOPTS
);
4462 #ifdef IPV6_HOPLIMIT
4463 PyModule_AddIntConstant(m
, "IPV6_HOPLIMIT", IPV6_HOPLIMIT
);
4466 PyModule_AddIntConstant(m
, "IPV6_HOPOPTS", IPV6_HOPOPTS
);
4469 PyModule_AddIntConstant(m
, "IPV6_NEXTHOP", IPV6_NEXTHOP
);
4472 PyModule_AddIntConstant(m
, "IPV6_PATHMTU", IPV6_PATHMTU
);
4475 PyModule_AddIntConstant(m
, "IPV6_PKTINFO", IPV6_PKTINFO
);
4477 #ifdef IPV6_RECVDSTOPTS
4478 PyModule_AddIntConstant(m
, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS
);
4480 #ifdef IPV6_RECVHOPLIMIT
4481 PyModule_AddIntConstant(m
, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT
);
4483 #ifdef IPV6_RECVHOPOPTS
4484 PyModule_AddIntConstant(m
, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS
);
4486 #ifdef IPV6_RECVPKTINFO
4487 PyModule_AddIntConstant(m
, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO
);
4489 #ifdef IPV6_RECVRTHDR
4490 PyModule_AddIntConstant(m
, "IPV6_RECVRTHDR", IPV6_RECVRTHDR
);
4492 #ifdef IPV6_RECVTCLASS
4493 PyModule_AddIntConstant(m
, "IPV6_RECVTCLASS", IPV6_RECVTCLASS
);
4496 PyModule_AddIntConstant(m
, "IPV6_RTHDR", IPV6_RTHDR
);
4498 #ifdef IPV6_RTHDRDSTOPTS
4499 PyModule_AddIntConstant(m
, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS
);
4501 #ifdef IPV6_RTHDR_TYPE_0
4502 PyModule_AddIntConstant(m
, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0
);
4504 #ifdef IPV6_RECVPATHMTU
4505 PyModule_AddIntConstant(m
, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU
);
4508 PyModule_AddIntConstant(m
, "IPV6_TCLASS", IPV6_TCLASS
);
4510 #ifdef IPV6_USE_MIN_MTU
4511 PyModule_AddIntConstant(m
, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU
);
4516 PyModule_AddIntConstant(m
, "TCP_NODELAY", TCP_NODELAY
);
4519 PyModule_AddIntConstant(m
, "TCP_MAXSEG", TCP_MAXSEG
);
4522 PyModule_AddIntConstant(m
, "TCP_CORK", TCP_CORK
);
4525 PyModule_AddIntConstant(m
, "TCP_KEEPIDLE", TCP_KEEPIDLE
);
4527 #ifdef TCP_KEEPINTVL
4528 PyModule_AddIntConstant(m
, "TCP_KEEPINTVL", TCP_KEEPINTVL
);
4531 PyModule_AddIntConstant(m
, "TCP_KEEPCNT", TCP_KEEPCNT
);
4534 PyModule_AddIntConstant(m
, "TCP_SYNCNT", TCP_SYNCNT
);
4537 PyModule_AddIntConstant(m
, "TCP_LINGER2", TCP_LINGER2
);
4539 #ifdef TCP_DEFER_ACCEPT
4540 PyModule_AddIntConstant(m
, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT
);
4542 #ifdef TCP_WINDOW_CLAMP
4543 PyModule_AddIntConstant(m
, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP
);
4546 PyModule_AddIntConstant(m
, "TCP_INFO", TCP_INFO
);
4549 PyModule_AddIntConstant(m
, "TCP_QUICKACK", TCP_QUICKACK
);
4555 PyModule_AddIntConstant(m
, "IPX_TYPE", IPX_TYPE
);
4558 /* get{addr,name}info parameters */
4559 #ifdef EAI_ADDRFAMILY
4560 PyModule_AddIntConstant(m
, "EAI_ADDRFAMILY", EAI_ADDRFAMILY
);
4563 PyModule_AddIntConstant(m
, "EAI_AGAIN", EAI_AGAIN
);
4566 PyModule_AddIntConstant(m
, "EAI_BADFLAGS", EAI_BADFLAGS
);
4569 PyModule_AddIntConstant(m
, "EAI_FAIL", EAI_FAIL
);
4572 PyModule_AddIntConstant(m
, "EAI_FAMILY", EAI_FAMILY
);
4575 PyModule_AddIntConstant(m
, "EAI_MEMORY", EAI_MEMORY
);
4578 PyModule_AddIntConstant(m
, "EAI_NODATA", EAI_NODATA
);
4581 PyModule_AddIntConstant(m
, "EAI_NONAME", EAI_NONAME
);
4584 PyModule_AddIntConstant(m
, "EAI_OVERFLOW", EAI_OVERFLOW
);
4587 PyModule_AddIntConstant(m
, "EAI_SERVICE", EAI_SERVICE
);
4590 PyModule_AddIntConstant(m
, "EAI_SOCKTYPE", EAI_SOCKTYPE
);
4593 PyModule_AddIntConstant(m
, "EAI_SYSTEM", EAI_SYSTEM
);
4596 PyModule_AddIntConstant(m
, "EAI_BADHINTS", EAI_BADHINTS
);
4599 PyModule_AddIntConstant(m
, "EAI_PROTOCOL", EAI_PROTOCOL
);
4602 PyModule_AddIntConstant(m
, "EAI_MAX", EAI_MAX
);
4605 PyModule_AddIntConstant(m
, "AI_PASSIVE", AI_PASSIVE
);
4608 PyModule_AddIntConstant(m
, "AI_CANONNAME", AI_CANONNAME
);
4610 #ifdef AI_NUMERICHOST
4611 PyModule_AddIntConstant(m
, "AI_NUMERICHOST", AI_NUMERICHOST
);
4613 #ifdef AI_NUMERICSERV
4614 PyModule_AddIntConstant(m
, "AI_NUMERICSERV", AI_NUMERICSERV
);
4617 PyModule_AddIntConstant(m
, "AI_MASK", AI_MASK
);
4620 PyModule_AddIntConstant(m
, "AI_ALL", AI_ALL
);
4622 #ifdef AI_V4MAPPED_CFG
4623 PyModule_AddIntConstant(m
, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG
);
4625 #ifdef AI_ADDRCONFIG
4626 PyModule_AddIntConstant(m
, "AI_ADDRCONFIG", AI_ADDRCONFIG
);
4629 PyModule_AddIntConstant(m
, "AI_V4MAPPED", AI_V4MAPPED
);
4632 PyModule_AddIntConstant(m
, "AI_DEFAULT", AI_DEFAULT
);
4635 PyModule_AddIntConstant(m
, "NI_MAXHOST", NI_MAXHOST
);
4638 PyModule_AddIntConstant(m
, "NI_MAXSERV", NI_MAXSERV
);
4641 PyModule_AddIntConstant(m
, "NI_NOFQDN", NI_NOFQDN
);
4643 #ifdef NI_NUMERICHOST
4644 PyModule_AddIntConstant(m
, "NI_NUMERICHOST", NI_NUMERICHOST
);
4647 PyModule_AddIntConstant(m
, "NI_NAMEREQD", NI_NAMEREQD
);
4649 #ifdef NI_NUMERICSERV
4650 PyModule_AddIntConstant(m
, "NI_NUMERICSERV", NI_NUMERICSERV
);
4653 PyModule_AddIntConstant(m
, "NI_DGRAM", NI_DGRAM
);
4656 /* shutdown() parameters */
4658 PyModule_AddIntConstant(m
, "SHUT_RD", SHUT_RD
);
4659 #elif defined(SD_RECEIVE)
4660 PyModule_AddIntConstant(m
, "SHUT_RD", SD_RECEIVE
);
4662 PyModule_AddIntConstant(m
, "SHUT_RD", 0);
4665 PyModule_AddIntConstant(m
, "SHUT_WR", SHUT_WR
);
4666 #elif defined(SD_SEND)
4667 PyModule_AddIntConstant(m
, "SHUT_WR", SD_SEND
);
4669 PyModule_AddIntConstant(m
, "SHUT_WR", 1);
4672 PyModule_AddIntConstant(m
, "SHUT_RDWR", SHUT_RDWR
);
4673 #elif defined(SD_BOTH)
4674 PyModule_AddIntConstant(m
, "SHUT_RDWR", SD_BOTH
);
4676 PyModule_AddIntConstant(m
, "SHUT_RDWR", 2);
4679 /* Initialize gethostbyname lock */
4680 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
4681 netdb_lock
= PyThread_allocate_lock();
4686 #ifndef HAVE_INET_PTON
4688 /* Simplistic emulation code for inet_pton that only works for IPv4 */
4689 /* These are not exposed because they do not set errno properly */
4692 inet_pton(int af
, const char *src
, void *dst
)
4694 if (af
== AF_INET
) {
4696 packed_addr
= inet_addr(src
);
4697 if (packed_addr
== INADDR_NONE
)
4699 memcpy(dst
, &packed_addr
, 4);
4702 /* Should set errno to EAFNOSUPPORT */
4707 inet_ntop(int af
, const void *src
, char *dst
, socklen_t size
)
4709 if (af
== AF_INET
) {
4710 struct in_addr packed_addr
;
4712 /* Should set errno to ENOSPC. */
4714 memcpy(&packed_addr
, src
, sizeof(packed_addr
));
4715 return strncpy(dst
, inet_ntoa(packed_addr
), size
);
4717 /* Should set errno to EAFNOSUPPORT */