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, AF_NETLINK and AF_TIPC are supported
12 - No read/write operations (use sendall/recv or makefile instead).
13 - Additional restrictions apply on some non-Unix platforms (compensated
18 - socket.error: exception raised for socket specific errors
19 - socket.gaierror: exception raised for getaddrinfo/getnameinfo errors,
20 a subclass of socket.error
21 - socket.herror: exception raised for gethostby* errors,
22 a subclass of socket.error
23 - socket.fromfd(fd, family, type[, proto]) --> new socket object (created
24 from an existing file descriptor)
25 - socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')
26 - socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])
27 - socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com')
28 - socket.getprotobyname(protocolname) --> protocol number
29 - socket.getservbyname(servicename[, protocolname]) --> port number
30 - socket.getservbyport(portnumber[, protocolname]) --> service name
31 - socket.socket([family[, type [, proto]]]) --> new socket object
32 - socket.socketpair([family[, type [, proto]]]) --> (socket, socket)
33 - socket.ntohs(16 bit value) --> new int object
34 - socket.ntohl(32 bit value) --> new int object
35 - socket.htons(16 bit value) --> new int object
36 - socket.htonl(32 bit value) --> new int object
37 - socket.getaddrinfo(host, port [, family, socktype, proto, flags])
38 --> List of (family, socktype, proto, canonname, sockaddr)
39 - socket.getnameinfo(sockaddr, flags) --> (host, port)
40 - socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
41 - socket.has_ipv6: boolean value indicating if IPv6 is supported
42 - socket.inet_aton(IP address) -> 32-bit packed IP representation
43 - socket.inet_ntoa(packed IP) -> IP address string
44 - socket.getdefaulttimeout() -> None | float
45 - socket.setdefaulttimeout(None | float)
46 - an Internet socket address is a pair (hostname, port)
47 where hostname can be anything recognized by gethostbyname()
48 (including the dd.dd.dd.dd notation) and port is in host byte order
49 - where a hostname is returned, the dd.dd.dd.dd notation is used
50 - a UNIX domain socket address is a string specifying the pathname
51 - an AF_PACKET socket address is a tuple containing a string
52 specifying the ethernet interface and an integer specifying
53 the Ethernet protocol number to be received. For example:
54 ("eth0",0x1234). Optional 3rd,4th,5th elements in the tuple
55 specify packet-type and ha-type/addr.
56 - an AF_TIPC socket address is expressed as
57 (addr_type, v1, v2, v3 [, scope]); where addr_type can be one of:
58 TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, and TIPC_ADDR_ID;
59 and scope can be one of:
60 TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and TIPC_NODE_SCOPE.
61 The meaning of v1, v2 and v3 depends on the value of addr_type:
62 if addr_type is TIPC_ADDR_NAME:
64 v2 is the port identifier
66 if addr_type is TIPC_ADDR_NAMESEQ:
68 v2 is the lower port number
69 v3 is the upper port number
70 if addr_type is TIPC_ADDR_ID:
76 Local naming conventions:
78 - names starting with sock_ are socket object methods
79 - names starting with socket_ are module-level functions
80 - names starting with PySocket are exported through socketmodule.h
86 * inet_aton is not available on OSX 10.3, yet we want to use a binary
87 * that was build on 10.4 or later to work on that release, weak linking
88 * comes to the rescue.
90 # pragma weak inet_aton
94 #include "structmember.h"
95 #include "timefuncs.h"
97 #ifndef INVALID_SOCKET /* MS defines this */
98 #define INVALID_SOCKET (-1)
102 #define MAX(x, y) ((x) < (y) ? (y) : (x))
104 /* Socket object documentation */
105 PyDoc_STRVAR(sock_doc
,
106 "socket([family[, type[, proto]]]) -> socket object\n\
108 Open a socket of the given type. The family argument specifies the\n\
109 address family; it defaults to AF_INET. The type argument specifies\n\
110 whether this is a stream (SOCK_STREAM, this is the default)\n\
111 or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0,\n\
112 specifying the default protocol. Keyword arguments are accepted.\n\
114 A socket object represents one endpoint of a network connection.\n\
116 Methods of socket objects (keyword arguments not allowed):\n\
118 accept() -- accept a connection, returning new socket and client address\n\
119 bind(addr) -- bind the socket to a local address\n\
120 close() -- close the socket\n\
121 connect(addr) -- connect the socket to a remote address\n\
122 connect_ex(addr) -- connect, return an error code instead of an exception\n\
123 dup() -- return a new socket object identical to the current one [*]\n\
124 fileno() -- return underlying file descriptor\n\
125 getpeername() -- return remote address [*]\n\
126 getsockname() -- return local address\n\
127 getsockopt(level, optname[, buflen]) -- get socket options\n\
128 gettimeout() -- return timeout or None\n\
129 listen(n) -- start listening for incoming connections\n\
130 makefile([mode, [bufsize]]) -- return a file object for the socket [*]\n\
131 recv(buflen[, flags]) -- receive data\n\
132 recv_into(buffer[, nbytes[, flags]]) -- receive data (into a buffer)\n\
133 recvfrom(buflen[, flags]) -- receive data and sender\'s address\n\
134 recvfrom_into(buffer[, nbytes, [, flags])\n\
135 -- receive data and sender\'s address (into a buffer)\n\
136 sendall(data[, flags]) -- send all data\n\
137 send(data[, flags]) -- send data, may not send all of it\n\
138 sendto(data[, flags], addr) -- send data to a given address\n\
139 setblocking(0 | 1) -- set or clear the blocking I/O flag\n\
140 setsockopt(level, optname, value) -- set socket options\n\
141 settimeout(None | float) -- set or clear the timeout\n\
142 shutdown(how) -- shut down traffic in one or both directions\n\
144 [*] not available on all platforms!");
146 /* XXX This is a terrible mess of platform-dependent preprocessor hacks.
147 I hope some day someone can clean this up please... */
149 /* Hacks for gethostbyname_r(). On some non-Linux platforms, the configure
150 script doesn't get this right, so we hardcode some platform checks below.
151 On the other hand, not all Linux versions agree, so there the settings
152 computed by the configure script are needed! */
155 # undef HAVE_GETHOSTBYNAME_R_3_ARG
156 # undef HAVE_GETHOSTBYNAME_R_5_ARG
157 # undef HAVE_GETHOSTBYNAME_R_6_ARG
161 # undef HAVE_GETHOSTBYNAME_R
164 #ifdef HAVE_GETHOSTBYNAME_R
165 # if defined(_AIX) || defined(__osf__)
166 # define HAVE_GETHOSTBYNAME_R_3_ARG
167 # elif defined(__sun) || defined(__sgi)
168 # define HAVE_GETHOSTBYNAME_R_5_ARG
169 # elif defined(linux)
170 /* Rely on the configure script */
172 # undef HAVE_GETHOSTBYNAME_R
176 #if !defined(HAVE_GETHOSTBYNAME_R) && defined(WITH_THREAD) && \
178 # define USE_GETHOSTBYNAME_LOCK
181 /* To use __FreeBSD_version */
182 #ifdef HAVE_SYS_PARAM_H
183 #include <sys/param.h>
185 /* On systems on which getaddrinfo() is believed to not be thread-safe,
186 (this includes the getaddrinfo emulation) protect access with a lock. */
187 #if defined(WITH_THREAD) && (defined(__APPLE__) || \
188 (defined(__FreeBSD__) && __FreeBSD_version+0 < 503000) || \
189 defined(__OpenBSD__) || defined(__NetBSD__) || \
190 defined(__VMS) || !defined(HAVE_GETADDRINFO))
191 #define USE_GETADDRINFO_LOCK
194 #ifdef USE_GETADDRINFO_LOCK
195 #define ACQUIRE_GETADDRINFO_LOCK PyThread_acquire_lock(netdb_lock, 1);
196 #define RELEASE_GETADDRINFO_LOCK PyThread_release_lock(netdb_lock);
198 #define ACQUIRE_GETADDRINFO_LOCK
199 #define RELEASE_GETADDRINFO_LOCK
202 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
203 # include "pythread.h"
206 #if defined(PYCC_VACPP)
209 # include <sys/ioctl.h>
218 #if defined(PYOS_OS2)
220 # define INCL_DOSERRORS
221 # define INCL_NOPMAPI
225 #if defined(__sgi) && _COMPILER_VERSION>700 && !_SGIAPI
226 /* make sure that the reentrant (gethostbyaddr_r etc)
227 functions are declared correctly if compiling with
228 MIPSPro 7.x in ANSI C mode (default) */
230 /* XXX Using _SGIAPI is the wrong thing,
231 but I don't know what the right thing is. */
232 #undef _SGIAPI /* to avoid warning */
236 #include <sys/socket.h>
237 #include <sys/types.h>
238 #include <netinet/in.h>
240 #define HAVE_GETADDRINFO 1
241 #define HAVE_GETNAMEINFO 1
244 #define HAVE_INET_PTON
248 /* Irix 6.5 fails to define this variable at all. This is needed
249 for both GCC and SGI's compiler. I'd say that the SGI headers
250 are just busted. Same thing for Solaris. */
251 #if (defined(__sgi) || defined(sun)) && !defined(INET_ADDRSTRLEN)
252 #define INET_ADDRSTRLEN 16
255 /* Generic includes */
256 #ifdef HAVE_SYS_TYPES_H
257 #include <sys/types.h>
260 /* Generic socket object definitions and includes */
261 #define PySocket_BUILDING_SOCKET
262 #include "socketmodule.h"
264 /* Addressing includes */
268 /* Non-MS WINDOWS includes */
271 /* Headers needed for inet_ntoa() and inet_addr() */
273 # include <net/netdb.h>
274 # elif defined(PYOS_OS2) && defined(PYCC_VACPP)
276 typedef size_t socklen_t
;
278 # include <arpa/inet.h>
284 # include <sys/ioctl.h>
285 # include <socklib.h>
287 int h_errno
; /* not used */
288 # define INET_ADDRSTRLEN 16
293 /* MS_WINDOWS includes */
303 # define offsetof(type, member) ((size_t)(&((type *)0)->member))
307 # define O_NONBLOCK O_NDELAY
310 /* include Python's addrinfo.h unless it causes trouble */
311 #if defined(__sgi) && _COMPILER_VERSION>700 && defined(_SS_ALIGNSIZE)
312 /* Do not include addinfo.h on some newer IRIX versions.
313 * _SS_ALIGNSIZE is defined in sys/socket.h by 6.5.21,
314 * for example, but not by 6.5.10.
316 #elif defined(_MSC_VER) && _MSC_VER>1201
317 /* Do not include addrinfo.h for MSVC7 or greater. 'addrinfo' and
318 * EAI_* constants are defined in (the already included) ws2tcpip.h.
321 # include "addrinfo.h"
324 #ifndef HAVE_INET_PTON
325 #if !defined(NTDDI_VERSION) || (NTDDI_VERSION < NTDDI_LONGHORN)
326 int inet_pton(int af
, const char *src
, void *dst
);
327 const char *inet_ntop(int af
, const void *src
, char *dst
, socklen_t size
);
332 /* On OS X, getaddrinfo returns no error indication of lookup
333 failure, so we must use the emulation instead of the libinfo
334 implementation. Unfortunately, performing an autoconf test
335 for this bug would require DNS access for the machine performing
336 the configuration, which is not acceptable. Therefore, we
337 determine the bug just by checking for __APPLE__. If this bug
338 gets ever fixed, perhaps checking for sys/version.h would be
339 appropriate, which is 10/0 on the system with the bug. */
340 #ifndef HAVE_GETNAMEINFO
341 /* This bug seems to be fixed in Jaguar. Ths easiest way I could
342 Find to check for Jaguar is that it has getnameinfo(), which
343 older releases don't have */
344 #undef HAVE_GETADDRINFO
347 #ifdef HAVE_INET_ATON
348 #define USE_INET_ATON_WEAKLINK
353 /* I know this is a bad practice, but it is the easiest... */
354 #if !defined(HAVE_GETADDRINFO)
355 /* avoid clashes with the C library definition of the symbol. */
356 #define getaddrinfo fake_getaddrinfo
357 #define gai_strerror fake_gai_strerror
358 #define freeaddrinfo fake_freeaddrinfo
359 #include "getaddrinfo.c"
361 #if !defined(HAVE_GETNAMEINFO)
362 #define getnameinfo fake_getnameinfo
363 #include "getnameinfo.c"
366 #if defined(MS_WINDOWS) || defined(__BEOS__)
367 /* BeOS suffers from the same socket dichotomy as Win32... - [cjh] */
368 /* seem to be a few differences in the API */
369 #define SOCKETCLOSE closesocket
370 #define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */
374 #define EAFNOSUPPORT WSAEAFNOSUPPORT
375 #define snprintf _snprintf
378 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
379 #define SOCKETCLOSE soclose
380 #define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
384 #define SOCKETCLOSE close
387 #if (defined(HAVE_BLUETOOTH_H) || defined(HAVE_BLUETOOTH_BLUETOOTH_H)) && !defined(__NetBSD__) && !defined(__DragonFly__)
388 #define USE_BLUETOOTH 1
389 #if defined(__FreeBSD__)
390 #define BTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP
391 #define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM
392 #define BTPROTO_HCI BLUETOOTH_PROTO_HCI
393 #define SOL_HCI SOL_HCI_RAW
394 #define HCI_FILTER SO_HCI_RAW_FILTER
395 #define sockaddr_l2 sockaddr_l2cap
396 #define sockaddr_rc sockaddr_rfcomm
397 #define hci_dev hci_node
398 #define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb)
399 #define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)
400 #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
401 #elif defined(__NetBSD__) || defined(__DragonFly__)
402 #define sockaddr_l2 sockaddr_bt
403 #define sockaddr_rc sockaddr_bt
404 #define sockaddr_hci sockaddr_bt
405 #define sockaddr_sco sockaddr_bt
406 #define SOL_HCI BTPROTO_HCI
407 #define HCI_DATA_DIR SO_HCI_DIRECTION
408 #define _BT_L2_MEMB(sa, memb) ((sa)->bt_##memb)
409 #define _BT_RC_MEMB(sa, memb) ((sa)->bt_##memb)
410 #define _BT_HCI_MEMB(sa, memb) ((sa)->bt_##memb)
411 #define _BT_SCO_MEMB(sa, memb) ((sa)->bt_##memb)
413 #define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb)
414 #define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb)
415 #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
416 #define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)
421 /* TCP/IP Services for VMS uses a maximum send/recv buffer length */
422 #define SEGMENT_SIZE (32 * 1024 -1)
425 #define SAS2SA(x) ((struct sockaddr *)(x))
428 * Constants for getnameinfo()
430 #if !defined(NI_MAXHOST)
431 #define NI_MAXHOST 1025
433 #if !defined(NI_MAXSERV)
434 #define NI_MAXSERV 32
437 /* XXX There's a problem here: *static* functions are not supposed to have
438 a Py prefix (or use CapitalizedWords). Later... */
440 /* Global variable holding the exception type for errors detected
441 by this module (but not argument type or memory errors, etc.). */
442 static PyObject
*socket_error
;
443 static PyObject
*socket_herror
;
444 static PyObject
*socket_gaierror
;
445 static PyObject
*socket_timeout
;
448 /* Global variable which is !=0 if Python is running in a RISC OS taskwindow */
449 static int taskwindow
;
452 /* A forward reference to the socket type object.
453 The sock_type variable contains pointers to various functions,
454 some of which call new_sockobject(), which uses sock_type, so
455 there has to be a circular reference. */
456 static PyTypeObject sock_type
;
458 #if defined(HAVE_POLL_H)
460 #elif defined(HAVE_SYS_POLL_H)
461 #include <sys/poll.h>
465 /* Instead of select(), we'll use poll() since poll() works on any fd. */
466 #define IS_SELECTABLE(s) 1
467 /* Can we call select() with this socket without a buffer overrun? */
469 /* If there's no timeout left, we don't have to call select, so it's a safe,
470 * little white lie. */
471 #define IS_SELECTABLE(s) (_PyIsSelectable_fd((s)->sock_fd) || (s)->sock_timeout <= 0.0)
477 PyErr_SetString(socket_error
, "unable to select on socket");
483 #define WSAEAGAIN WSAEWOULDBLOCK
485 #define CHECK_ERRNO(expected) \
486 (WSAGetLastError() == WSA ## expected)
488 #define CHECK_ERRNO(expected) \
492 /* Convenience function to raise an error according to errno
493 and return a NULL pointer from a function. */
499 int err_no
= WSAGetLastError();
500 /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which
501 recognizes the error codes used by both GetLastError() and
504 return PyErr_SetExcFromWindowsErr(socket_error
, err_no
);
507 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
508 if (sock_errno() != NO_ERROR
) {
512 int myerrorcode
= sock_errno();
514 /* Retrieve socket-related error message from MPTN.MSG file */
515 rc
= DosGetMessage(NULL
, 0, outbuf
, sizeof(outbuf
),
516 myerrorcode
- SOCBASEERR
+ 26,
519 if (rc
== NO_ERROR
) {
522 /* OS/2 doesn't guarantee a terminator */
523 outbuf
[msglen
] = '\0';
524 if (strlen(outbuf
) > 0) {
525 /* If non-empty msg, trim CRLF */
526 char *lastc
= &outbuf
[ strlen(outbuf
)-1 ];
527 while (lastc
> outbuf
&&
528 isspace(Py_CHARMASK(*lastc
))) {
529 /* Trim trailing whitespace (CRLF) */
533 v
= Py_BuildValue("(is)", myerrorcode
, outbuf
);
535 PyErr_SetObject(socket_error
, v
);
544 if (_inet_error
.errnum
!= NULL
) {
546 v
= Py_BuildValue("(is)", errno
, _inet_err());
548 PyErr_SetObject(socket_error
, v
);
555 return PyErr_SetFromErrno(socket_error
);
560 set_herror(int h_error
)
564 #ifdef HAVE_HSTRERROR
565 v
= Py_BuildValue("(is)", h_error
, (char *)hstrerror(h_error
));
567 v
= Py_BuildValue("(is)", h_error
, "host not found");
570 PyErr_SetObject(socket_herror
, v
);
579 set_gaierror(int error
)
584 /* EAI_SYSTEM is not available on Windows XP. */
585 if (error
== EAI_SYSTEM
)
589 #ifdef HAVE_GAI_STRERROR
590 v
= Py_BuildValue("(is)", error
, gai_strerror(error
));
592 v
= Py_BuildValue("(is)", error
, "getaddrinfo failed");
595 PyErr_SetObject(socket_gaierror
, v
);
603 /* Function to send in segments */
605 sendsegmented(int sock_fd
, char *buf
, int len
, int flags
)
610 while (remaining
> 0) {
611 unsigned int segment
;
613 segment
= (remaining
>= SEGMENT_SIZE
? SEGMENT_SIZE
: remaining
);
614 n
= send(sock_fd
, buf
, segment
, flags
);
618 remaining
-= segment
;
626 /* Function to perform the setting of socket blocking mode
627 internally. block = (1 | 0). */
629 internal_setblocking(PySocketSockObject
*s
, int block
)
637 Py_BEGIN_ALLOW_THREADS
640 setsockopt(s
->sock_fd
, SOL_SOCKET
, SO_NONBLOCK
,
641 (void *)(&block
), sizeof(int));
645 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
647 ioctl(s
->sock_fd
, FIONBIO
, (caddr_t
)&block
, sizeof(block
));
650 ioctl(s
->sock_fd
, FIONBIO
, (unsigned int *)&block
);
651 #else /* !PYOS_OS2 && !__VMS */
652 delay_flag
= fcntl(s
->sock_fd
, F_GETFL
, 0);
654 delay_flag
&= (~O_NONBLOCK
);
656 delay_flag
|= O_NONBLOCK
;
657 fcntl(s
->sock_fd
, F_SETFL
, delay_flag
);
658 #endif /* !PYOS_OS2 */
659 #else /* MS_WINDOWS */
661 ioctlsocket(s
->sock_fd
, FIONBIO
, (u_long
*)&block
);
662 #endif /* MS_WINDOWS */
665 socketioctl(s
->sock_fd
, FIONBIO
, (u_long
*)&block
);
667 #endif /* __BEOS__ */
670 /* Since these don't return anything */
674 /* Do a select()/poll() on the socket, if necessary (sock_timeout > 0).
675 The argument writing indicates the direction.
676 This does not raise an exception; we'll let our caller do that
677 after they've reacquired the interpreter lock.
678 Returns 1 on timeout, -1 on error, 0 otherwise. */
680 internal_select_ex(PySocketSockObject
*s
, int writing
, double interval
)
684 /* Nothing to do unless we're in timeout mode (not non-blocking) */
685 if (s
->sock_timeout
<= 0.0)
688 /* Guard against closed socket */
692 /* Handling this condition here simplifies the select loops */
696 /* Prefer poll, if available, since you can poll() any fd
697 * which can't be done with select(). */
700 struct pollfd pollfd
;
703 pollfd
.fd
= s
->sock_fd
;
704 pollfd
.events
= writing
? POLLOUT
: POLLIN
;
706 /* s->sock_timeout is in seconds, timeout in ms */
707 timeout
= (int)(interval
* 1000 + 0.5);
708 n
= poll(&pollfd
, 1, timeout
);
712 /* Construct the arguments to select */
715 tv
.tv_sec
= (int)interval
;
716 tv
.tv_usec
= (int)((interval
- tv
.tv_sec
) * 1e6
);
718 FD_SET(s
->sock_fd
, &fds
);
720 /* See if the socket is ready */
722 n
= select(s
->sock_fd
+1, NULL
, &fds
, NULL
, &tv
);
724 n
= select(s
->sock_fd
+1, &fds
, NULL
, NULL
, &tv
);
736 internal_select(PySocketSockObject
*s
, int writing
)
738 return internal_select_ex(s
, writing
, s
->sock_timeout
);
742 Two macros for automatic retry of select() in case of false positives
743 (for example, select() could indicate a socket is ready for reading
744 but the data then discarded by the OS because of a wrong checksum).
745 Here is an example of use:
748 Py_BEGIN_ALLOW_THREADS
749 timeout = internal_select_ex(s, 0, interval);
751 outlen = recv(s->sock_fd, cbuf, len, flags);
754 PyErr_SetString(socket_timeout, "timed out");
759 #define BEGIN_SELECT_LOOP(s) \
761 double deadline, interval = s->sock_timeout; \
762 int has_timeout = s->sock_timeout > 0.0; \
764 deadline = _PyTime_FloatTime() + s->sock_timeout; \
769 #define END_SELECT_LOOP(s) \
770 if (!has_timeout || \
771 (!CHECK_ERRNO(EWOULDBLOCK) && !CHECK_ERRNO(EAGAIN))) \
773 interval = deadline - _PyTime_FloatTime(); \
777 /* Initialize a new socket object. */
779 static double defaulttimeout
= -1.0; /* Default timeout for new sockets */
782 init_sockobject(PySocketSockObject
*s
,
783 SOCKET_T fd
, int family
, int type
, int proto
)
789 s
->sock_family
= family
;
791 s
->sock_proto
= proto
;
792 s
->sock_timeout
= defaulttimeout
;
794 s
->errorhandler
= &set_error
;
796 if (defaulttimeout
>= 0.0)
797 internal_setblocking(s
, 0);
801 socketioctl(s
->sock_fd
, 0x80046679, (u_long
*)&block
);
806 /* Create a new socket object.
807 This just creates the object and initializes it.
808 If the creation fails, return NULL and set an exception (implicit
811 static PySocketSockObject
*
812 new_sockobject(SOCKET_T fd
, int family
, int type
, int proto
)
814 PySocketSockObject
*s
;
815 s
= (PySocketSockObject
*)
816 PyType_GenericNew(&sock_type
, NULL
, NULL
);
818 init_sockobject(s
, fd
, family
, type
, proto
);
823 /* Lock to allow python interpreter to continue, but only allow one
824 thread to be in gethostbyname or getaddrinfo */
825 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
826 static PyThread_type_lock netdb_lock
;
830 /* Convert a string specifying a host name or one of a few symbolic
831 names to a numeric IP address. This usually calls gethostbyname()
832 to do the work; the names "" and "<broadcast>" are special.
833 Return the length (IPv4 should be 4 bytes), or negative if
834 an error occurred; then an exception is raised. */
837 setipaddr(char *name
, struct sockaddr
*addr_ret
, size_t addr_ret_size
, int af
)
839 struct addrinfo hints
, *res
;
844 memset((void *) addr_ret
, '\0', sizeof(*addr_ret
));
845 if (name
[0] == '\0') {
847 memset(&hints
, 0, sizeof(hints
));
848 hints
.ai_family
= af
;
849 hints
.ai_socktype
= SOCK_DGRAM
; /*dummy*/
850 hints
.ai_flags
= AI_PASSIVE
;
851 Py_BEGIN_ALLOW_THREADS
852 ACQUIRE_GETADDRINFO_LOCK
853 error
= getaddrinfo(NULL
, "0", &hints
, &res
);
855 /* We assume that those thread-unsafe getaddrinfo() versions
856 *are* safe regarding their return value, ie. that a
857 subsequent call to getaddrinfo() does not destroy the
858 outcome of the first call. */
859 RELEASE_GETADDRINFO_LOCK
864 switch (res
->ai_family
) {
875 PyErr_SetString(socket_error
,
876 "unsupported address family");
881 PyErr_SetString(socket_error
,
882 "wildcard resolved to multiple address");
885 if (res
->ai_addrlen
< addr_ret_size
)
886 addr_ret_size
= res
->ai_addrlen
;
887 memcpy(addr_ret
, res
->ai_addr
, addr_ret_size
);
891 if (name
[0] == '<' && strcmp(name
, "<broadcast>") == 0) {
892 struct sockaddr_in
*sin
;
893 if (af
!= AF_INET
&& af
!= AF_UNSPEC
) {
894 PyErr_SetString(socket_error
,
895 "address family mismatched");
898 sin
= (struct sockaddr_in
*)addr_ret
;
899 memset((void *) sin
, '\0', sizeof(*sin
));
900 sin
->sin_family
= AF_INET
;
901 #ifdef HAVE_SOCKADDR_SA_LEN
902 sin
->sin_len
= sizeof(*sin
);
904 sin
->sin_addr
.s_addr
= INADDR_BROADCAST
;
905 return sizeof(sin
->sin_addr
);
907 if (sscanf(name
, "%d.%d.%d.%d%c", &d1
, &d2
, &d3
, &d4
, &ch
) == 4 &&
908 0 <= d1
&& d1
<= 255 && 0 <= d2
&& d2
<= 255 &&
909 0 <= d3
&& d3
<= 255 && 0 <= d4
&& d4
<= 255) {
910 struct sockaddr_in
*sin
;
911 sin
= (struct sockaddr_in
*)addr_ret
;
912 sin
->sin_addr
.s_addr
= htonl(
913 ((long) d1
<< 24) | ((long) d2
<< 16) |
914 ((long) d3
<< 8) | ((long) d4
<< 0));
915 sin
->sin_family
= AF_INET
;
916 #ifdef HAVE_SOCKADDR_SA_LEN
917 sin
->sin_len
= sizeof(*sin
);
921 memset(&hints
, 0, sizeof(hints
));
922 hints
.ai_family
= af
;
923 Py_BEGIN_ALLOW_THREADS
924 ACQUIRE_GETADDRINFO_LOCK
925 error
= getaddrinfo(name
, NULL
, &hints
, &res
);
926 #if defined(__digital__) && defined(__unix__)
927 if (error
== EAI_NONAME
&& af
== AF_UNSPEC
) {
928 /* On Tru64 V5.1, numeric-to-addr conversion fails
929 if no address family is given. Assume IPv4 for now.*/
930 hints
.ai_family
= AF_INET
;
931 error
= getaddrinfo(name
, NULL
, &hints
, &res
);
935 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
940 if (res
->ai_addrlen
< addr_ret_size
)
941 addr_ret_size
= res
->ai_addrlen
;
942 memcpy((char *) addr_ret
, res
->ai_addr
, addr_ret_size
);
944 switch (addr_ret
->sa_family
) {
952 PyErr_SetString(socket_error
, "unknown address family");
958 /* Create a string object representing an IP address.
959 This is always a string of the form 'dd.dd.dd.dd' (with variable
963 makeipaddr(struct sockaddr
*addr
, int addrlen
)
965 char buf
[NI_MAXHOST
];
968 error
= getnameinfo(addr
, addrlen
, buf
, sizeof(buf
), NULL
, 0,
974 return PyString_FromString(buf
);
979 /* Convert a string representation of a Bluetooth address into a numeric
980 address. Returns the length (6), or raises an exception and returns -1 if
981 an error occurred. */
984 setbdaddr(char *name
, bdaddr_t
*bdaddr
)
986 unsigned int b0
, b1
, b2
, b3
, b4
, b5
;
990 n
= sscanf(name
, "%X:%X:%X:%X:%X:%X%c",
991 &b5
, &b4
, &b3
, &b2
, &b1
, &b0
, &ch
);
992 if (n
== 6 && (b0
| b1
| b2
| b3
| b4
| b5
) < 256) {
1001 PyErr_SetString(socket_error
, "bad bluetooth address");
1006 /* Create a string representation of the Bluetooth address. This is always a
1007 string of the form 'XX:XX:XX:XX:XX:XX' where XX is a two digit hexadecimal
1008 value (zero padded if necessary). */
1011 makebdaddr(bdaddr_t
*bdaddr
)
1013 char buf
[(6 * 2) + 5 + 1];
1015 sprintf(buf
, "%02X:%02X:%02X:%02X:%02X:%02X",
1016 bdaddr
->b
[5], bdaddr
->b
[4], bdaddr
->b
[3],
1017 bdaddr
->b
[2], bdaddr
->b
[1], bdaddr
->b
[0]);
1018 return PyString_FromString(buf
);
1023 /* Create an object representing the given socket address,
1024 suitable for passing it back to bind(), connect() etc.
1025 The family field of the sockaddr structure is inspected
1026 to determine what kind of address it really is. */
1030 makesockaddr(int sockfd
, struct sockaddr
*addr
, int addrlen
, int proto
)
1033 /* No address -- may be recvfrom() from known socket */
1039 /* XXX: BeOS version of accept() doesn't set family correctly */
1040 addr
->sa_family
= AF_INET
;
1043 switch (addr
->sa_family
) {
1047 struct sockaddr_in
*a
;
1048 PyObject
*addrobj
= makeipaddr(addr
, sizeof(*a
));
1049 PyObject
*ret
= NULL
;
1051 a
= (struct sockaddr_in
*)addr
;
1052 ret
= Py_BuildValue("Oi", addrobj
, ntohs(a
->sin_port
));
1058 #if defined(AF_UNIX)
1061 struct sockaddr_un
*a
= (struct sockaddr_un
*) addr
;
1063 if (a
->sun_path
[0] == 0) { /* Linux abstract namespace */
1064 addrlen
-= offsetof(struct sockaddr_un
, sun_path
);
1065 return PyString_FromStringAndSize(a
->sun_path
,
1071 /* regular NULL-terminated string */
1072 return PyString_FromString(a
->sun_path
);
1075 #endif /* AF_UNIX */
1077 #if defined(AF_NETLINK)
1080 struct sockaddr_nl
*a
= (struct sockaddr_nl
*) addr
;
1081 return Py_BuildValue("II", a
->nl_pid
, a
->nl_groups
);
1083 #endif /* AF_NETLINK */
1088 struct sockaddr_in6
*a
;
1089 PyObject
*addrobj
= makeipaddr(addr
, sizeof(*a
));
1090 PyObject
*ret
= NULL
;
1092 a
= (struct sockaddr_in6
*)addr
;
1093 ret
= Py_BuildValue("OiII",
1095 ntohs(a
->sin6_port
),
1096 ntohl(a
->sin6_flowinfo
),
1104 #ifdef USE_BLUETOOTH
1110 struct sockaddr_l2
*a
= (struct sockaddr_l2
*) addr
;
1111 PyObject
*addrobj
= makebdaddr(&_BT_L2_MEMB(a
, bdaddr
));
1112 PyObject
*ret
= NULL
;
1114 ret
= Py_BuildValue("Oi",
1116 _BT_L2_MEMB(a
, psm
));
1122 case BTPROTO_RFCOMM
:
1124 struct sockaddr_rc
*a
= (struct sockaddr_rc
*) addr
;
1125 PyObject
*addrobj
= makebdaddr(&_BT_RC_MEMB(a
, bdaddr
));
1126 PyObject
*ret
= NULL
;
1128 ret
= Py_BuildValue("Oi",
1130 _BT_RC_MEMB(a
, channel
));
1138 struct sockaddr_hci
*a
= (struct sockaddr_hci
*) addr
;
1139 #if defined(__NetBSD__) || defined(__DragonFly__)
1140 return makebdaddr(&_BT_HCI_MEMB(a
, bdaddr
));
1142 PyObject
*ret
= NULL
;
1143 ret
= Py_BuildValue("i", _BT_HCI_MEMB(a
, dev
));
1148 #if !defined(__FreeBSD__)
1151 struct sockaddr_sco
*a
= (struct sockaddr_sco
*) addr
;
1152 return makebdaddr(&_BT_SCO_MEMB(a
, bdaddr
));
1157 PyErr_SetString(PyExc_ValueError
,
1158 "Unknown Bluetooth protocol");
1163 #if defined(HAVE_NETPACKET_PACKET_H) && defined(SIOCGIFNAME)
1166 struct sockaddr_ll
*a
= (struct sockaddr_ll
*)addr
;
1169 /* need to look up interface name give index */
1170 if (a
->sll_ifindex
) {
1171 ifr
.ifr_ifindex
= a
->sll_ifindex
;
1172 if (ioctl(sockfd
, SIOCGIFNAME
, &ifr
) == 0)
1173 ifname
= ifr
.ifr_name
;
1175 return Py_BuildValue("shbhs#",
1177 ntohs(a
->sll_protocol
),
1185 #ifdef HAVE_LINUX_TIPC_H
1188 struct sockaddr_tipc
*a
= (struct sockaddr_tipc
*) addr
;
1189 if (a
->addrtype
== TIPC_ADDR_NAMESEQ
) {
1190 return Py_BuildValue("IIIII",
1192 a
->addr
.nameseq
.type
,
1193 a
->addr
.nameseq
.lower
,
1194 a
->addr
.nameseq
.upper
,
1196 } else if (a
->addrtype
== TIPC_ADDR_NAME
) {
1197 return Py_BuildValue("IIIII",
1199 a
->addr
.name
.name
.type
,
1200 a
->addr
.name
.name
.instance
,
1201 a
->addr
.name
.name
.instance
,
1203 } else if (a
->addrtype
== TIPC_ADDR_ID
) {
1204 return Py_BuildValue("IIIII",
1211 PyErr_SetString(PyExc_ValueError
,
1212 "Invalid address type");
1218 /* More cases here... */
1221 /* If we don't know the address family, don't raise an
1222 exception -- return it as a tuple. */
1223 return Py_BuildValue("is#",
1226 sizeof(addr
->sa_data
));
1232 /* Parse a socket address argument according to the socket object's
1233 address family. Return 1 if the address was in the proper format,
1234 0 of not. The address is returned through addr_ret, its length
1238 getsockaddrarg(PySocketSockObject
*s
, PyObject
*args
,
1239 struct sockaddr
*addr_ret
, int *len_ret
)
1241 switch (s
->sock_family
) {
1243 #if defined(AF_UNIX)
1246 struct sockaddr_un
* addr
;
1249 if (!PyArg_Parse(args
, "t#", &path
, &len
))
1252 addr
= (struct sockaddr_un
*)addr_ret
;
1254 if (len
> 0 && path
[0] == 0) {
1255 /* Linux abstract namespace extension */
1256 if (len
> sizeof addr
->sun_path
) {
1257 PyErr_SetString(socket_error
,
1258 "AF_UNIX path too long");
1265 /* regular NULL-terminated string */
1266 if (len
>= sizeof addr
->sun_path
) {
1267 PyErr_SetString(socket_error
,
1268 "AF_UNIX path too long");
1271 addr
->sun_path
[len
] = 0;
1273 addr
->sun_family
= s
->sock_family
;
1274 memcpy(addr
->sun_path
, path
, len
);
1275 #if defined(PYOS_OS2)
1276 *len_ret
= sizeof(*addr
);
1278 *len_ret
= len
+ offsetof(struct sockaddr_un
, sun_path
);
1282 #endif /* AF_UNIX */
1284 #if defined(AF_NETLINK)
1287 struct sockaddr_nl
* addr
;
1289 addr
= (struct sockaddr_nl
*)addr_ret
;
1290 if (!PyTuple_Check(args
)) {
1294 "AF_NETLINK address must be tuple, not %.500s",
1295 Py_TYPE(args
)->tp_name
);
1298 if (!PyArg_ParseTuple(args
, "II:getsockaddrarg", &pid
, &groups
))
1300 addr
->nl_family
= AF_NETLINK
;
1302 addr
->nl_groups
= groups
;
1303 *len_ret
= sizeof(*addr
);
1310 struct sockaddr_in
* addr
;
1313 if (!PyTuple_Check(args
)) {
1317 "AF_INET address must be tuple, not %.500s",
1318 Py_TYPE(args
)->tp_name
);
1321 if (!PyArg_ParseTuple(args
, "eti:getsockaddrarg",
1322 "idna", &host
, &port
))
1324 addr
=(struct sockaddr_in
*)addr_ret
;
1325 result
= setipaddr(host
, (struct sockaddr
*)addr
,
1326 sizeof(*addr
), AF_INET
);
1330 if (port
< 0 || port
> 0xffff) {
1332 PyExc_OverflowError
,
1333 "getsockaddrarg: port must be 0-65535.");
1336 addr
->sin_family
= AF_INET
;
1337 addr
->sin_port
= htons((short)port
);
1338 *len_ret
= sizeof *addr
;
1345 struct sockaddr_in6
* addr
;
1348 unsigned int flowinfo
, scope_id
;
1349 flowinfo
= scope_id
= 0;
1350 if (!PyTuple_Check(args
)) {
1354 "AF_INET6 address must be tuple, not %.500s",
1355 Py_TYPE(args
)->tp_name
);
1358 if (!PyArg_ParseTuple(args
, "eti|II",
1359 "idna", &host
, &port
, &flowinfo
,
1363 addr
= (struct sockaddr_in6
*)addr_ret
;
1364 result
= setipaddr(host
, (struct sockaddr
*)addr
,
1365 sizeof(*addr
), AF_INET6
);
1369 if (port
< 0 || port
> 0xffff) {
1371 PyExc_OverflowError
,
1372 "getsockaddrarg: port must be 0-65535.");
1375 if (flowinfo
> 0xfffff) {
1377 PyExc_OverflowError
,
1378 "getsockaddrarg: flowinfo must be 0-1048575.");
1381 addr
->sin6_family
= s
->sock_family
;
1382 addr
->sin6_port
= htons((short)port
);
1383 addr
->sin6_flowinfo
= htonl(flowinfo
);
1384 addr
->sin6_scope_id
= scope_id
;
1385 *len_ret
= sizeof *addr
;
1390 #ifdef USE_BLUETOOTH
1393 switch (s
->sock_proto
) {
1396 struct sockaddr_l2
*addr
;
1399 addr
= (struct sockaddr_l2
*)addr_ret
;
1400 memset(addr
, 0, sizeof(struct sockaddr_l2
));
1401 _BT_L2_MEMB(addr
, family
) = AF_BLUETOOTH
;
1402 if (!PyArg_ParseTuple(args
, "si", &straddr
,
1403 &_BT_L2_MEMB(addr
, psm
))) {
1404 PyErr_SetString(socket_error
, "getsockaddrarg: "
1408 if (setbdaddr(straddr
, &_BT_L2_MEMB(addr
, bdaddr
)) < 0)
1411 *len_ret
= sizeof *addr
;
1414 case BTPROTO_RFCOMM
:
1416 struct sockaddr_rc
*addr
;
1419 addr
= (struct sockaddr_rc
*)addr_ret
;
1420 _BT_RC_MEMB(addr
, family
) = AF_BLUETOOTH
;
1421 if (!PyArg_ParseTuple(args
, "si", &straddr
,
1422 &_BT_RC_MEMB(addr
, channel
))) {
1423 PyErr_SetString(socket_error
, "getsockaddrarg: "
1427 if (setbdaddr(straddr
, &_BT_RC_MEMB(addr
, bdaddr
)) < 0)
1430 *len_ret
= sizeof *addr
;
1435 struct sockaddr_hci
*addr
= (struct sockaddr_hci
*)addr_ret
;
1436 #if defined(__NetBSD__) || defined(__DragonFly__)
1437 char *straddr
= PyBytes_AS_STRING(args
);
1439 _BT_HCI_MEMB(addr
, family
) = AF_BLUETOOTH
;
1440 if (straddr
== NULL
) {
1441 PyErr_SetString(socket_error
, "getsockaddrarg: "
1445 if (setbdaddr(straddr
, &_BT_HCI_MEMB(addr
, bdaddr
)) < 0)
1448 _BT_HCI_MEMB(addr
, family
) = AF_BLUETOOTH
;
1449 if (!PyArg_ParseTuple(args
, "i", &_BT_HCI_MEMB(addr
, dev
))) {
1450 PyErr_SetString(socket_error
, "getsockaddrarg: "
1455 *len_ret
= sizeof *addr
;
1458 #if !defined(__FreeBSD__)
1461 struct sockaddr_sco
*addr
;
1464 addr
= (struct sockaddr_sco
*)addr_ret
;
1465 _BT_SCO_MEMB(addr
, family
) = AF_BLUETOOTH
;
1466 straddr
= PyString_AsString(args
);
1467 if (straddr
== NULL
) {
1468 PyErr_SetString(socket_error
, "getsockaddrarg: "
1472 if (setbdaddr(straddr
, &_BT_SCO_MEMB(addr
, bdaddr
)) < 0)
1475 *len_ret
= sizeof *addr
;
1480 PyErr_SetString(socket_error
, "getsockaddrarg: unknown Bluetooth protocol");
1486 #if defined(HAVE_NETPACKET_PACKET_H) && defined(SIOCGIFINDEX)
1489 struct sockaddr_ll
* addr
;
1491 char *interfaceName
;
1496 unsigned int halen
= 0;
1498 if (!PyTuple_Check(args
)) {
1502 "AF_PACKET address must be tuple, not %.500s",
1503 Py_TYPE(args
)->tp_name
);
1506 if (!PyArg_ParseTuple(args
, "si|iis#", &interfaceName
,
1507 &protoNumber
, &pkttype
, &hatype
,
1510 strncpy(ifr
.ifr_name
, interfaceName
, sizeof(ifr
.ifr_name
));
1511 ifr
.ifr_name
[(sizeof(ifr
.ifr_name
))-1] = '\0';
1512 if (ioctl(s
->sock_fd
, SIOCGIFINDEX
, &ifr
) < 0) {
1517 PyErr_SetString(PyExc_ValueError
,
1518 "Hardware address must be 8 bytes or less");
1521 if (protoNumber
< 0 || protoNumber
> 0xffff) {
1523 PyExc_OverflowError
,
1524 "getsockaddrarg: protoNumber must be 0-65535.");
1527 addr
= (struct sockaddr_ll
*)addr_ret
;
1528 addr
->sll_family
= AF_PACKET
;
1529 addr
->sll_protocol
= htons((short)protoNumber
);
1530 addr
->sll_ifindex
= ifr
.ifr_ifindex
;
1531 addr
->sll_pkttype
= pkttype
;
1532 addr
->sll_hatype
= hatype
;
1534 memcpy(&addr
->sll_addr
, haddr
, halen
);
1536 addr
->sll_halen
= halen
;
1537 *len_ret
= sizeof *addr
;
1542 #ifdef HAVE_LINUX_TIPC_H
1545 unsigned int atype
, v1
, v2
, v3
;
1546 unsigned int scope
= TIPC_CLUSTER_SCOPE
;
1547 struct sockaddr_tipc
*addr
;
1549 if (!PyTuple_Check(args
)) {
1553 "AF_TIPC address must be tuple, not %.500s",
1554 Py_TYPE(args
)->tp_name
);
1558 if (!PyArg_ParseTuple(args
,
1559 "IIII|I;Invalid TIPC address format",
1560 &atype
, &v1
, &v2
, &v3
, &scope
))
1563 addr
= (struct sockaddr_tipc
*) addr_ret
;
1564 memset(addr
, 0, sizeof(struct sockaddr_tipc
));
1566 addr
->family
= AF_TIPC
;
1567 addr
->scope
= scope
;
1568 addr
->addrtype
= atype
;
1570 if (atype
== TIPC_ADDR_NAMESEQ
) {
1571 addr
->addr
.nameseq
.type
= v1
;
1572 addr
->addr
.nameseq
.lower
= v2
;
1573 addr
->addr
.nameseq
.upper
= v3
;
1574 } else if (atype
== TIPC_ADDR_NAME
) {
1575 addr
->addr
.name
.name
.type
= v1
;
1576 addr
->addr
.name
.name
.instance
= v2
;
1577 } else if (atype
== TIPC_ADDR_ID
) {
1578 addr
->addr
.id
.node
= v1
;
1579 addr
->addr
.id
.ref
= v2
;
1581 /* Shouldn't happen */
1582 PyErr_SetString(PyExc_TypeError
, "Invalid address type");
1586 *len_ret
= sizeof(*addr
);
1592 /* More cases here... */
1595 PyErr_SetString(socket_error
, "getsockaddrarg: bad family");
1602 /* Get the address length according to the socket object's address family.
1603 Return 1 if the family is known, 0 otherwise. The length is returned
1607 getsockaddrlen(PySocketSockObject
*s
, socklen_t
*len_ret
)
1609 switch (s
->sock_family
) {
1611 #if defined(AF_UNIX)
1614 *len_ret
= sizeof (struct sockaddr_un
);
1617 #endif /* AF_UNIX */
1618 #if defined(AF_NETLINK)
1621 *len_ret
= sizeof (struct sockaddr_nl
);
1628 *len_ret
= sizeof (struct sockaddr_in
);
1635 *len_ret
= sizeof (struct sockaddr_in6
);
1640 #ifdef USE_BLUETOOTH
1643 switch(s
->sock_proto
)
1647 *len_ret
= sizeof (struct sockaddr_l2
);
1649 case BTPROTO_RFCOMM
:
1650 *len_ret
= sizeof (struct sockaddr_rc
);
1653 *len_ret
= sizeof (struct sockaddr_hci
);
1655 #if !defined(__FreeBSD__)
1657 *len_ret
= sizeof (struct sockaddr_sco
);
1661 PyErr_SetString(socket_error
, "getsockaddrlen: "
1662 "unknown BT protocol");
1669 #ifdef HAVE_NETPACKET_PACKET_H
1672 *len_ret
= sizeof (struct sockaddr_ll
);
1677 #ifdef HAVE_LINUX_TIPC_H
1680 *len_ret
= sizeof (struct sockaddr_tipc
);
1685 /* More cases here... */
1688 PyErr_SetString(socket_error
, "getsockaddrlen: bad family");
1695 /* s.accept() method */
1698 sock_accept(PySocketSockObject
*s
)
1700 sock_addr_t addrbuf
;
1703 PyObject
*sock
= NULL
;
1704 PyObject
*addr
= NULL
;
1705 PyObject
*res
= NULL
;
1708 if (!getsockaddrlen(s
, &addrlen
))
1710 memset(&addrbuf
, 0, addrlen
);
1712 newfd
= INVALID_SOCKET
;
1714 if (!IS_SELECTABLE(s
))
1715 return select_error();
1717 BEGIN_SELECT_LOOP(s
)
1718 Py_BEGIN_ALLOW_THREADS
1719 timeout
= internal_select_ex(s
, 0, interval
);
1721 newfd
= accept(s
->sock_fd
, SAS2SA(&addrbuf
), &addrlen
);
1722 Py_END_ALLOW_THREADS
1725 PyErr_SetString(socket_timeout
, "timed out");
1730 if (newfd
== INVALID_SOCKET
)
1731 return s
->errorhandler();
1733 /* Create the new object with unspecified family,
1734 to avoid calls to bind() etc. on it. */
1735 sock
= (PyObject
*) new_sockobject(newfd
,
1744 addr
= makesockaddr(s
->sock_fd
, SAS2SA(&addrbuf
),
1745 addrlen
, s
->sock_proto
);
1749 res
= PyTuple_Pack(2, sock
, addr
);
1757 PyDoc_STRVAR(accept_doc
,
1758 "accept() -> (socket object, address info)\n\
1760 Wait for an incoming connection. Return a new socket representing the\n\
1761 connection, and the address of the client. For IP sockets, the address\n\
1762 info is a pair (hostaddr, port).");
1764 /* s.setblocking(flag) method. Argument:
1765 False -- non-blocking mode; same as settimeout(0)
1766 True -- blocking mode; same as settimeout(None)
1770 sock_setblocking(PySocketSockObject
*s
, PyObject
*arg
)
1774 block
= PyInt_AsLong(arg
);
1775 if (block
== -1 && PyErr_Occurred())
1778 s
->sock_timeout
= block
? -1.0 : 0.0;
1779 internal_setblocking(s
, block
);
1785 PyDoc_STRVAR(setblocking_doc
,
1786 "setblocking(flag)\n\
1788 Set the socket to blocking (flag is true) or non-blocking (false).\n\
1789 setblocking(True) is equivalent to settimeout(None);\n\
1790 setblocking(False) is equivalent to settimeout(0.0).");
1792 /* s.settimeout(timeout) method. Argument:
1793 None -- no timeout, blocking mode; same as setblocking(True)
1794 0.0 -- non-blocking mode; same as setblocking(False)
1795 > 0 -- timeout mode; operations time out after timeout seconds
1796 < 0 -- illegal; raises an exception
1799 sock_settimeout(PySocketSockObject
*s
, PyObject
*arg
)
1806 timeout
= PyFloat_AsDouble(arg
);
1807 if (timeout
< 0.0) {
1808 if (!PyErr_Occurred())
1809 PyErr_SetString(PyExc_ValueError
,
1810 "Timeout value out of range");
1815 s
->sock_timeout
= timeout
;
1816 internal_setblocking(s
, timeout
< 0.0);
1822 PyDoc_STRVAR(settimeout_doc
,
1823 "settimeout(timeout)\n\
1825 Set a timeout on socket operations. 'timeout' can be a float,\n\
1826 giving in seconds, or None. Setting a timeout of None disables\n\
1827 the timeout feature and is equivalent to setblocking(1).\n\
1828 Setting a timeout of zero is the same as setblocking(0).");
1830 /* s.gettimeout() method.
1831 Returns the timeout associated with a socket. */
1833 sock_gettimeout(PySocketSockObject
*s
)
1835 if (s
->sock_timeout
< 0.0) {
1840 return PyFloat_FromDouble(s
->sock_timeout
);
1843 PyDoc_STRVAR(gettimeout_doc
,
1844 "gettimeout() -> timeout\n\
1846 Returns the timeout in seconds (float) associated with socket \n\
1847 operations. A timeout of None indicates that timeouts on socket \n\
1848 operations are disabled.");
1851 /* s.sleeptaskw(1 | 0) method */
1854 sock_sleeptaskw(PySocketSockObject
*s
,PyObject
*arg
)
1857 block
= PyInt_AsLong(arg
);
1858 if (block
== -1 && PyErr_Occurred())
1860 Py_BEGIN_ALLOW_THREADS
1861 socketioctl(s
->sock_fd
, 0x80046679, (u_long
*)&block
);
1862 Py_END_ALLOW_THREADS
1867 PyDoc_STRVAR(sleeptaskw_doc
,
1868 "sleeptaskw(flag)\n\
1870 Allow sleeps in taskwindows.");
1874 /* s.setsockopt() method.
1875 With an integer third argument, sets an integer option.
1876 With a string third argument, sets an option from a buffer;
1877 use optional built-in module 'struct' to encode the string. */
1880 sock_setsockopt(PySocketSockObject
*s
, PyObject
*args
)
1889 if (PyArg_ParseTuple(args
, "iii:setsockopt",
1890 &level
, &optname
, &flag
)) {
1891 buf
= (char *) &flag
;
1892 buflen
= sizeof flag
;
1896 if (!PyArg_ParseTuple(args
, "iis#:setsockopt",
1897 &level
, &optname
, &buf
, &buflen
))
1900 res
= setsockopt(s
->sock_fd
, level
, optname
, (void *)buf
, buflen
);
1902 return s
->errorhandler();
1907 PyDoc_STRVAR(setsockopt_doc
,
1908 "setsockopt(level, option, value)\n\
1910 Set a socket option. See the Unix manual for level and option.\n\
1911 The value argument can either be an integer or a string.");
1914 /* s.getsockopt() method.
1915 With two arguments, retrieves an integer option.
1916 With a third integer argument, retrieves a string buffer of that size;
1917 use optional built-in module 'struct' to decode the string. */
1920 sock_getsockopt(PySocketSockObject
*s
, PyObject
*args
)
1926 socklen_t buflen
= 0;
1929 /* We have incomplete socket support. */
1930 PyErr_SetString(socket_error
, "getsockopt not supported");
1934 if (!PyArg_ParseTuple(args
, "ii|i:getsockopt",
1935 &level
, &optname
, &buflen
))
1940 socklen_t flagsize
= sizeof flag
;
1941 res
= getsockopt(s
->sock_fd
, level
, optname
,
1942 (void *)&flag
, &flagsize
);
1944 return s
->errorhandler();
1945 return PyInt_FromLong(flag
);
1948 /* socklen_t is unsigned so no negative test is needed,
1949 test buflen == 0 is previously done */
1950 if (buflen
> 1024) {
1952 if (buflen
<= 0 || buflen
> 1024) {
1954 PyErr_SetString(socket_error
,
1955 "getsockopt buflen out of range");
1958 buf
= PyString_FromStringAndSize((char *)NULL
, buflen
);
1961 res
= getsockopt(s
->sock_fd
, level
, optname
,
1962 (void *)PyString_AS_STRING(buf
), &buflen
);
1965 return s
->errorhandler();
1967 _PyString_Resize(&buf
, buflen
);
1969 #endif /* __BEOS__ */
1972 PyDoc_STRVAR(getsockopt_doc
,
1973 "getsockopt(level, option[, buffersize]) -> value\n\
1975 Get a socket option. See the Unix manual for level and option.\n\
1976 If a nonzero buffersize argument is given, the return value is a\n\
1977 string of that length; otherwise it is an integer.");
1980 /* s.bind(sockaddr) method */
1983 sock_bind(PySocketSockObject
*s
, PyObject
*addro
)
1985 sock_addr_t addrbuf
;
1989 if (!getsockaddrarg(s
, addro
, SAS2SA(&addrbuf
), &addrlen
))
1991 Py_BEGIN_ALLOW_THREADS
1992 res
= bind(s
->sock_fd
, SAS2SA(&addrbuf
), addrlen
);
1993 Py_END_ALLOW_THREADS
1995 return s
->errorhandler();
2000 PyDoc_STRVAR(bind_doc
,
2003 Bind the socket to a local address. For IP sockets, the address is a\n\
2004 pair (host, port); the host must refer to the local host. For raw packet\n\
2005 sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");
2008 /* s.close() method.
2009 Set the file descriptor to -1 so operations tried subsequently
2010 will surely fail. */
2013 sock_close(PySocketSockObject
*s
)
2017 if ((fd
= s
->sock_fd
) != -1) {
2019 Py_BEGIN_ALLOW_THREADS
2020 (void) SOCKETCLOSE(fd
);
2021 Py_END_ALLOW_THREADS
2027 PyDoc_STRVAR(close_doc
,
2030 Close the socket. It cannot be used after this call.");
2033 internal_connect(PySocketSockObject
*s
, struct sockaddr
*addr
, int addrlen
,
2039 res
= connect(s
->sock_fd
, addr
, addrlen
);
2043 if (s
->sock_timeout
> 0.0) {
2044 if (res
< 0 && WSAGetLastError() == WSAEWOULDBLOCK
&&
2046 /* This is a mess. Best solution: trust select */
2050 tv
.tv_sec
= (int)s
->sock_timeout
;
2051 tv
.tv_usec
= (int)((s
->sock_timeout
- tv
.tv_sec
) * 1e6
);
2053 FD_SET(s
->sock_fd
, &fds
);
2055 FD_SET(s
->sock_fd
, &fds_exc
);
2056 res
= select(s
->sock_fd
+1, NULL
, &fds
, &fds_exc
, &tv
);
2058 res
= WSAEWOULDBLOCK
;
2060 } else if (res
> 0) {
2061 if (FD_ISSET(s
->sock_fd
, &fds
))
2062 /* The socket is in the writeable set - this
2066 /* As per MS docs, we need to call getsockopt()
2067 to get the underlying error */
2068 int res_size
= sizeof res
;
2069 /* It must be in the exception set */
2070 assert(FD_ISSET(s
->sock_fd
, &fds_exc
));
2071 if (0 == getsockopt(s
->sock_fd
, SOL_SOCKET
, SO_ERROR
,
2072 (char *)&res
, &res_size
))
2073 /* getsockopt also clears WSAGetLastError,
2074 so reset it back. */
2075 WSASetLastError(res
);
2077 res
= WSAGetLastError();
2080 /* else if (res < 0) an error occurred */
2085 res
= WSAGetLastError();
2089 if (s
->sock_timeout
> 0.0) {
2090 if (res
< 0 && errno
== EINPROGRESS
&& IS_SELECTABLE(s
)) {
2091 timeout
= internal_select(s
, 1);
2093 /* Bug #1019808: in case of an EINPROGRESS,
2094 use getsockopt(SO_ERROR) to get the real
2096 socklen_t res_size
= sizeof res
;
2097 (void)getsockopt(s
->sock_fd
, SOL_SOCKET
,
2098 SO_ERROR
, &res
, &res_size
);
2103 else if (timeout
== -1) {
2104 res
= errno
; /* had error */
2107 res
= EWOULDBLOCK
; /* timed out */
2115 *timeoutp
= timeout
;
2120 /* s.connect(sockaddr) method */
2123 sock_connect(PySocketSockObject
*s
, PyObject
*addro
)
2125 sock_addr_t addrbuf
;
2130 if (!getsockaddrarg(s
, addro
, SAS2SA(&addrbuf
), &addrlen
))
2133 Py_BEGIN_ALLOW_THREADS
2134 res
= internal_connect(s
, SAS2SA(&addrbuf
), addrlen
, &timeout
);
2135 Py_END_ALLOW_THREADS
2138 PyErr_SetString(socket_timeout
, "timed out");
2142 return s
->errorhandler();
2147 PyDoc_STRVAR(connect_doc
,
2148 "connect(address)\n\
2150 Connect the socket to a remote address. For IP sockets, the address\n\
2151 is a pair (host, port).");
2154 /* s.connect_ex(sockaddr) method */
2157 sock_connect_ex(PySocketSockObject
*s
, PyObject
*addro
)
2159 sock_addr_t addrbuf
;
2164 if (!getsockaddrarg(s
, addro
, SAS2SA(&addrbuf
), &addrlen
))
2167 Py_BEGIN_ALLOW_THREADS
2168 res
= internal_connect(s
, SAS2SA(&addrbuf
), addrlen
, &timeout
);
2169 Py_END_ALLOW_THREADS
2171 /* Signals are not errors (though they may raise exceptions). Adapted
2172 from PyErr_SetFromErrnoWithFilenameObject(). */
2174 if (res
== EINTR
&& PyErr_CheckSignals())
2178 return PyInt_FromLong((long) res
);
2181 PyDoc_STRVAR(connect_ex_doc
,
2182 "connect_ex(address) -> errno\n\
2184 This is like connect(address), but returns an error code (the errno value)\n\
2185 instead of raising an exception when an error occurs.");
2188 /* s.fileno() method */
2191 sock_fileno(PySocketSockObject
*s
)
2193 #if SIZEOF_SOCKET_T <= SIZEOF_LONG
2194 return PyInt_FromLong((long) s
->sock_fd
);
2196 return PyLong_FromLongLong((PY_LONG_LONG
)s
->sock_fd
);
2200 PyDoc_STRVAR(fileno_doc
,
2201 "fileno() -> integer\n\
2203 Return the integer file descriptor of the socket.");
2207 /* s.dup() method */
2210 sock_dup(PySocketSockObject
*s
)
2215 newfd
= dup(s
->sock_fd
);
2217 return s
->errorhandler();
2218 sock
= (PyObject
*) new_sockobject(newfd
,
2227 PyDoc_STRVAR(dup_doc
,
2228 "dup() -> socket object\n\
2230 Return a new socket object connected to the same system resource.");
2235 /* s.getsockname() method */
2238 sock_getsockname(PySocketSockObject
*s
)
2240 sock_addr_t addrbuf
;
2244 if (!getsockaddrlen(s
, &addrlen
))
2246 memset(&addrbuf
, 0, addrlen
);
2247 Py_BEGIN_ALLOW_THREADS
2248 res
= getsockname(s
->sock_fd
, SAS2SA(&addrbuf
), &addrlen
);
2249 Py_END_ALLOW_THREADS
2251 return s
->errorhandler();
2252 return makesockaddr(s
->sock_fd
, SAS2SA(&addrbuf
), addrlen
,
2256 PyDoc_STRVAR(getsockname_doc
,
2257 "getsockname() -> address info\n\
2259 Return the address of the local endpoint. For IP sockets, the address\n\
2260 info is a pair (hostaddr, port).");
2263 #ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
2264 /* s.getpeername() method */
2267 sock_getpeername(PySocketSockObject
*s
)
2269 sock_addr_t addrbuf
;
2273 if (!getsockaddrlen(s
, &addrlen
))
2275 memset(&addrbuf
, 0, addrlen
);
2276 Py_BEGIN_ALLOW_THREADS
2277 res
= getpeername(s
->sock_fd
, SAS2SA(&addrbuf
), &addrlen
);
2278 Py_END_ALLOW_THREADS
2280 return s
->errorhandler();
2281 return makesockaddr(s
->sock_fd
, SAS2SA(&addrbuf
), addrlen
,
2285 PyDoc_STRVAR(getpeername_doc
,
2286 "getpeername() -> address info\n\
2288 Return the address of the remote endpoint. For IP sockets, the address\n\
2289 info is a pair (hostaddr, port).");
2291 #endif /* HAVE_GETPEERNAME */
2294 /* s.listen(n) method */
2297 sock_listen(PySocketSockObject
*s
, PyObject
*arg
)
2302 backlog
= _PyInt_AsInt(arg
);
2303 if (backlog
== -1 && PyErr_Occurred())
2305 Py_BEGIN_ALLOW_THREADS
2306 /* To avoid problems on systems that don't allow a negative backlog
2307 * (which doesn't make sense anyway) we force a minimum value of 0. */
2310 res
= listen(s
->sock_fd
, backlog
);
2311 Py_END_ALLOW_THREADS
2313 return s
->errorhandler();
2318 PyDoc_STRVAR(listen_doc
,
2321 Enable a server to accept connections. The backlog argument must be at\n\
2322 least 0 (if it is lower, it is set to 0); it specifies the number of\n\
2323 unaccepted connections that the system will allow before refusing new\n\
2328 /* s.makefile(mode) method.
2329 Create a new open file object referring to a dupped version of
2330 the socket's file descriptor. (The dup() call is necessary so
2331 that the open file and socket objects may be closed independent
2333 The mode argument specifies 'r' or 'w' passed to fdopen(). */
2336 sock_makefile(PySocketSockObject
*s
, PyObject
*args
)
2338 extern int fclose(FILE *);
2353 if (!PyArg_ParseTuple(args
, "|si:makefile", &mode
, &bufsize
))
2356 if (strcmp(mode
,"rb") == 0) {
2360 if (strcmp(mode
,"wb") == 0) {
2366 if (((fd
= _open_osfhandle(s
->sock_fd
, _O_BINARY
)) < 0) ||
2367 ((fd
= dup(fd
)) < 0) || ((fp
= fdopen(fd
, mode
)) == NULL
))
2369 if ((fd
= dup(s
->sock_fd
)) < 0 || (fp
= fdopen(fd
, mode
)) == NULL
)
2374 return s
->errorhandler();
2376 f
= PyFile_FromFile(fp
, "<socket>", mode
, fclose
);
2378 PyFile_SetBufSize(f
, bufsize
);
2382 PyDoc_STRVAR(makefile_doc
,
2383 "makefile([mode[, buffersize]]) -> file object\n\
2385 Return a regular file object corresponding to the socket.\n\
2386 The mode and buffersize arguments are as for the built-in open() function.");
2391 * This is the guts of the recv() and recv_into() methods, which reads into a
2392 * char buffer. If you have any inc/dec ref to do to the objects that contain
2393 * the buffer, do it in the caller. This function returns the number of bytes
2394 * successfully read. If there was an error, it returns -1. Note that it is
2395 * also possible that we return a number of bytes smaller than the request
2399 sock_recv_guts(PySocketSockObject
*s
, char* cbuf
, int len
, int flags
)
2401 ssize_t outlen
= -1;
2408 if (!IS_SELECTABLE(s
)) {
2414 BEGIN_SELECT_LOOP(s
)
2415 Py_BEGIN_ALLOW_THREADS
2416 timeout
= internal_select_ex(s
, 0, interval
);
2418 outlen
= recv(s
->sock_fd
, cbuf
, len
, flags
);
2419 Py_END_ALLOW_THREADS
2422 PyErr_SetString(socket_timeout
, "timed out");
2427 /* Note: the call to errorhandler() ALWAYS indirectly returned
2428 NULL, so ignore its return value */
2435 while (remaining
!= 0) {
2436 unsigned int segment
;
2439 segment
= remaining
/SEGMENT_SIZE
;
2441 segment
= SEGMENT_SIZE
;
2444 segment
= remaining
;
2447 BEGIN_SELECT_LOOP(s
)
2448 Py_BEGIN_ALLOW_THREADS
2449 timeout
= internal_select_ex(s
, 0, interval
);
2451 nread
= recv(s
->sock_fd
, read_buf
, segment
, flags
);
2452 Py_END_ALLOW_THREADS
2455 PyErr_SetString(socket_timeout
, "timed out");
2464 if (nread
!= remaining
) {
2469 remaining
-= segment
;
2470 read_buf
+= segment
;
2472 outlen
= read_buf
- cbuf
;
2479 /* s.recv(nbytes [,flags]) method */
2482 sock_recv(PySocketSockObject
*s
, PyObject
*args
)
2484 int recvlen
, flags
= 0;
2488 if (!PyArg_ParseTuple(args
, "i|i:recv", &recvlen
, &flags
))
2492 PyErr_SetString(PyExc_ValueError
,
2493 "negative buffersize in recv");
2497 /* Allocate a new string. */
2498 buf
= PyString_FromStringAndSize((char *) 0, recvlen
);
2503 outlen
= sock_recv_guts(s
, PyString_AS_STRING(buf
), recvlen
, flags
);
2505 /* An error occurred, release the string and return an
2510 if (outlen
!= recvlen
) {
2511 /* We did not read as many bytes as we anticipated, resize the
2512 string if possible and be successful. */
2513 if (_PyString_Resize(&buf
, outlen
) < 0)
2514 /* Oopsy, not so successful after all. */
2521 PyDoc_STRVAR(recv_doc
,
2522 "recv(buffersize[, flags]) -> data\n\
2524 Receive up to buffersize bytes from the socket. For the optional flags\n\
2525 argument, see the Unix manual. When no data is available, block until\n\
2526 at least one byte is available or until the remote end is closed. When\n\
2527 the remote end is closed and all data is read, return the empty string.");
2530 /* s.recv_into(buffer, [nbytes [,flags]]) method */
2533 sock_recv_into(PySocketSockObject
*s
, PyObject
*args
, PyObject
*kwds
)
2535 static char *kwlist
[] = {"buffer", "nbytes", "flags", 0};
2537 int recvlen
= 0, flags
= 0;
2542 /* Get the buffer's memory */
2543 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "w*|ii:recv_into", kwlist
,
2544 &buf
, &recvlen
, &flags
))
2547 assert(buf
.buf
!= 0 && buflen
> 0);
2550 PyErr_SetString(PyExc_ValueError
,
2551 "negative buffersize in recv_into");
2555 /* If nbytes was not specified, use the buffer's length */
2559 /* Check if the buffer is large enough */
2560 if (buflen
< recvlen
) {
2561 PyErr_SetString(PyExc_ValueError
,
2562 "buffer too small for requested bytes");
2567 readlen
= sock_recv_guts(s
, buf
.buf
, recvlen
, flags
);
2569 /* Return an error. */
2573 PyBuffer_Release(&buf
);
2574 /* Return the number of bytes read. Note that we do not do anything
2575 special here in the case that readlen < recvlen. */
2576 return PyInt_FromSsize_t(readlen
);
2579 PyBuffer_Release(&buf
);
2583 PyDoc_STRVAR(recv_into_doc
,
2584 "recv_into(buffer, [nbytes[, flags]]) -> nbytes_read\n\
2586 A version of recv() that stores its data into a buffer rather than creating \n\
2587 a new string. Receive up to buffersize bytes from the socket. If buffersize \n\
2588 is not specified (or 0), receive up to the size available in the given buffer.\n\
2590 See recv() for documentation about the flags.");
2594 * This is the guts of the recvfrom() and recvfrom_into() methods, which reads
2595 * into a char buffer. If you have any inc/def ref to do to the objects that
2596 * contain the buffer, do it in the caller. This function returns the number
2597 * of bytes successfully read. If there was an error, it returns -1. Note
2598 * that it is also possible that we return a number of bytes smaller than the
2601 * 'addr' is a return value for the address object. Note that you must decref
2605 sock_recvfrom_guts(PySocketSockObject
*s
, char* cbuf
, int len
, int flags
,
2608 sock_addr_t addrbuf
;
2615 if (!getsockaddrlen(s
, &addrlen
))
2618 if (!IS_SELECTABLE(s
)) {
2623 BEGIN_SELECT_LOOP(s
)
2624 Py_BEGIN_ALLOW_THREADS
2625 memset(&addrbuf
, 0, addrlen
);
2626 timeout
= internal_select_ex(s
, 0, interval
);
2629 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
2630 n
= recvfrom(s
->sock_fd
, cbuf
, len
, flags
,
2631 SAS2SA(&addrbuf
), &addrlen
);
2633 n
= recvfrom(s
->sock_fd
, cbuf
, len
, flags
,
2634 (void *) &addrbuf
, &addrlen
);
2637 n
= recvfrom(s
->sock_fd
, cbuf
, len
, flags
,
2638 SAS2SA(&addrbuf
), &addrlen
);
2641 Py_END_ALLOW_THREADS
2644 PyErr_SetString(socket_timeout
, "timed out");
2653 if (!(*addr
= makesockaddr(s
->sock_fd
, SAS2SA(&addrbuf
),
2654 addrlen
, s
->sock_proto
)))
2660 /* s.recvfrom(nbytes [,flags]) method */
2663 sock_recvfrom(PySocketSockObject
*s
, PyObject
*args
)
2665 PyObject
*buf
= NULL
;
2666 PyObject
*addr
= NULL
;
2667 PyObject
*ret
= NULL
;
2668 int recvlen
, flags
= 0;
2671 if (!PyArg_ParseTuple(args
, "i|i:recvfrom", &recvlen
, &flags
))
2675 PyErr_SetString(PyExc_ValueError
,
2676 "negative buffersize in recvfrom");
2680 buf
= PyString_FromStringAndSize((char *) 0, recvlen
);
2684 outlen
= sock_recvfrom_guts(s
, PyString_AS_STRING(buf
),
2685 recvlen
, flags
, &addr
);
2690 if (outlen
!= recvlen
) {
2691 /* We did not read as many bytes as we anticipated, resize the
2692 string if possible and be successful. */
2693 if (_PyString_Resize(&buf
, outlen
) < 0)
2694 /* Oopsy, not so successful after all. */
2698 ret
= PyTuple_Pack(2, buf
, addr
);
2706 PyDoc_STRVAR(recvfrom_doc
,
2707 "recvfrom(buffersize[, flags]) -> (data, address info)\n\
2709 Like recv(buffersize, flags) but also return the sender's address info.");
2712 /* s.recvfrom_into(buffer[, nbytes [,flags]]) method */
2715 sock_recvfrom_into(PySocketSockObject
*s
, PyObject
*args
, PyObject
* kwds
)
2717 static char *kwlist
[] = {"buffer", "nbytes", "flags", 0};
2719 int recvlen
= 0, flags
= 0;
2724 PyObject
*addr
= NULL
;
2726 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "w*|ii:recvfrom_into",
2733 PyErr_SetString(PyExc_ValueError
,
2734 "negative buffersize in recvfrom_into");
2738 /* If nbytes was not specified, use the buffer's length */
2740 } else if (recvlen
> buflen
) {
2741 PyErr_SetString(PyExc_ValueError
,
2742 "nbytes is greater than the length of the buffer");
2746 readlen
= sock_recvfrom_guts(s
, buf
.buf
, recvlen
, flags
, &addr
);
2748 /* Return an error */
2752 PyBuffer_Release(&buf
);
2753 /* Return the number of bytes read and the address. Note that we do
2754 not do anything special here in the case that readlen < recvlen. */
2755 return Py_BuildValue("lN", readlen
, addr
);
2759 PyBuffer_Release(&buf
);
2763 PyDoc_STRVAR(recvfrom_into_doc
,
2764 "recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)\n\
2766 Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.");
2769 /* s.send(data [,flags]) method */
2772 sock_send(PySocketSockObject
*s
, PyObject
*args
)
2775 int len
, n
= -1, flags
= 0, timeout
;
2778 if (!PyArg_ParseTuple(args
, "s*|i:send", &pbuf
, &flags
))
2781 if (!IS_SELECTABLE(s
)) {
2782 PyBuffer_Release(&pbuf
);
2783 return select_error();
2788 BEGIN_SELECT_LOOP(s
)
2789 Py_BEGIN_ALLOW_THREADS
2790 timeout
= internal_select_ex(s
, 1, interval
);
2793 n
= sendsegmented(s
->sock_fd
, buf
, len
, flags
);
2795 n
= send(s
->sock_fd
, buf
, len
, flags
);
2797 Py_END_ALLOW_THREADS
2799 PyBuffer_Release(&pbuf
);
2800 PyErr_SetString(socket_timeout
, "timed out");
2805 PyBuffer_Release(&pbuf
);
2807 return s
->errorhandler();
2808 return PyInt_FromLong((long)n
);
2811 PyDoc_STRVAR(send_doc
,
2812 "send(data[, flags]) -> count\n\
2814 Send a data string to the socket. For the optional flags\n\
2815 argument, see the Unix manual. Return the number of bytes\n\
2816 sent; this may be less than len(data) if the network is busy.");
2819 /* s.sendall(data [,flags]) method */
2822 sock_sendall(PySocketSockObject
*s
, PyObject
*args
)
2825 int len
, n
= -1, flags
= 0, timeout
, saved_errno
;
2828 if (!PyArg_ParseTuple(args
, "s*|i:sendall", &pbuf
, &flags
))
2833 if (!IS_SELECTABLE(s
)) {
2834 PyBuffer_Release(&pbuf
);
2835 return select_error();
2839 BEGIN_SELECT_LOOP(s
)
2840 Py_BEGIN_ALLOW_THREADS
2841 timeout
= internal_select_ex(s
, 1, interval
);
2845 n
= sendsegmented(s
->sock_fd
, buf
, len
, flags
);
2847 n
= send(s
->sock_fd
, buf
, len
, flags
);
2850 Py_END_ALLOW_THREADS
2852 PyBuffer_Release(&pbuf
);
2853 PyErr_SetString(socket_timeout
, "timed out");
2857 /* PyErr_CheckSignals() might change errno */
2858 saved_errno
= errno
;
2859 /* We must run our signal handlers before looping again.
2860 send() can return a successful partial write when it is
2861 interrupted, so we can't restrict ourselves to EINTR. */
2862 if (PyErr_CheckSignals()) {
2863 PyBuffer_Release(&pbuf
);
2867 /* If interrupted, try again */
2868 if (saved_errno
== EINTR
)
2876 PyBuffer_Release(&pbuf
);
2879 return s
->errorhandler();
2885 PyDoc_STRVAR(sendall_doc
,
2886 "sendall(data[, flags])\n\
2888 Send a data string to the socket. For the optional flags\n\
2889 argument, see the Unix manual. This calls send() repeatedly\n\
2890 until all data is sent. If an error occurs, it's impossible\n\
2891 to tell how much data has been sent.");
2894 /* s.sendto(data, [flags,] sockaddr) method */
2897 sock_sendto(PySocketSockObject
*s
, PyObject
*args
)
2903 sock_addr_t addrbuf
;
2904 int addrlen
, flags
, timeout
;
2909 arglen
= PyTuple_Size(args
);
2912 PyArg_ParseTuple(args
, "s*O:sendto", &pbuf
, &addro
);
2915 PyArg_ParseTuple(args
, "s*iO:sendto", &pbuf
, &flags
, &addro
);
2918 PyErr_Format(PyExc_TypeError
, "sendto() takes 2 or 3"
2919 " arguments (%d given)", arglen
);
2921 if (PyErr_Occurred())
2927 if (!IS_SELECTABLE(s
)) {
2928 PyBuffer_Release(&pbuf
);
2929 return select_error();
2932 if (!getsockaddrarg(s
, addro
, SAS2SA(&addrbuf
), &addrlen
)) {
2933 PyBuffer_Release(&pbuf
);
2937 BEGIN_SELECT_LOOP(s
)
2938 Py_BEGIN_ALLOW_THREADS
2939 timeout
= internal_select_ex(s
, 1, interval
);
2941 n
= sendto(s
->sock_fd
, buf
, len
, flags
, SAS2SA(&addrbuf
), addrlen
);
2942 Py_END_ALLOW_THREADS
2945 PyBuffer_Release(&pbuf
);
2946 PyErr_SetString(socket_timeout
, "timed out");
2950 PyBuffer_Release(&pbuf
);
2952 return s
->errorhandler();
2953 return PyInt_FromLong((long)n
);
2956 PyDoc_STRVAR(sendto_doc
,
2957 "sendto(data[, flags], address) -> count\n\
2959 Like send(data, flags) but allows specifying the destination address.\n\
2960 For IP sockets, the address is a pair (hostaddr, port).");
2963 /* s.shutdown(how) method */
2966 sock_shutdown(PySocketSockObject
*s
, PyObject
*arg
)
2971 how
= _PyInt_AsInt(arg
);
2972 if (how
== -1 && PyErr_Occurred())
2974 Py_BEGIN_ALLOW_THREADS
2975 res
= shutdown(s
->sock_fd
, how
);
2976 Py_END_ALLOW_THREADS
2978 return s
->errorhandler();
2983 PyDoc_STRVAR(shutdown_doc
,
2986 Shut down the reading side of the socket (flag == SHUT_RD), the writing side\n\
2987 of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).");
2989 #if defined(MS_WINDOWS) && defined(SIO_RCVALL)
2991 sock_ioctl(PySocketSockObject
*s
, PyObject
*arg
)
2993 unsigned long cmd
= SIO_RCVALL
;
2997 if (!PyArg_ParseTuple(arg
, "kO:ioctl", &cmd
, &argO
))
3002 unsigned int option
= RCVALL_ON
;
3003 if (!PyArg_ParseTuple(arg
, "kI:ioctl", &cmd
, &option
))
3005 if (WSAIoctl(s
->sock_fd
, cmd
, &option
, sizeof(option
),
3006 NULL
, 0, &recv
, NULL
, NULL
) == SOCKET_ERROR
) {
3009 return PyLong_FromUnsignedLong(recv
); }
3010 case SIO_KEEPALIVE_VALS
: {
3011 struct tcp_keepalive ka
;
3012 if (!PyArg_ParseTuple(arg
, "k(kkk):ioctl", &cmd
,
3013 &ka
.onoff
, &ka
.keepalivetime
, &ka
.keepaliveinterval
))
3015 if (WSAIoctl(s
->sock_fd
, cmd
, &ka
, sizeof(ka
),
3016 NULL
, 0, &recv
, NULL
, NULL
) == SOCKET_ERROR
) {
3019 return PyLong_FromUnsignedLong(recv
); }
3021 PyErr_Format(PyExc_ValueError
, "invalid ioctl command %d", cmd
);
3025 PyDoc_STRVAR(sock_ioctl_doc
,
3026 "ioctl(cmd, option) -> long\n\
3028 Control the socket with WSAIoctl syscall. Currently supported 'cmd' values are\n\
3029 SIO_RCVALL: 'option' must be one of the socket.RCVALL_* constants.\n\
3030 SIO_KEEPALIVE_VALS: 'option' is a tuple of (onoff, timeout, interval).");
3034 /* List of methods for socket objects */
3036 static PyMethodDef sock_methods
[] = {
3037 {"accept", (PyCFunction
)sock_accept
, METH_NOARGS
,
3039 {"bind", (PyCFunction
)sock_bind
, METH_O
,
3041 {"close", (PyCFunction
)sock_close
, METH_NOARGS
,
3043 {"connect", (PyCFunction
)sock_connect
, METH_O
,
3045 {"connect_ex", (PyCFunction
)sock_connect_ex
, METH_O
,
3048 {"dup", (PyCFunction
)sock_dup
, METH_NOARGS
,
3051 {"fileno", (PyCFunction
)sock_fileno
, METH_NOARGS
,
3053 #ifdef HAVE_GETPEERNAME
3054 {"getpeername", (PyCFunction
)sock_getpeername
,
3055 METH_NOARGS
, getpeername_doc
},
3057 {"getsockname", (PyCFunction
)sock_getsockname
,
3058 METH_NOARGS
, getsockname_doc
},
3059 {"getsockopt", (PyCFunction
)sock_getsockopt
, METH_VARARGS
,
3061 #if defined(MS_WINDOWS) && defined(SIO_RCVALL)
3062 {"ioctl", (PyCFunction
)sock_ioctl
, METH_VARARGS
,
3065 {"listen", (PyCFunction
)sock_listen
, METH_O
,
3068 {"makefile", (PyCFunction
)sock_makefile
, METH_VARARGS
,
3071 {"recv", (PyCFunction
)sock_recv
, METH_VARARGS
,
3073 {"recv_into", (PyCFunction
)sock_recv_into
, METH_VARARGS
| METH_KEYWORDS
,
3075 {"recvfrom", (PyCFunction
)sock_recvfrom
, METH_VARARGS
,
3077 {"recvfrom_into", (PyCFunction
)sock_recvfrom_into
, METH_VARARGS
| METH_KEYWORDS
,
3079 {"send", (PyCFunction
)sock_send
, METH_VARARGS
,
3081 {"sendall", (PyCFunction
)sock_sendall
, METH_VARARGS
,
3083 {"sendto", (PyCFunction
)sock_sendto
, METH_VARARGS
,
3085 {"setblocking", (PyCFunction
)sock_setblocking
, METH_O
,
3087 {"settimeout", (PyCFunction
)sock_settimeout
, METH_O
,
3089 {"gettimeout", (PyCFunction
)sock_gettimeout
, METH_NOARGS
,
3091 {"setsockopt", (PyCFunction
)sock_setsockopt
, METH_VARARGS
,
3093 {"shutdown", (PyCFunction
)sock_shutdown
, METH_O
,
3096 {"sleeptaskw", (PyCFunction
)sock_sleeptaskw
, METH_O
,
3099 {NULL
, NULL
} /* sentinel */
3102 /* SockObject members */
3103 static PyMemberDef sock_memberlist
[] = {
3104 {"family", T_INT
, offsetof(PySocketSockObject
, sock_family
), READONLY
, "the socket family"},
3105 {"type", T_INT
, offsetof(PySocketSockObject
, sock_type
), READONLY
, "the socket type"},
3106 {"proto", T_INT
, offsetof(PySocketSockObject
, sock_proto
), READONLY
, "the socket protocol"},
3107 {"timeout", T_DOUBLE
, offsetof(PySocketSockObject
, sock_timeout
), READONLY
, "the socket timeout"},
3111 /* Deallocate a socket object in response to the last Py_DECREF().
3112 First close the file description. */
3115 sock_dealloc(PySocketSockObject
*s
)
3117 if (s
->sock_fd
!= -1)
3118 (void) SOCKETCLOSE(s
->sock_fd
);
3119 if (s
->weakreflist
!= NULL
)
3120 PyObject_ClearWeakRefs((PyObject
*)s
);
3121 Py_TYPE(s
)->tp_free((PyObject
*)s
);
3126 sock_repr(PySocketSockObject
*s
)
3130 /* On Windows, this test is needed because SOCKET_T is unsigned */
3131 if (s
->sock_fd
== INVALID_SOCKET
) {
3134 #if SIZEOF_SOCKET_T > SIZEOF_LONG
3135 else if (s
->sock_fd
> LONG_MAX
) {
3136 /* this can occur on Win64, and actually there is a special
3137 ugly printf formatter for decimal pointer length integer
3138 printing, only bother if necessary*/
3139 PyErr_SetString(PyExc_OverflowError
,
3140 "no printf formatter to display "
3141 "the socket descriptor in decimal");
3146 sock_fd
= (long)s
->sock_fd
;
3149 "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
3150 sock_fd
, s
->sock_family
,
3153 return PyString_FromString(buf
);
3157 /* Create a new, uninitialized socket object. */
3160 sock_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
3164 new = type
->tp_alloc(type
, 0);
3166 ((PySocketSockObject
*)new)->sock_fd
= -1;
3167 ((PySocketSockObject
*)new)->sock_timeout
= -1.0;
3168 ((PySocketSockObject
*)new)->errorhandler
= &set_error
;
3169 ((PySocketSockObject
*)new)->weakreflist
= NULL
;
3175 /* Initialize a new socket object. */
3179 sock_initobj(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
3181 PySocketSockObject
*s
= (PySocketSockObject
*)self
;
3183 int family
= AF_INET
, type
= SOCK_STREAM
, proto
= 0;
3184 static char *keywords
[] = {"family", "type", "proto", 0};
3186 if (!PyArg_ParseTupleAndKeywords(args
, kwds
,
3187 "|iii:socket", keywords
,
3188 &family
, &type
, &proto
))
3191 Py_BEGIN_ALLOW_THREADS
3192 fd
= socket(family
, type
, proto
);
3193 Py_END_ALLOW_THREADS
3195 if (fd
== INVALID_SOCKET
) {
3199 init_sockobject(s
, fd
, family
, type
, proto
);
3206 /* Type object for socket objects. */
3208 static PyTypeObject sock_type
= {
3209 PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */
3210 "_socket.socket", /* tp_name */
3211 sizeof(PySocketSockObject
), /* tp_basicsize */
3212 0, /* tp_itemsize */
3213 (destructor
)sock_dealloc
, /* tp_dealloc */
3218 (reprfunc
)sock_repr
, /* tp_repr */
3219 0, /* tp_as_number */
3220 0, /* tp_as_sequence */
3221 0, /* tp_as_mapping */
3225 PyObject_GenericGetAttr
, /* tp_getattro */
3226 0, /* tp_setattro */
3227 0, /* tp_as_buffer */
3228 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
3229 sock_doc
, /* tp_doc */
3230 0, /* tp_traverse */
3232 0, /* tp_richcompare */
3233 offsetof(PySocketSockObject
, weakreflist
), /* tp_weaklistoffset */
3235 0, /* tp_iternext */
3236 sock_methods
, /* tp_methods */
3237 sock_memberlist
, /* tp_members */
3241 0, /* tp_descr_get */
3242 0, /* tp_descr_set */
3243 0, /* tp_dictoffset */
3244 sock_initobj
, /* tp_init */
3245 PyType_GenericAlloc
, /* tp_alloc */
3246 sock_new
, /* tp_new */
3247 PyObject_Del
, /* tp_free */
3251 /* Python interface to gethostname(). */
3255 socket_gethostname(PyObject
*self
, PyObject
*unused
)
3259 Py_BEGIN_ALLOW_THREADS
3260 res
= gethostname(buf
, (int) sizeof buf
- 1);
3261 Py_END_ALLOW_THREADS
3264 buf
[sizeof buf
- 1] = '\0';
3265 return PyString_FromString(buf
);
3268 PyDoc_STRVAR(gethostname_doc
,
3269 "gethostname() -> string\n\
3271 Return the current host name.");
3274 /* Python interface to gethostbyname(name). */
3278 socket_gethostbyname(PyObject
*self
, PyObject
*args
)
3281 sock_addr_t addrbuf
;
3283 if (!PyArg_ParseTuple(args
, "s:gethostbyname", &name
))
3285 if (setipaddr(name
, SAS2SA(&addrbuf
), sizeof(addrbuf
), AF_INET
) < 0)
3287 return makeipaddr(SAS2SA(&addrbuf
), sizeof(struct sockaddr_in
));
3290 PyDoc_STRVAR(gethostbyname_doc
,
3291 "gethostbyname(host) -> address\n\
3293 Return the IP address (a string of the form '255.255.255.255') for a host.");
3296 /* Convenience function common to gethostbyname_ex and gethostbyaddr */
3299 gethost_common(struct hostent
*h
, struct sockaddr
*addr
, int alen
, int af
)
3302 PyObject
*rtn_tuple
= (PyObject
*)NULL
;
3303 PyObject
*name_list
= (PyObject
*)NULL
;
3304 PyObject
*addr_list
= (PyObject
*)NULL
;
3308 /* Let's get real error message to return */
3310 set_herror(h_errno
);
3312 PyErr_SetString(socket_error
, "host not found");
3317 if (h
->h_addrtype
!= af
) {
3318 /* Let's get real error message to return */
3319 PyErr_SetString(socket_error
,
3320 (char *)strerror(EAFNOSUPPORT
));
3328 if (alen
< sizeof(struct sockaddr_in
))
3334 if (alen
< sizeof(struct sockaddr_in6
))
3341 if ((name_list
= PyList_New(0)) == NULL
)
3344 if ((addr_list
= PyList_New(0)) == NULL
)
3347 /* SF #1511317: h_aliases can be NULL */
3349 for (pch
= h
->h_aliases
; *pch
!= NULL
; pch
++) {
3351 tmp
= PyString_FromString(*pch
);
3355 status
= PyList_Append(name_list
, tmp
);
3363 for (pch
= h
->h_addr_list
; *pch
!= NULL
; pch
++) {
3370 struct sockaddr_in sin
;
3371 memset(&sin
, 0, sizeof(sin
));
3372 sin
.sin_family
= af
;
3373 #ifdef HAVE_SOCKADDR_SA_LEN
3374 sin
.sin_len
= sizeof(sin
);
3376 memcpy(&sin
.sin_addr
, *pch
, sizeof(sin
.sin_addr
));
3377 tmp
= makeipaddr((struct sockaddr
*)&sin
, sizeof(sin
));
3379 if (pch
== h
->h_addr_list
&& alen
>= sizeof(sin
))
3380 memcpy((char *) addr
, &sin
, sizeof(sin
));
3387 struct sockaddr_in6 sin6
;
3388 memset(&sin6
, 0, sizeof(sin6
));
3389 sin6
.sin6_family
= af
;
3390 #ifdef HAVE_SOCKADDR_SA_LEN
3391 sin6
.sin6_len
= sizeof(sin6
);
3393 memcpy(&sin6
.sin6_addr
, *pch
, sizeof(sin6
.sin6_addr
));
3394 tmp
= makeipaddr((struct sockaddr
*)&sin6
,
3397 if (pch
== h
->h_addr_list
&& alen
>= sizeof(sin6
))
3398 memcpy((char *) addr
, &sin6
, sizeof(sin6
));
3403 default: /* can't happen */
3404 PyErr_SetString(socket_error
,
3405 "unsupported address family");
3412 status
= PyList_Append(addr_list
, tmp
);
3419 rtn_tuple
= Py_BuildValue("sOO", h
->h_name
, name_list
, addr_list
);
3422 Py_XDECREF(name_list
);
3423 Py_XDECREF(addr_list
);
3428 /* Python interface to gethostbyname_ex(name). */
3432 socket_gethostbyname_ex(PyObject
*self
, PyObject
*args
)
3437 struct sockaddr_storage addr
;
3439 struct sockaddr_in addr
;
3441 struct sockaddr
*sa
;
3443 #ifdef HAVE_GETHOSTBYNAME_R
3444 struct hostent hp_allocated
;
3445 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
3446 struct hostent_data data
;
3449 int buf_len
= (sizeof buf
) - 1;
3452 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3455 #endif /* HAVE_GETHOSTBYNAME_R */
3457 if (!PyArg_ParseTuple(args
, "s:gethostbyname_ex", &name
))
3459 if (setipaddr(name
, (struct sockaddr
*)&addr
, sizeof(addr
), AF_INET
) < 0)
3461 Py_BEGIN_ALLOW_THREADS
3462 #ifdef HAVE_GETHOSTBYNAME_R
3463 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3464 result
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
,
3466 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
3467 h
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
, &errnop
);
3468 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
3469 memset((void *) &data
, '\0', sizeof(data
));
3470 result
= gethostbyname_r(name
, &hp_allocated
, &data
);
3471 h
= (result
!= 0) ? NULL
: &hp_allocated
;
3473 #else /* not HAVE_GETHOSTBYNAME_R */
3474 #ifdef USE_GETHOSTBYNAME_LOCK
3475 PyThread_acquire_lock(netdb_lock
, 1);
3477 h
= gethostbyname(name
);
3478 #endif /* HAVE_GETHOSTBYNAME_R */
3479 Py_END_ALLOW_THREADS
3480 /* Some C libraries would require addr.__ss_family instead of
3482 Therefore, we cast the sockaddr_storage into sockaddr to
3483 access sa_family. */
3484 sa
= (struct sockaddr
*)&addr
;
3485 ret
= gethost_common(h
, (struct sockaddr
*)&addr
, sizeof(addr
),
3487 #ifdef USE_GETHOSTBYNAME_LOCK
3488 PyThread_release_lock(netdb_lock
);
3493 PyDoc_STRVAR(ghbn_ex_doc
,
3494 "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
3496 Return the true host name, a list of aliases, and a list of IP addresses,\n\
3497 for a host. The host argument is a string giving a host name or IP number.");
3500 /* Python interface to gethostbyaddr(IP). */
3504 socket_gethostbyaddr(PyObject
*self
, PyObject
*args
)
3507 struct sockaddr_storage addr
;
3509 struct sockaddr_in addr
;
3511 struct sockaddr
*sa
= (struct sockaddr
*)&addr
;
3515 #ifdef HAVE_GETHOSTBYNAME_R
3516 struct hostent hp_allocated
;
3517 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
3518 struct hostent_data data
;
3520 /* glibcs up to 2.10 assume that the buf argument to
3521 gethostbyaddr_r is 8-byte aligned, which at least llvm-gcc
3522 does not ensure. The attribute below instructs the compiler
3523 to maintain this alignment. */
3524 char buf
[16384] Py_ALIGNED(8);
3525 int buf_len
= (sizeof buf
) - 1;
3528 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3531 #endif /* HAVE_GETHOSTBYNAME_R */
3536 if (!PyArg_ParseTuple(args
, "s:gethostbyaddr", &ip_num
))
3539 if (setipaddr(ip_num
, sa
, sizeof(addr
), af
) < 0)
3545 ap
= (char *)&((struct sockaddr_in
*)sa
)->sin_addr
;
3546 al
= sizeof(((struct sockaddr_in
*)sa
)->sin_addr
);
3550 ap
= (char *)&((struct sockaddr_in6
*)sa
)->sin6_addr
;
3551 al
= sizeof(((struct sockaddr_in6
*)sa
)->sin6_addr
);
3555 PyErr_SetString(socket_error
, "unsupported address family");
3558 Py_BEGIN_ALLOW_THREADS
3559 #ifdef HAVE_GETHOSTBYNAME_R
3560 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3561 result
= gethostbyaddr_r(ap
, al
, af
,
3562 &hp_allocated
, buf
, buf_len
,
3564 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
3565 h
= gethostbyaddr_r(ap
, al
, af
,
3566 &hp_allocated
, buf
, buf_len
, &errnop
);
3567 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
3568 memset((void *) &data
, '\0', sizeof(data
));
3569 result
= gethostbyaddr_r(ap
, al
, af
, &hp_allocated
, &data
);
3570 h
= (result
!= 0) ? NULL
: &hp_allocated
;
3572 #else /* not HAVE_GETHOSTBYNAME_R */
3573 #ifdef USE_GETHOSTBYNAME_LOCK
3574 PyThread_acquire_lock(netdb_lock
, 1);
3576 h
= gethostbyaddr(ap
, al
, af
);
3577 #endif /* HAVE_GETHOSTBYNAME_R */
3578 Py_END_ALLOW_THREADS
3579 ret
= gethost_common(h
, (struct sockaddr
*)&addr
, sizeof(addr
), af
);
3580 #ifdef USE_GETHOSTBYNAME_LOCK
3581 PyThread_release_lock(netdb_lock
);
3586 PyDoc_STRVAR(gethostbyaddr_doc
,
3587 "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
3589 Return the true host name, a list of aliases, and a list of IP addresses,\n\
3590 for a host. The host argument is a string giving a host name or IP number.");
3593 /* Python interface to getservbyname(name).
3594 This only returns the port number, since the other info is already
3595 known or not useful (like the list of aliases). */
3599 socket_getservbyname(PyObject
*self
, PyObject
*args
)
3601 char *name
, *proto
=NULL
;
3603 if (!PyArg_ParseTuple(args
, "s|s:getservbyname", &name
, &proto
))
3605 Py_BEGIN_ALLOW_THREADS
3606 sp
= getservbyname(name
, proto
);
3607 Py_END_ALLOW_THREADS
3609 PyErr_SetString(socket_error
, "service/proto not found");
3612 return PyInt_FromLong((long) ntohs(sp
->s_port
));
3615 PyDoc_STRVAR(getservbyname_doc
,
3616 "getservbyname(servicename[, protocolname]) -> integer\n\
3618 Return a port number from a service name and protocol name.\n\
3619 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3620 otherwise any protocol will match.");
3623 /* Python interface to getservbyport(port).
3624 This only returns the service name, since the other info is already
3625 known or not useful (like the list of aliases). */
3629 socket_getservbyport(PyObject
*self
, PyObject
*args
)
3634 if (!PyArg_ParseTuple(args
, "i|s:getservbyport", &port
, &proto
))
3636 if (port
< 0 || port
> 0xffff) {
3638 PyExc_OverflowError
,
3639 "getservbyport: port must be 0-65535.");
3642 Py_BEGIN_ALLOW_THREADS
3643 sp
= getservbyport(htons((short)port
), proto
);
3644 Py_END_ALLOW_THREADS
3646 PyErr_SetString(socket_error
, "port/proto not found");
3649 return PyString_FromString(sp
->s_name
);
3652 PyDoc_STRVAR(getservbyport_doc
,
3653 "getservbyport(port[, protocolname]) -> string\n\
3655 Return the service name from a port number and protocol name.\n\
3656 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3657 otherwise any protocol will match.");
3659 /* Python interface to getprotobyname(name).
3660 This only returns the protocol number, since the other info is
3661 already known or not useful (like the list of aliases). */
3665 socket_getprotobyname(PyObject
*self
, PyObject
*args
)
3668 struct protoent
*sp
;
3670 /* Not available in BeOS yet. - [cjh] */
3671 PyErr_SetString(socket_error
, "getprotobyname not supported");
3674 if (!PyArg_ParseTuple(args
, "s:getprotobyname", &name
))
3676 Py_BEGIN_ALLOW_THREADS
3677 sp
= getprotobyname(name
);
3678 Py_END_ALLOW_THREADS
3680 PyErr_SetString(socket_error
, "protocol not found");
3683 return PyInt_FromLong((long) sp
->p_proto
);
3687 PyDoc_STRVAR(getprotobyname_doc
,
3688 "getprotobyname(name) -> integer\n\
3690 Return the protocol number for the named protocol. (Rarely used.)");
3693 #ifdef HAVE_SOCKETPAIR
3694 /* Create a pair of sockets using the socketpair() function.
3695 Arguments as for socket() except the default family is AF_UNIX if
3696 defined on the platform; otherwise, the default is AF_INET. */
3700 socket_socketpair(PyObject
*self
, PyObject
*args
)
3702 PySocketSockObject
*s0
= NULL
, *s1
= NULL
;
3704 int family
, type
= SOCK_STREAM
, proto
= 0;
3705 PyObject
*res
= NULL
;
3707 #if defined(AF_UNIX)
3712 if (!PyArg_ParseTuple(args
, "|iii:socketpair",
3713 &family
, &type
, &proto
))
3715 /* Create a pair of socket fds */
3716 if (socketpair(family
, type
, proto
, sv
) < 0)
3718 s0
= new_sockobject(sv
[0], family
, type
, proto
);
3721 s1
= new_sockobject(sv
[1], family
, type
, proto
);
3724 res
= PyTuple_Pack(2, s0
, s1
);
3738 PyDoc_STRVAR(socketpair_doc
,
3739 "socketpair([family[, type[, proto]]]) -> (socket object, socket object)\n\
3741 Create a pair of socket objects from the sockets returned by the platform\n\
3742 socketpair() function.\n\
3743 The arguments are the same as for socket() except the default family is\n\
3744 AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");
3746 #endif /* HAVE_SOCKETPAIR */
3750 /* Create a socket object from a numeric file description.
3751 Useful e.g. if stdin is a socket.
3752 Additional arguments as for socket(). */
3756 socket_fromfd(PyObject
*self
, PyObject
*args
)
3758 PySocketSockObject
*s
;
3760 int family
, type
, proto
= 0;
3761 if (!PyArg_ParseTuple(args
, "iii|i:fromfd",
3762 &fd
, &family
, &type
, &proto
))
3764 /* Dup the fd so it and the socket can be closed independently */
3768 s
= new_sockobject(fd
, family
, type
, proto
);
3769 return (PyObject
*) s
;
3772 PyDoc_STRVAR(fromfd_doc
,
3773 "fromfd(fd, family, type[, proto]) -> socket object\n\
3775 Create a socket object from a duplicate of the given\n\
3777 The remaining arguments are the same as for socket().");
3783 socket_ntohs(PyObject
*self
, PyObject
*args
)
3787 if (!PyArg_ParseTuple(args
, "i:ntohs", &x1
)) {
3791 PyErr_SetString(PyExc_OverflowError
,
3792 "can't convert negative number to unsigned long");
3795 x2
= (unsigned int)ntohs((unsigned short)x1
);
3796 return PyInt_FromLong(x2
);
3799 PyDoc_STRVAR(ntohs_doc
,
3800 "ntohs(integer) -> integer\n\
3802 Convert a 16-bit integer from network to host byte order.");
3806 socket_ntohl(PyObject
*self
, PyObject
*arg
)
3810 if (PyInt_Check(arg
)) {
3811 x
= PyInt_AS_LONG(arg
);
3812 if (x
== (unsigned long) -1 && PyErr_Occurred())
3815 PyErr_SetString(PyExc_OverflowError
,
3816 "can't convert negative number to unsigned long");
3820 else if (PyLong_Check(arg
)) {
3821 x
= PyLong_AsUnsignedLong(arg
);
3822 if (x
== (unsigned long) -1 && PyErr_Occurred())
3827 /* only want the trailing 32 bits */
3828 y
= x
& 0xFFFFFFFFUL
;
3830 return PyErr_Format(PyExc_OverflowError
,
3831 "long int larger than 32 bits");
3837 return PyErr_Format(PyExc_TypeError
,
3838 "expected int/long, %s found",
3839 Py_TYPE(arg
)->tp_name
);
3840 if (x
== (unsigned long) -1 && PyErr_Occurred())
3842 return PyLong_FromUnsignedLong(ntohl(x
));
3845 PyDoc_STRVAR(ntohl_doc
,
3846 "ntohl(integer) -> integer\n\
3848 Convert a 32-bit integer from network to host byte order.");
3852 socket_htons(PyObject
*self
, PyObject
*args
)
3856 if (!PyArg_ParseTuple(args
, "i:htons", &x1
)) {
3860 PyErr_SetString(PyExc_OverflowError
,
3861 "can't convert negative number to unsigned long");
3864 x2
= (unsigned int)htons((unsigned short)x1
);
3865 return PyInt_FromLong(x2
);
3868 PyDoc_STRVAR(htons_doc
,
3869 "htons(integer) -> integer\n\
3871 Convert a 16-bit integer from host to network byte order.");
3875 socket_htonl(PyObject
*self
, PyObject
*arg
)
3879 if (PyInt_Check(arg
)) {
3880 x
= PyInt_AS_LONG(arg
);
3881 if (x
== (unsigned long) -1 && PyErr_Occurred())
3884 PyErr_SetString(PyExc_OverflowError
,
3885 "can't convert negative number to unsigned long");
3889 else if (PyLong_Check(arg
)) {
3890 x
= PyLong_AsUnsignedLong(arg
);
3891 if (x
== (unsigned long) -1 && PyErr_Occurred())
3896 /* only want the trailing 32 bits */
3897 y
= x
& 0xFFFFFFFFUL
;
3899 return PyErr_Format(PyExc_OverflowError
,
3900 "long int larger than 32 bits");
3906 return PyErr_Format(PyExc_TypeError
,
3907 "expected int/long, %s found",
3908 Py_TYPE(arg
)->tp_name
);
3909 return PyLong_FromUnsignedLong(htonl((unsigned long)x
));
3912 PyDoc_STRVAR(htonl_doc
,
3913 "htonl(integer) -> integer\n\
3915 Convert a 32-bit integer from host to network byte order.");
3917 /* socket.inet_aton() and socket.inet_ntoa() functions. */
3919 PyDoc_STRVAR(inet_aton_doc
,
3920 "inet_aton(string) -> packed 32-bit IP representation\n\
3922 Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
3923 binary format used in low-level network functions.");
3926 socket_inet_aton(PyObject
*self
, PyObject
*args
)
3929 #define INADDR_NONE (-1)
3931 #ifdef HAVE_INET_ATON
3935 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
3936 #if (SIZEOF_INT != 4)
3937 #error "Not sure if in_addr_t exists and int is not 32-bits."
3939 /* Have to use inet_addr() instead */
3940 unsigned int packed_addr
;
3944 if (!PyArg_ParseTuple(args
, "s:inet_aton", &ip_addr
))
3948 #ifdef HAVE_INET_ATON
3950 #ifdef USE_INET_ATON_WEAKLINK
3951 if (inet_aton
!= NULL
) {
3953 if (inet_aton(ip_addr
, &buf
))
3954 return PyString_FromStringAndSize((char *)(&buf
),
3957 PyErr_SetString(socket_error
,
3958 "illegal IP address string passed to inet_aton");
3961 #ifdef USE_INET_ATON_WEAKLINK
3967 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
3969 /* special-case this address as inet_addr might return INADDR_NONE
3971 if (strcmp(ip_addr
, "255.255.255.255") == 0) {
3972 packed_addr
= 0xFFFFFFFF;
3975 packed_addr
= inet_addr(ip_addr
);
3977 if (packed_addr
== INADDR_NONE
) { /* invalid address */
3978 PyErr_SetString(socket_error
,
3979 "illegal IP address string passed to inet_aton");
3983 return PyString_FromStringAndSize((char *) &packed_addr
,
3984 sizeof(packed_addr
));
3986 #ifdef USE_INET_ATON_WEAKLINK
3993 PyDoc_STRVAR(inet_ntoa_doc
,
3994 "inet_ntoa(packed_ip) -> ip_address_string\n\
3996 Convert an IP address from 32-bit packed binary format to string format");
3999 socket_inet_ntoa(PyObject
*self
, PyObject
*args
)
4003 struct in_addr packed_addr
;
4005 if (!PyArg_ParseTuple(args
, "s#:inet_ntoa", &packed_str
, &addr_len
)) {
4009 if (addr_len
!= sizeof(packed_addr
)) {
4010 PyErr_SetString(socket_error
,
4011 "packed IP wrong length for inet_ntoa");
4015 memcpy(&packed_addr
, packed_str
, addr_len
);
4017 return PyString_FromString(inet_ntoa(packed_addr
));
4020 #ifdef HAVE_INET_PTON
4022 PyDoc_STRVAR(inet_pton_doc
,
4023 "inet_pton(af, ip) -> packed IP address string\n\
4025 Convert an IP address from string format to a packed string suitable\n\
4026 for use with low-level network functions.");
4029 socket_inet_pton(PyObject
*self
, PyObject
*args
)
4035 char packed
[MAX(sizeof(struct in_addr
), sizeof(struct in6_addr
))];
4037 char packed
[sizeof(struct in_addr
)];
4039 if (!PyArg_ParseTuple(args
, "is:inet_pton", &af
, &ip
)) {
4043 #if !defined(ENABLE_IPV6) && defined(AF_INET6)
4044 if(af
== AF_INET6
) {
4045 PyErr_SetString(socket_error
,
4046 "can't use AF_INET6, IPv6 is disabled");
4051 retval
= inet_pton(af
, ip
, packed
);
4053 PyErr_SetFromErrno(socket_error
);
4055 } else if (retval
== 0) {
4056 PyErr_SetString(socket_error
,
4057 "illegal IP address string passed to inet_pton");
4059 } else if (af
== AF_INET
) {
4060 return PyString_FromStringAndSize(packed
,
4061 sizeof(struct in_addr
));
4063 } else if (af
== AF_INET6
) {
4064 return PyString_FromStringAndSize(packed
,
4065 sizeof(struct in6_addr
));
4068 PyErr_SetString(socket_error
, "unknown address family");
4073 PyDoc_STRVAR(inet_ntop_doc
,
4074 "inet_ntop(af, packed_ip) -> string formatted IP address\n\
4076 Convert a packed IP address of the given family to string format.");
4079 socket_inet_ntop(PyObject
*self
, PyObject
*args
)
4086 char ip
[MAX(INET_ADDRSTRLEN
, INET6_ADDRSTRLEN
) + 1];
4088 char ip
[INET_ADDRSTRLEN
+ 1];
4091 /* Guarantee NUL-termination for PyString_FromString() below */
4092 memset((void *) &ip
[0], '\0', sizeof(ip
));
4094 if (!PyArg_ParseTuple(args
, "is#:inet_ntop", &af
, &packed
, &len
)) {
4098 if (af
== AF_INET
) {
4099 if (len
!= sizeof(struct in_addr
)) {
4100 PyErr_SetString(PyExc_ValueError
,
4101 "invalid length of packed IP address string");
4105 } else if (af
== AF_INET6
) {
4106 if (len
!= sizeof(struct in6_addr
)) {
4107 PyErr_SetString(PyExc_ValueError
,
4108 "invalid length of packed IP address string");
4113 PyErr_Format(PyExc_ValueError
,
4114 "unknown address family %d", af
);
4118 retval
= inet_ntop(af
, packed
, ip
, sizeof(ip
));
4120 PyErr_SetFromErrno(socket_error
);
4123 return PyString_FromString(retval
);
4127 PyErr_SetString(PyExc_RuntimeError
, "invalid handling of inet_ntop");
4131 #endif /* HAVE_INET_PTON */
4133 /* Python interface to getaddrinfo(host, port). */
4137 socket_getaddrinfo(PyObject
*self
, PyObject
*args
)
4139 struct addrinfo hints
, *res
;
4140 struct addrinfo
*res0
= NULL
;
4141 PyObject
*hobj
= NULL
;
4142 PyObject
*pobj
= (PyObject
*)NULL
;
4145 int family
, socktype
, protocol
, flags
;
4147 PyObject
*all
= (PyObject
*)NULL
;
4148 PyObject
*single
= (PyObject
*)NULL
;
4149 PyObject
*idna
= NULL
;
4151 family
= socktype
= protocol
= flags
= 0;
4153 if (!PyArg_ParseTuple(args
, "OO|iiii:getaddrinfo",
4154 &hobj
, &pobj
, &family
, &socktype
,
4155 &protocol
, &flags
)) {
4158 if (hobj
== Py_None
) {
4160 } else if (PyUnicode_Check(hobj
)) {
4161 idna
= PyObject_CallMethod(hobj
, "encode", "s", "idna");
4164 hptr
= PyString_AsString(idna
);
4165 } else if (PyString_Check(hobj
)) {
4166 hptr
= PyString_AsString(hobj
);
4168 PyErr_SetString(PyExc_TypeError
,
4169 "getaddrinfo() argument 1 must be string or None");
4172 if (PyInt_Check(pobj
) || PyLong_Check(pobj
)) {
4173 long value
= PyLong_AsLong(pobj
);
4174 if (value
== -1 && PyErr_Occurred())
4176 PyOS_snprintf(pbuf
, sizeof(pbuf
), "%ld", value
);
4178 } else if (PyString_Check(pobj
)) {
4179 pptr
= PyString_AsString(pobj
);
4180 } else if (pobj
== Py_None
) {
4181 pptr
= (char *)NULL
;
4183 PyErr_SetString(socket_error
,
4184 "getaddrinfo() argument 2 must be integer or string");
4187 #if defined(__APPLE__) && defined(AI_NUMERICSERV)
4188 if ((flags
& AI_NUMERICSERV
) && (pptr
== NULL
|| (pptr
[0] == '0' && pptr
[1] == 0))) {
4189 /* On OSX upto at least OSX 10.8 getaddrinfo crashes
4190 * if AI_NUMERICSERV is set and the servname is NULL or "0".
4191 * This workaround avoids a segfault in libsystem.
4196 memset(&hints
, 0, sizeof(hints
));
4197 hints
.ai_family
= family
;
4198 hints
.ai_socktype
= socktype
;
4199 hints
.ai_protocol
= protocol
;
4200 hints
.ai_flags
= flags
;
4201 Py_BEGIN_ALLOW_THREADS
4202 ACQUIRE_GETADDRINFO_LOCK
4203 error
= getaddrinfo(hptr
, pptr
, &hints
, &res0
);
4204 Py_END_ALLOW_THREADS
4205 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
4207 set_gaierror(error
);
4211 all
= PyList_New(0);
4214 for (res
= res0
; res
; res
= res
->ai_next
) {
4216 makesockaddr(-1, res
->ai_addr
, res
->ai_addrlen
, protocol
);
4219 single
= Py_BuildValue("iiisO", res
->ai_family
,
4220 res
->ai_socktype
, res
->ai_protocol
,
4221 res
->ai_canonname
? res
->ai_canonname
: "",
4227 if (PyList_Append(all
, single
))
4241 return (PyObject
*)NULL
;
4244 PyDoc_STRVAR(getaddrinfo_doc
,
4245 "getaddrinfo(host, port [, family, socktype, proto, flags])\n\
4246 -> list of (family, socktype, proto, canonname, sockaddr)\n\
4248 Resolve host and port into addrinfo struct.");
4250 /* Python interface to getnameinfo(sa, flags). */
4254 socket_getnameinfo(PyObject
*self
, PyObject
*args
)
4256 PyObject
*sa
= (PyObject
*)NULL
;
4260 unsigned int flowinfo
, scope_id
;
4261 char hbuf
[NI_MAXHOST
], pbuf
[NI_MAXSERV
];
4262 struct addrinfo hints
, *res
= NULL
;
4264 PyObject
*ret
= (PyObject
*)NULL
;
4266 flags
= flowinfo
= scope_id
= 0;
4267 if (!PyArg_ParseTuple(args
, "Oi:getnameinfo", &sa
, &flags
))
4269 if (!PyTuple_Check(sa
)) {
4270 PyErr_SetString(PyExc_TypeError
,
4271 "getnameinfo() argument 1 must be a tuple");
4274 if (!PyArg_ParseTuple(sa
, "si|II",
4275 &hostp
, &port
, &flowinfo
, &scope_id
))
4277 if (flowinfo
> 0xfffff) {
4278 PyErr_SetString(PyExc_OverflowError
,
4279 "getsockaddrarg: flowinfo must be 0-1048575.");
4282 PyOS_snprintf(pbuf
, sizeof(pbuf
), "%d", port
);
4283 memset(&hints
, 0, sizeof(hints
));
4284 hints
.ai_family
= AF_UNSPEC
;
4285 hints
.ai_socktype
= SOCK_DGRAM
; /* make numeric port happy */
4286 Py_BEGIN_ALLOW_THREADS
4287 ACQUIRE_GETADDRINFO_LOCK
4288 error
= getaddrinfo(hostp
, pbuf
, &hints
, &res
);
4289 Py_END_ALLOW_THREADS
4290 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
4292 set_gaierror(error
);
4296 PyErr_SetString(socket_error
,
4297 "sockaddr resolved to multiple addresses");
4300 switch (res
->ai_family
) {
4303 if (PyTuple_GET_SIZE(sa
) != 2) {
4304 PyErr_SetString(socket_error
,
4305 "IPv4 sockaddr must be 2 tuple");
4313 struct sockaddr_in6
*sin6
;
4314 sin6
= (struct sockaddr_in6
*)res
->ai_addr
;
4315 sin6
->sin6_flowinfo
= htonl(flowinfo
);
4316 sin6
->sin6_scope_id
= scope_id
;
4321 error
= getnameinfo(res
->ai_addr
, res
->ai_addrlen
,
4322 hbuf
, sizeof(hbuf
), pbuf
, sizeof(pbuf
), flags
);
4324 set_gaierror(error
);
4327 ret
= Py_BuildValue("ss", hbuf
, pbuf
);
4335 PyDoc_STRVAR(getnameinfo_doc
,
4336 "getnameinfo(sockaddr, flags) --> (host, port)\n\
4338 Get host and port for a sockaddr.");
4341 /* Python API to getting and setting the default timeout value. */
4344 socket_getdefaulttimeout(PyObject
*self
)
4346 if (defaulttimeout
< 0.0) {
4351 return PyFloat_FromDouble(defaulttimeout
);
4354 PyDoc_STRVAR(getdefaulttimeout_doc
,
4355 "getdefaulttimeout() -> timeout\n\
4357 Returns the default timeout in seconds (float) for new socket objects.\n\
4358 A value of None indicates that new socket objects have no timeout.\n\
4359 When the socket module is first imported, the default is None.");
4362 socket_setdefaulttimeout(PyObject
*self
, PyObject
*arg
)
4369 timeout
= PyFloat_AsDouble(arg
);
4370 if (timeout
< 0.0) {
4371 if (!PyErr_Occurred())
4372 PyErr_SetString(PyExc_ValueError
,
4373 "Timeout value out of range");
4378 defaulttimeout
= timeout
;
4384 PyDoc_STRVAR(setdefaulttimeout_doc
,
4385 "setdefaulttimeout(timeout)\n\
4387 Set the default timeout in seconds (float) for new socket objects.\n\
4388 A value of None indicates that new socket objects have no timeout.\n\
4389 When the socket module is first imported, the default is None.");
4392 /* List of functions exported by this module. */
4394 static PyMethodDef socket_methods
[] = {
4395 {"gethostbyname", socket_gethostbyname
,
4396 METH_VARARGS
, gethostbyname_doc
},
4397 {"gethostbyname_ex", socket_gethostbyname_ex
,
4398 METH_VARARGS
, ghbn_ex_doc
},
4399 {"gethostbyaddr", socket_gethostbyaddr
,
4400 METH_VARARGS
, gethostbyaddr_doc
},
4401 {"gethostname", socket_gethostname
,
4402 METH_NOARGS
, gethostname_doc
},
4403 {"getservbyname", socket_getservbyname
,
4404 METH_VARARGS
, getservbyname_doc
},
4405 {"getservbyport", socket_getservbyport
,
4406 METH_VARARGS
, getservbyport_doc
},
4407 {"getprotobyname", socket_getprotobyname
,
4408 METH_VARARGS
, getprotobyname_doc
},
4410 {"fromfd", socket_fromfd
,
4411 METH_VARARGS
, fromfd_doc
},
4413 #ifdef HAVE_SOCKETPAIR
4414 {"socketpair", socket_socketpair
,
4415 METH_VARARGS
, socketpair_doc
},
4417 {"ntohs", socket_ntohs
,
4418 METH_VARARGS
, ntohs_doc
},
4419 {"ntohl", socket_ntohl
,
4421 {"htons", socket_htons
,
4422 METH_VARARGS
, htons_doc
},
4423 {"htonl", socket_htonl
,
4425 {"inet_aton", socket_inet_aton
,
4426 METH_VARARGS
, inet_aton_doc
},
4427 {"inet_ntoa", socket_inet_ntoa
,
4428 METH_VARARGS
, inet_ntoa_doc
},
4429 #ifdef HAVE_INET_PTON
4430 {"inet_pton", socket_inet_pton
,
4431 METH_VARARGS
, inet_pton_doc
},
4432 {"inet_ntop", socket_inet_ntop
,
4433 METH_VARARGS
, inet_ntop_doc
},
4435 {"getaddrinfo", socket_getaddrinfo
,
4436 METH_VARARGS
, getaddrinfo_doc
},
4437 {"getnameinfo", socket_getnameinfo
,
4438 METH_VARARGS
, getnameinfo_doc
},
4439 {"getdefaulttimeout", (PyCFunction
)socket_getdefaulttimeout
,
4440 METH_NOARGS
, getdefaulttimeout_doc
},
4441 {"setdefaulttimeout", socket_setdefaulttimeout
,
4442 METH_O
, setdefaulttimeout_doc
},
4443 {NULL
, NULL
} /* Sentinel */
4448 #define OS_INIT_DEFINED
4456 _kernel_swi(0x43380, &r
, &r
);
4457 taskwindow
= r
.r
[0];
4466 #define OS_INIT_DEFINED
4468 /* Additional initialization and cleanup for Windows */
4482 ret
= WSAStartup(0x0101, &WSAData
);
4484 case 0: /* No error */
4485 Py_AtExit(os_cleanup
);
4486 return 1; /* Success */
4487 case WSASYSNOTREADY
:
4488 PyErr_SetString(PyExc_ImportError
,
4489 "WSAStartup failed: network not ready");
4491 case WSAVERNOTSUPPORTED
:
4495 "WSAStartup failed: requested version not supported");
4498 PyOS_snprintf(buf
, sizeof(buf
),
4499 "WSAStartup failed: error code %d", ret
);
4500 PyErr_SetString(PyExc_ImportError
, buf
);
4503 return 0; /* Failure */
4506 #endif /* MS_WINDOWS */
4510 #define OS_INIT_DEFINED
4512 /* Additional initialization for OS/2 */
4519 int rc
= sock_init();
4522 return 1; /* Success */
4525 PyOS_snprintf(reason
, sizeof(reason
),
4526 "OS/2 TCP/IP Error# %d", sock_errno());
4527 PyErr_SetString(PyExc_ImportError
, reason
);
4529 return 0; /* Failure */
4531 /* No need to initialize sockets with GCC/EMX */
4532 return 1; /* Success */
4536 #endif /* PYOS_OS2 */
4539 #ifndef OS_INIT_DEFINED
4543 return 1; /* Success */
4548 /* C API table - always add new things to the end for binary
4551 PySocketModule_APIObject PySocketModuleAPI
=
4558 /* Initialize the _socket module.
4560 This module is actually called "_socket", and there's a wrapper
4561 "socket.py" which implements some additional functionality. On some
4562 platforms (e.g. Windows and OS/2), socket.py also implements a
4563 wrapper for the socket type that provides missing functionality such
4564 as makefile(), dup() and fromfd(). The import of "_socket" may fail
4565 with an ImportError exception if os-specific initialization fails.
4566 On Windows, this does WINSOCK initialization. When WINSOCK is
4567 initialized successfully, a call to WSACleanup() is scheduled to be
4571 PyDoc_STRVAR(socket_doc
,
4572 "Implementation module for socket operations.\n\
4574 See the socket module for documentation.");
4579 PyObject
*m
, *has_ipv6
;
4584 Py_TYPE(&sock_type
) = &PyType_Type
;
4585 m
= Py_InitModule3(PySocket_MODULE_NAME
,
4591 socket_error
= PyErr_NewException("socket.error",
4592 PyExc_IOError
, NULL
);
4593 if (socket_error
== NULL
)
4595 PySocketModuleAPI
.error
= socket_error
;
4596 Py_INCREF(socket_error
);
4597 PyModule_AddObject(m
, "error", socket_error
);
4598 socket_herror
= PyErr_NewException("socket.herror",
4599 socket_error
, NULL
);
4600 if (socket_herror
== NULL
)
4602 Py_INCREF(socket_herror
);
4603 PyModule_AddObject(m
, "herror", socket_herror
);
4604 socket_gaierror
= PyErr_NewException("socket.gaierror", socket_error
,
4606 if (socket_gaierror
== NULL
)
4608 Py_INCREF(socket_gaierror
);
4609 PyModule_AddObject(m
, "gaierror", socket_gaierror
);
4610 socket_timeout
= PyErr_NewException("socket.timeout",
4611 socket_error
, NULL
);
4612 if (socket_timeout
== NULL
)
4614 Py_INCREF(socket_timeout
);
4615 PyModule_AddObject(m
, "timeout", socket_timeout
);
4616 Py_INCREF((PyObject
*)&sock_type
);
4617 if (PyModule_AddObject(m
, "SocketType",
4618 (PyObject
*)&sock_type
) != 0)
4620 Py_INCREF((PyObject
*)&sock_type
);
4621 if (PyModule_AddObject(m
, "socket",
4622 (PyObject
*)&sock_type
) != 0)
4628 has_ipv6
= Py_False
;
4630 Py_INCREF(has_ipv6
);
4631 PyModule_AddObject(m
, "has_ipv6", has_ipv6
);
4634 if (PyModule_AddObject(m
, PySocket_CAPI_NAME
,
4635 PyCapsule_New(&PySocketModuleAPI
, PySocket_CAPSULE_NAME
, NULL
)
4639 /* Address families (we only support AF_INET and AF_UNIX) */
4641 PyModule_AddIntConstant(m
, "AF_UNSPEC", AF_UNSPEC
);
4643 PyModule_AddIntConstant(m
, "AF_INET", AF_INET
);
4645 PyModule_AddIntConstant(m
, "AF_INET6", AF_INET6
);
4646 #endif /* AF_INET6 */
4647 #if defined(AF_UNIX)
4648 PyModule_AddIntConstant(m
, "AF_UNIX", AF_UNIX
);
4649 #endif /* AF_UNIX */
4651 /* Amateur Radio AX.25 */
4652 PyModule_AddIntConstant(m
, "AF_AX25", AF_AX25
);
4655 PyModule_AddIntConstant(m
, "AF_IPX", AF_IPX
); /* Novell IPX */
4659 PyModule_AddIntConstant(m
, "AF_APPLETALK", AF_APPLETALK
);
4662 /* Amateur radio NetROM */
4663 PyModule_AddIntConstant(m
, "AF_NETROM", AF_NETROM
);
4666 /* Multiprotocol bridge */
4667 PyModule_AddIntConstant(m
, "AF_BRIDGE", AF_BRIDGE
);
4671 PyModule_AddIntConstant(m
, "AF_ATMPVC", AF_ATMPVC
);
4674 /* Reserved for Werner's ATM */
4675 PyModule_AddIntConstant(m
, "AF_AAL5", AF_AAL5
);
4678 /* Reserved for X.25 project */
4679 PyModule_AddIntConstant(m
, "AF_X25", AF_X25
);
4682 PyModule_AddIntConstant(m
, "AF_INET6", AF_INET6
); /* IP version 6 */
4685 /* Amateur Radio X.25 PLP */
4686 PyModule_AddIntConstant(m
, "AF_ROSE", AF_ROSE
);
4689 /* Reserved for DECnet project */
4690 PyModule_AddIntConstant(m
, "AF_DECnet", AF_DECnet
);
4693 /* Reserved for 802.2LLC project */
4694 PyModule_AddIntConstant(m
, "AF_NETBEUI", AF_NETBEUI
);
4697 /* Security callback pseudo AF */
4698 PyModule_AddIntConstant(m
, "AF_SECURITY", AF_SECURITY
);
4701 /* PF_KEY key management API */
4702 PyModule_AddIntConstant(m
, "AF_KEY", AF_KEY
);
4706 PyModule_AddIntConstant(m
, "AF_NETLINK", AF_NETLINK
);
4707 PyModule_AddIntConstant(m
, "NETLINK_ROUTE", NETLINK_ROUTE
);
4709 PyModule_AddIntConstant(m
, "NETLINK_SKIP", NETLINK_SKIP
);
4712 PyModule_AddIntConstant(m
, "NETLINK_W1", NETLINK_W1
);
4714 PyModule_AddIntConstant(m
, "NETLINK_USERSOCK", NETLINK_USERSOCK
);
4715 PyModule_AddIntConstant(m
, "NETLINK_FIREWALL", NETLINK_FIREWALL
);
4716 #ifdef NETLINK_TCPDIAG
4717 PyModule_AddIntConstant(m
, "NETLINK_TCPDIAG", NETLINK_TCPDIAG
);
4719 #ifdef NETLINK_NFLOG
4720 PyModule_AddIntConstant(m
, "NETLINK_NFLOG", NETLINK_NFLOG
);
4723 PyModule_AddIntConstant(m
, "NETLINK_XFRM", NETLINK_XFRM
);
4726 PyModule_AddIntConstant(m
, "NETLINK_ARPD", NETLINK_ARPD
);
4728 #ifdef NETLINK_ROUTE6
4729 PyModule_AddIntConstant(m
, "NETLINK_ROUTE6", NETLINK_ROUTE6
);
4731 PyModule_AddIntConstant(m
, "NETLINK_IP6_FW", NETLINK_IP6_FW
);
4732 #ifdef NETLINK_DNRTMSG
4733 PyModule_AddIntConstant(m
, "NETLINK_DNRTMSG", NETLINK_DNRTMSG
);
4735 #ifdef NETLINK_TAPBASE
4736 PyModule_AddIntConstant(m
, "NETLINK_TAPBASE", NETLINK_TAPBASE
);
4738 #endif /* AF_NETLINK */
4740 /* Alias to emulate 4.4BSD */
4741 PyModule_AddIntConstant(m
, "AF_ROUTE", AF_ROUTE
);
4745 PyModule_AddIntConstant(m
, "AF_ASH", AF_ASH
);
4749 PyModule_AddIntConstant(m
, "AF_ECONET", AF_ECONET
);
4753 PyModule_AddIntConstant(m
, "AF_ATMSVC", AF_ATMSVC
);
4756 /* Linux SNA Project (nutters!) */
4757 PyModule_AddIntConstant(m
, "AF_SNA", AF_SNA
);
4761 PyModule_AddIntConstant(m
, "AF_IRDA", AF_IRDA
);
4765 PyModule_AddIntConstant(m
, "AF_PPPOX", AF_PPPOX
);
4768 /* Wanpipe API Sockets */
4769 PyModule_AddIntConstant(m
, "AF_WANPIPE", AF_WANPIPE
);
4773 PyModule_AddIntConstant(m
, "AF_LLC", AF_LLC
);
4776 #ifdef USE_BLUETOOTH
4777 PyModule_AddIntConstant(m
, "AF_BLUETOOTH", AF_BLUETOOTH
);
4778 PyModule_AddIntConstant(m
, "BTPROTO_L2CAP", BTPROTO_L2CAP
);
4779 PyModule_AddIntConstant(m
, "BTPROTO_HCI", BTPROTO_HCI
);
4780 PyModule_AddIntConstant(m
, "SOL_HCI", SOL_HCI
);
4781 #if !defined(__NetBSD__) && !defined(__DragonFly__)
4782 PyModule_AddIntConstant(m
, "HCI_FILTER", HCI_FILTER
);
4784 #if !defined(__FreeBSD__)
4785 #if !defined(__NetBSD__) && !defined(__DragonFly__)
4786 PyModule_AddIntConstant(m
, "HCI_TIME_STAMP", HCI_TIME_STAMP
);
4788 PyModule_AddIntConstant(m
, "HCI_DATA_DIR", HCI_DATA_DIR
);
4789 PyModule_AddIntConstant(m
, "BTPROTO_SCO", BTPROTO_SCO
);
4791 PyModule_AddIntConstant(m
, "BTPROTO_RFCOMM", BTPROTO_RFCOMM
);
4792 PyModule_AddStringConstant(m
, "BDADDR_ANY", "00:00:00:00:00:00");
4793 PyModule_AddStringConstant(m
, "BDADDR_LOCAL", "00:00:00:FF:FF:FF");
4797 PyModule_AddIntMacro(m
, AF_PACKET
);
4800 PyModule_AddIntMacro(m
, PF_PACKET
);
4803 PyModule_AddIntMacro(m
, PACKET_HOST
);
4805 #ifdef PACKET_BROADCAST
4806 PyModule_AddIntMacro(m
, PACKET_BROADCAST
);
4808 #ifdef PACKET_MULTICAST
4809 PyModule_AddIntMacro(m
, PACKET_MULTICAST
);
4811 #ifdef PACKET_OTHERHOST
4812 PyModule_AddIntMacro(m
, PACKET_OTHERHOST
);
4814 #ifdef PACKET_OUTGOING
4815 PyModule_AddIntMacro(m
, PACKET_OUTGOING
);
4817 #ifdef PACKET_LOOPBACK
4818 PyModule_AddIntMacro(m
, PACKET_LOOPBACK
);
4820 #ifdef PACKET_FASTROUTE
4821 PyModule_AddIntMacro(m
, PACKET_FASTROUTE
);
4824 #ifdef HAVE_LINUX_TIPC_H
4825 PyModule_AddIntConstant(m
, "AF_TIPC", AF_TIPC
);
4828 PyModule_AddIntConstant(m
, "TIPC_ADDR_NAMESEQ", TIPC_ADDR_NAMESEQ
);
4829 PyModule_AddIntConstant(m
, "TIPC_ADDR_NAME", TIPC_ADDR_NAME
);
4830 PyModule_AddIntConstant(m
, "TIPC_ADDR_ID", TIPC_ADDR_ID
);
4832 PyModule_AddIntConstant(m
, "TIPC_ZONE_SCOPE", TIPC_ZONE_SCOPE
);
4833 PyModule_AddIntConstant(m
, "TIPC_CLUSTER_SCOPE", TIPC_CLUSTER_SCOPE
);
4834 PyModule_AddIntConstant(m
, "TIPC_NODE_SCOPE", TIPC_NODE_SCOPE
);
4836 /* for setsockopt() */
4837 PyModule_AddIntConstant(m
, "SOL_TIPC", SOL_TIPC
);
4838 PyModule_AddIntConstant(m
, "TIPC_IMPORTANCE", TIPC_IMPORTANCE
);
4839 PyModule_AddIntConstant(m
, "TIPC_SRC_DROPPABLE", TIPC_SRC_DROPPABLE
);
4840 PyModule_AddIntConstant(m
, "TIPC_DEST_DROPPABLE",
4841 TIPC_DEST_DROPPABLE
);
4842 PyModule_AddIntConstant(m
, "TIPC_CONN_TIMEOUT", TIPC_CONN_TIMEOUT
);
4844 PyModule_AddIntConstant(m
, "TIPC_LOW_IMPORTANCE",
4845 TIPC_LOW_IMPORTANCE
);
4846 PyModule_AddIntConstant(m
, "TIPC_MEDIUM_IMPORTANCE",
4847 TIPC_MEDIUM_IMPORTANCE
);
4848 PyModule_AddIntConstant(m
, "TIPC_HIGH_IMPORTANCE",
4849 TIPC_HIGH_IMPORTANCE
);
4850 PyModule_AddIntConstant(m
, "TIPC_CRITICAL_IMPORTANCE",
4851 TIPC_CRITICAL_IMPORTANCE
);
4853 /* for subscriptions */
4854 PyModule_AddIntConstant(m
, "TIPC_SUB_PORTS", TIPC_SUB_PORTS
);
4855 PyModule_AddIntConstant(m
, "TIPC_SUB_SERVICE", TIPC_SUB_SERVICE
);
4856 #ifdef TIPC_SUB_CANCEL
4857 /* doesn't seem to be available everywhere */
4858 PyModule_AddIntConstant(m
, "TIPC_SUB_CANCEL", TIPC_SUB_CANCEL
);
4860 PyModule_AddIntConstant(m
, "TIPC_WAIT_FOREVER", TIPC_WAIT_FOREVER
);
4861 PyModule_AddIntConstant(m
, "TIPC_PUBLISHED", TIPC_PUBLISHED
);
4862 PyModule_AddIntConstant(m
, "TIPC_WITHDRAWN", TIPC_WITHDRAWN
);
4863 PyModule_AddIntConstant(m
, "TIPC_SUBSCR_TIMEOUT", TIPC_SUBSCR_TIMEOUT
);
4864 PyModule_AddIntConstant(m
, "TIPC_CFG_SRV", TIPC_CFG_SRV
);
4865 PyModule_AddIntConstant(m
, "TIPC_TOP_SRV", TIPC_TOP_SRV
);
4869 PyModule_AddIntConstant(m
, "SOCK_STREAM", SOCK_STREAM
);
4870 PyModule_AddIntConstant(m
, "SOCK_DGRAM", SOCK_DGRAM
);
4872 /* We have incomplete socket support. */
4873 PyModule_AddIntConstant(m
, "SOCK_RAW", SOCK_RAW
);
4874 PyModule_AddIntConstant(m
, "SOCK_SEQPACKET", SOCK_SEQPACKET
);
4875 #if defined(SOCK_RDM)
4876 PyModule_AddIntConstant(m
, "SOCK_RDM", SOCK_RDM
);
4881 PyModule_AddIntConstant(m
, "SO_DEBUG", SO_DEBUG
);
4883 #ifdef SO_ACCEPTCONN
4884 PyModule_AddIntConstant(m
, "SO_ACCEPTCONN", SO_ACCEPTCONN
);
4887 PyModule_AddIntConstant(m
, "SO_REUSEADDR", SO_REUSEADDR
);
4889 #ifdef SO_EXCLUSIVEADDRUSE
4890 PyModule_AddIntConstant(m
, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE
);
4894 PyModule_AddIntConstant(m
, "SO_KEEPALIVE", SO_KEEPALIVE
);
4897 PyModule_AddIntConstant(m
, "SO_DONTROUTE", SO_DONTROUTE
);
4900 PyModule_AddIntConstant(m
, "SO_BROADCAST", SO_BROADCAST
);
4902 #ifdef SO_USELOOPBACK
4903 PyModule_AddIntConstant(m
, "SO_USELOOPBACK", SO_USELOOPBACK
);
4906 PyModule_AddIntConstant(m
, "SO_LINGER", SO_LINGER
);
4909 PyModule_AddIntConstant(m
, "SO_OOBINLINE", SO_OOBINLINE
);
4912 PyModule_AddIntConstant(m
, "SO_REUSEPORT", SO_REUSEPORT
);
4915 PyModule_AddIntConstant(m
, "SO_SNDBUF", SO_SNDBUF
);
4918 PyModule_AddIntConstant(m
, "SO_RCVBUF", SO_RCVBUF
);
4921 PyModule_AddIntConstant(m
, "SO_SNDLOWAT", SO_SNDLOWAT
);
4924 PyModule_AddIntConstant(m
, "SO_RCVLOWAT", SO_RCVLOWAT
);
4927 PyModule_AddIntConstant(m
, "SO_SNDTIMEO", SO_SNDTIMEO
);
4930 PyModule_AddIntConstant(m
, "SO_RCVTIMEO", SO_RCVTIMEO
);
4933 PyModule_AddIntConstant(m
, "SO_ERROR", SO_ERROR
);
4936 PyModule_AddIntConstant(m
, "SO_TYPE", SO_TYPE
);
4939 PyModule_AddIntConstant(m
, "SO_SETFIB", SO_SETFIB
);
4942 /* Maximum number of connections for "listen" */
4944 PyModule_AddIntConstant(m
, "SOMAXCONN", SOMAXCONN
);
4946 PyModule_AddIntConstant(m
, "SOMAXCONN", 5); /* Common value */
4949 /* Flags for send, recv */
4951 PyModule_AddIntConstant(m
, "MSG_OOB", MSG_OOB
);
4954 PyModule_AddIntConstant(m
, "MSG_PEEK", MSG_PEEK
);
4956 #ifdef MSG_DONTROUTE
4957 PyModule_AddIntConstant(m
, "MSG_DONTROUTE", MSG_DONTROUTE
);
4960 PyModule_AddIntConstant(m
, "MSG_DONTWAIT", MSG_DONTWAIT
);
4963 PyModule_AddIntConstant(m
, "MSG_EOR", MSG_EOR
);
4966 PyModule_AddIntConstant(m
, "MSG_TRUNC", MSG_TRUNC
);
4969 PyModule_AddIntConstant(m
, "MSG_CTRUNC", MSG_CTRUNC
);
4972 PyModule_AddIntConstant(m
, "MSG_WAITALL", MSG_WAITALL
);
4975 PyModule_AddIntConstant(m
, "MSG_BTAG", MSG_BTAG
);
4978 PyModule_AddIntConstant(m
, "MSG_ETAG", MSG_ETAG
);
4981 /* Protocol level and numbers, usable for [gs]etsockopt */
4983 PyModule_AddIntConstant(m
, "SOL_SOCKET", SOL_SOCKET
);
4986 PyModule_AddIntConstant(m
, "SOL_IP", SOL_IP
);
4988 PyModule_AddIntConstant(m
, "SOL_IP", 0);
4991 PyModule_AddIntConstant(m
, "SOL_IPX", SOL_IPX
);
4994 PyModule_AddIntConstant(m
, "SOL_AX25", SOL_AX25
);
4997 PyModule_AddIntConstant(m
, "SOL_ATALK", SOL_ATALK
);
5000 PyModule_AddIntConstant(m
, "SOL_NETROM", SOL_NETROM
);
5003 PyModule_AddIntConstant(m
, "SOL_ROSE", SOL_ROSE
);
5006 PyModule_AddIntConstant(m
, "SOL_TCP", SOL_TCP
);
5008 PyModule_AddIntConstant(m
, "SOL_TCP", 6);
5011 PyModule_AddIntConstant(m
, "SOL_UDP", SOL_UDP
);
5013 PyModule_AddIntConstant(m
, "SOL_UDP", 17);
5016 PyModule_AddIntConstant(m
, "IPPROTO_IP", IPPROTO_IP
);
5018 PyModule_AddIntConstant(m
, "IPPROTO_IP", 0);
5020 #ifdef IPPROTO_HOPOPTS
5021 PyModule_AddIntConstant(m
, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS
);
5024 PyModule_AddIntConstant(m
, "IPPROTO_ICMP", IPPROTO_ICMP
);
5026 PyModule_AddIntConstant(m
, "IPPROTO_ICMP", 1);
5029 PyModule_AddIntConstant(m
, "IPPROTO_IGMP", IPPROTO_IGMP
);
5032 PyModule_AddIntConstant(m
, "IPPROTO_GGP", IPPROTO_GGP
);
5035 PyModule_AddIntConstant(m
, "IPPROTO_IPV4", IPPROTO_IPV4
);
5038 PyModule_AddIntConstant(m
, "IPPROTO_IPV6", IPPROTO_IPV6
);
5041 PyModule_AddIntConstant(m
, "IPPROTO_IPIP", IPPROTO_IPIP
);
5044 PyModule_AddIntConstant(m
, "IPPROTO_TCP", IPPROTO_TCP
);
5046 PyModule_AddIntConstant(m
, "IPPROTO_TCP", 6);
5049 PyModule_AddIntConstant(m
, "IPPROTO_EGP", IPPROTO_EGP
);
5052 PyModule_AddIntConstant(m
, "IPPROTO_PUP", IPPROTO_PUP
);
5055 PyModule_AddIntConstant(m
, "IPPROTO_UDP", IPPROTO_UDP
);
5057 PyModule_AddIntConstant(m
, "IPPROTO_UDP", 17);
5060 PyModule_AddIntConstant(m
, "IPPROTO_IDP", IPPROTO_IDP
);
5062 #ifdef IPPROTO_HELLO
5063 PyModule_AddIntConstant(m
, "IPPROTO_HELLO", IPPROTO_HELLO
);
5066 PyModule_AddIntConstant(m
, "IPPROTO_ND", IPPROTO_ND
);
5069 PyModule_AddIntConstant(m
, "IPPROTO_TP", IPPROTO_TP
);
5072 PyModule_AddIntConstant(m
, "IPPROTO_IPV6", IPPROTO_IPV6
);
5074 #ifdef IPPROTO_ROUTING
5075 PyModule_AddIntConstant(m
, "IPPROTO_ROUTING", IPPROTO_ROUTING
);
5077 #ifdef IPPROTO_FRAGMENT
5078 PyModule_AddIntConstant(m
, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT
);
5081 PyModule_AddIntConstant(m
, "IPPROTO_RSVP", IPPROTO_RSVP
);
5084 PyModule_AddIntConstant(m
, "IPPROTO_GRE", IPPROTO_GRE
);
5087 PyModule_AddIntConstant(m
, "IPPROTO_ESP", IPPROTO_ESP
);
5090 PyModule_AddIntConstant(m
, "IPPROTO_AH", IPPROTO_AH
);
5092 #ifdef IPPROTO_MOBILE
5093 PyModule_AddIntConstant(m
, "IPPROTO_MOBILE", IPPROTO_MOBILE
);
5095 #ifdef IPPROTO_ICMPV6
5096 PyModule_AddIntConstant(m
, "IPPROTO_ICMPV6", IPPROTO_ICMPV6
);
5099 PyModule_AddIntConstant(m
, "IPPROTO_NONE", IPPROTO_NONE
);
5101 #ifdef IPPROTO_DSTOPTS
5102 PyModule_AddIntConstant(m
, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS
);
5105 PyModule_AddIntConstant(m
, "IPPROTO_XTP", IPPROTO_XTP
);
5108 PyModule_AddIntConstant(m
, "IPPROTO_EON", IPPROTO_EON
);
5111 PyModule_AddIntConstant(m
, "IPPROTO_PIM", IPPROTO_PIM
);
5113 #ifdef IPPROTO_IPCOMP
5114 PyModule_AddIntConstant(m
, "IPPROTO_IPCOMP", IPPROTO_IPCOMP
);
5117 PyModule_AddIntConstant(m
, "IPPROTO_VRRP", IPPROTO_VRRP
);
5120 PyModule_AddIntConstant(m
, "IPPROTO_BIP", IPPROTO_BIP
);
5124 PyModule_AddIntConstant(m
, "IPPROTO_RAW", IPPROTO_RAW
);
5126 PyModule_AddIntConstant(m
, "IPPROTO_RAW", 255);
5129 PyModule_AddIntConstant(m
, "IPPROTO_MAX", IPPROTO_MAX
);
5132 /* Some port configuration */
5133 #ifdef IPPORT_RESERVED
5134 PyModule_AddIntConstant(m
, "IPPORT_RESERVED", IPPORT_RESERVED
);
5136 PyModule_AddIntConstant(m
, "IPPORT_RESERVED", 1024);
5138 #ifdef IPPORT_USERRESERVED
5139 PyModule_AddIntConstant(m
, "IPPORT_USERRESERVED", IPPORT_USERRESERVED
);
5141 PyModule_AddIntConstant(m
, "IPPORT_USERRESERVED", 5000);
5144 /* Some reserved IP v.4 addresses */
5146 PyModule_AddIntConstant(m
, "INADDR_ANY", INADDR_ANY
);
5148 PyModule_AddIntConstant(m
, "INADDR_ANY", 0x00000000);
5150 #ifdef INADDR_BROADCAST
5151 PyModule_AddIntConstant(m
, "INADDR_BROADCAST", INADDR_BROADCAST
);
5153 PyModule_AddIntConstant(m
, "INADDR_BROADCAST", 0xffffffff);
5155 #ifdef INADDR_LOOPBACK
5156 PyModule_AddIntConstant(m
, "INADDR_LOOPBACK", INADDR_LOOPBACK
);
5158 PyModule_AddIntConstant(m
, "INADDR_LOOPBACK", 0x7F000001);
5160 #ifdef INADDR_UNSPEC_GROUP
5161 PyModule_AddIntConstant(m
, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP
);
5163 PyModule_AddIntConstant(m
, "INADDR_UNSPEC_GROUP", 0xe0000000);
5165 #ifdef INADDR_ALLHOSTS_GROUP
5166 PyModule_AddIntConstant(m
, "INADDR_ALLHOSTS_GROUP",
5167 INADDR_ALLHOSTS_GROUP
);
5169 PyModule_AddIntConstant(m
, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
5171 #ifdef INADDR_MAX_LOCAL_GROUP
5172 PyModule_AddIntConstant(m
, "INADDR_MAX_LOCAL_GROUP",
5173 INADDR_MAX_LOCAL_GROUP
);
5175 PyModule_AddIntConstant(m
, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
5178 PyModule_AddIntConstant(m
, "INADDR_NONE", INADDR_NONE
);
5180 PyModule_AddIntConstant(m
, "INADDR_NONE", 0xffffffff);
5183 /* IPv4 [gs]etsockopt options */
5185 PyModule_AddIntConstant(m
, "IP_OPTIONS", IP_OPTIONS
);
5188 PyModule_AddIntConstant(m
, "IP_HDRINCL", IP_HDRINCL
);
5191 PyModule_AddIntConstant(m
, "IP_TOS", IP_TOS
);
5194 PyModule_AddIntConstant(m
, "IP_TTL", IP_TTL
);
5197 PyModule_AddIntConstant(m
, "IP_RECVOPTS", IP_RECVOPTS
);
5199 #ifdef IP_RECVRETOPTS
5200 PyModule_AddIntConstant(m
, "IP_RECVRETOPTS", IP_RECVRETOPTS
);
5202 #ifdef IP_RECVDSTADDR
5203 PyModule_AddIntConstant(m
, "IP_RECVDSTADDR", IP_RECVDSTADDR
);
5206 PyModule_AddIntConstant(m
, "IP_RETOPTS", IP_RETOPTS
);
5208 #ifdef IP_MULTICAST_IF
5209 PyModule_AddIntConstant(m
, "IP_MULTICAST_IF", IP_MULTICAST_IF
);
5211 #ifdef IP_MULTICAST_TTL
5212 PyModule_AddIntConstant(m
, "IP_MULTICAST_TTL", IP_MULTICAST_TTL
);
5214 #ifdef IP_MULTICAST_LOOP
5215 PyModule_AddIntConstant(m
, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP
);
5217 #ifdef IP_ADD_MEMBERSHIP
5218 PyModule_AddIntConstant(m
, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP
);
5220 #ifdef IP_DROP_MEMBERSHIP
5221 PyModule_AddIntConstant(m
, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP
);
5223 #ifdef IP_DEFAULT_MULTICAST_TTL
5224 PyModule_AddIntConstant(m
, "IP_DEFAULT_MULTICAST_TTL",
5225 IP_DEFAULT_MULTICAST_TTL
);
5227 #ifdef IP_DEFAULT_MULTICAST_LOOP
5228 PyModule_AddIntConstant(m
, "IP_DEFAULT_MULTICAST_LOOP",
5229 IP_DEFAULT_MULTICAST_LOOP
);
5231 #ifdef IP_MAX_MEMBERSHIPS
5232 PyModule_AddIntConstant(m
, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS
);
5235 /* IPv6 [gs]etsockopt options, defined in RFC2553 */
5236 #ifdef IPV6_JOIN_GROUP
5237 PyModule_AddIntConstant(m
, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP
);
5239 #ifdef IPV6_LEAVE_GROUP
5240 PyModule_AddIntConstant(m
, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP
);
5242 #ifdef IPV6_MULTICAST_HOPS
5243 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS
);
5245 #ifdef IPV6_MULTICAST_IF
5246 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF
);
5248 #ifdef IPV6_MULTICAST_LOOP
5249 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP
);
5251 #ifdef IPV6_UNICAST_HOPS
5252 PyModule_AddIntConstant(m
, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS
);
5254 /* Additional IPV6 socket options, defined in RFC 3493 */
5256 PyModule_AddIntConstant(m
, "IPV6_V6ONLY", IPV6_V6ONLY
);
5258 /* Advanced IPV6 socket options, from RFC 3542 */
5259 #ifdef IPV6_CHECKSUM
5260 PyModule_AddIntConstant(m
, "IPV6_CHECKSUM", IPV6_CHECKSUM
);
5262 #ifdef IPV6_DONTFRAG
5263 PyModule_AddIntConstant(m
, "IPV6_DONTFRAG", IPV6_DONTFRAG
);
5266 PyModule_AddIntConstant(m
, "IPV6_DSTOPTS", IPV6_DSTOPTS
);
5268 #ifdef IPV6_HOPLIMIT
5269 PyModule_AddIntConstant(m
, "IPV6_HOPLIMIT", IPV6_HOPLIMIT
);
5272 PyModule_AddIntConstant(m
, "IPV6_HOPOPTS", IPV6_HOPOPTS
);
5275 PyModule_AddIntConstant(m
, "IPV6_NEXTHOP", IPV6_NEXTHOP
);
5278 PyModule_AddIntConstant(m
, "IPV6_PATHMTU", IPV6_PATHMTU
);
5281 PyModule_AddIntConstant(m
, "IPV6_PKTINFO", IPV6_PKTINFO
);
5283 #ifdef IPV6_RECVDSTOPTS
5284 PyModule_AddIntConstant(m
, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS
);
5286 #ifdef IPV6_RECVHOPLIMIT
5287 PyModule_AddIntConstant(m
, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT
);
5289 #ifdef IPV6_RECVHOPOPTS
5290 PyModule_AddIntConstant(m
, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS
);
5292 #ifdef IPV6_RECVPKTINFO
5293 PyModule_AddIntConstant(m
, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO
);
5295 #ifdef IPV6_RECVRTHDR
5296 PyModule_AddIntConstant(m
, "IPV6_RECVRTHDR", IPV6_RECVRTHDR
);
5298 #ifdef IPV6_RECVTCLASS
5299 PyModule_AddIntConstant(m
, "IPV6_RECVTCLASS", IPV6_RECVTCLASS
);
5302 PyModule_AddIntConstant(m
, "IPV6_RTHDR", IPV6_RTHDR
);
5304 #ifdef IPV6_RTHDRDSTOPTS
5305 PyModule_AddIntConstant(m
, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS
);
5307 #ifdef IPV6_RTHDR_TYPE_0
5308 PyModule_AddIntConstant(m
, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0
);
5310 #ifdef IPV6_RECVPATHMTU
5311 PyModule_AddIntConstant(m
, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU
);
5314 PyModule_AddIntConstant(m
, "IPV6_TCLASS", IPV6_TCLASS
);
5316 #ifdef IPV6_USE_MIN_MTU
5317 PyModule_AddIntConstant(m
, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU
);
5322 PyModule_AddIntConstant(m
, "TCP_NODELAY", TCP_NODELAY
);
5325 PyModule_AddIntConstant(m
, "TCP_MAXSEG", TCP_MAXSEG
);
5328 PyModule_AddIntConstant(m
, "TCP_CORK", TCP_CORK
);
5331 PyModule_AddIntConstant(m
, "TCP_KEEPIDLE", TCP_KEEPIDLE
);
5333 #ifdef TCP_KEEPINTVL
5334 PyModule_AddIntConstant(m
, "TCP_KEEPINTVL", TCP_KEEPINTVL
);
5337 PyModule_AddIntConstant(m
, "TCP_KEEPCNT", TCP_KEEPCNT
);
5340 PyModule_AddIntConstant(m
, "TCP_SYNCNT", TCP_SYNCNT
);
5343 PyModule_AddIntConstant(m
, "TCP_LINGER2", TCP_LINGER2
);
5345 #ifdef TCP_DEFER_ACCEPT
5346 PyModule_AddIntConstant(m
, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT
);
5348 #ifdef TCP_WINDOW_CLAMP
5349 PyModule_AddIntConstant(m
, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP
);
5352 PyModule_AddIntConstant(m
, "TCP_INFO", TCP_INFO
);
5355 PyModule_AddIntConstant(m
, "TCP_QUICKACK", TCP_QUICKACK
);
5361 PyModule_AddIntConstant(m
, "IPX_TYPE", IPX_TYPE
);
5364 /* get{addr,name}info parameters */
5365 #ifdef EAI_ADDRFAMILY
5366 PyModule_AddIntConstant(m
, "EAI_ADDRFAMILY", EAI_ADDRFAMILY
);
5369 PyModule_AddIntConstant(m
, "EAI_AGAIN", EAI_AGAIN
);
5372 PyModule_AddIntConstant(m
, "EAI_BADFLAGS", EAI_BADFLAGS
);
5375 PyModule_AddIntConstant(m
, "EAI_FAIL", EAI_FAIL
);
5378 PyModule_AddIntConstant(m
, "EAI_FAMILY", EAI_FAMILY
);
5381 PyModule_AddIntConstant(m
, "EAI_MEMORY", EAI_MEMORY
);
5384 PyModule_AddIntConstant(m
, "EAI_NODATA", EAI_NODATA
);
5387 PyModule_AddIntConstant(m
, "EAI_NONAME", EAI_NONAME
);
5390 PyModule_AddIntConstant(m
, "EAI_OVERFLOW", EAI_OVERFLOW
);
5393 PyModule_AddIntConstant(m
, "EAI_SERVICE", EAI_SERVICE
);
5396 PyModule_AddIntConstant(m
, "EAI_SOCKTYPE", EAI_SOCKTYPE
);
5399 PyModule_AddIntConstant(m
, "EAI_SYSTEM", EAI_SYSTEM
);
5402 PyModule_AddIntConstant(m
, "EAI_BADHINTS", EAI_BADHINTS
);
5405 PyModule_AddIntConstant(m
, "EAI_PROTOCOL", EAI_PROTOCOL
);
5408 PyModule_AddIntConstant(m
, "EAI_MAX", EAI_MAX
);
5411 PyModule_AddIntConstant(m
, "AI_PASSIVE", AI_PASSIVE
);
5414 PyModule_AddIntConstant(m
, "AI_CANONNAME", AI_CANONNAME
);
5416 #ifdef AI_NUMERICHOST
5417 PyModule_AddIntConstant(m
, "AI_NUMERICHOST", AI_NUMERICHOST
);
5419 #ifdef AI_NUMERICSERV
5420 PyModule_AddIntConstant(m
, "AI_NUMERICSERV", AI_NUMERICSERV
);
5423 PyModule_AddIntConstant(m
, "AI_MASK", AI_MASK
);
5426 PyModule_AddIntConstant(m
, "AI_ALL", AI_ALL
);
5428 #ifdef AI_V4MAPPED_CFG
5429 PyModule_AddIntConstant(m
, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG
);
5431 #ifdef AI_ADDRCONFIG
5432 PyModule_AddIntConstant(m
, "AI_ADDRCONFIG", AI_ADDRCONFIG
);
5435 PyModule_AddIntConstant(m
, "AI_V4MAPPED", AI_V4MAPPED
);
5438 PyModule_AddIntConstant(m
, "AI_DEFAULT", AI_DEFAULT
);
5441 PyModule_AddIntConstant(m
, "NI_MAXHOST", NI_MAXHOST
);
5444 PyModule_AddIntConstant(m
, "NI_MAXSERV", NI_MAXSERV
);
5447 PyModule_AddIntConstant(m
, "NI_NOFQDN", NI_NOFQDN
);
5449 #ifdef NI_NUMERICHOST
5450 PyModule_AddIntConstant(m
, "NI_NUMERICHOST", NI_NUMERICHOST
);
5453 PyModule_AddIntConstant(m
, "NI_NAMEREQD", NI_NAMEREQD
);
5455 #ifdef NI_NUMERICSERV
5456 PyModule_AddIntConstant(m
, "NI_NUMERICSERV", NI_NUMERICSERV
);
5459 PyModule_AddIntConstant(m
, "NI_DGRAM", NI_DGRAM
);
5462 /* shutdown() parameters */
5464 PyModule_AddIntConstant(m
, "SHUT_RD", SHUT_RD
);
5465 #elif defined(SD_RECEIVE)
5466 PyModule_AddIntConstant(m
, "SHUT_RD", SD_RECEIVE
);
5468 PyModule_AddIntConstant(m
, "SHUT_RD", 0);
5471 PyModule_AddIntConstant(m
, "SHUT_WR", SHUT_WR
);
5472 #elif defined(SD_SEND)
5473 PyModule_AddIntConstant(m
, "SHUT_WR", SD_SEND
);
5475 PyModule_AddIntConstant(m
, "SHUT_WR", 1);
5478 PyModule_AddIntConstant(m
, "SHUT_RDWR", SHUT_RDWR
);
5479 #elif defined(SD_BOTH)
5480 PyModule_AddIntConstant(m
, "SHUT_RDWR", SD_BOTH
);
5482 PyModule_AddIntConstant(m
, "SHUT_RDWR", 2);
5487 DWORD codes
[] = {SIO_RCVALL
, SIO_KEEPALIVE_VALS
};
5488 const char *names
[] = {"SIO_RCVALL", "SIO_KEEPALIVE_VALS"};
5490 for(i
= 0; i
<sizeof(codes
)/sizeof(*codes
); ++i
) {
5492 tmp
= PyLong_FromUnsignedLong(codes
[i
]);
5495 PyModule_AddObject(m
, names
[i
], tmp
);
5498 PyModule_AddIntConstant(m
, "RCVALL_OFF", RCVALL_OFF
);
5499 PyModule_AddIntConstant(m
, "RCVALL_ON", RCVALL_ON
);
5500 PyModule_AddIntConstant(m
, "RCVALL_SOCKETLEVELONLY", RCVALL_SOCKETLEVELONLY
);
5501 #ifdef RCVALL_IPLEVEL
5502 PyModule_AddIntConstant(m
, "RCVALL_IPLEVEL", RCVALL_IPLEVEL
);
5505 PyModule_AddIntConstant(m
, "RCVALL_MAX", RCVALL_MAX
);
5507 #endif /* _MSTCPIP_ */
5509 /* Initialize gethostbyname lock */
5510 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
5511 netdb_lock
= PyThread_allocate_lock();
5516 #ifndef HAVE_INET_PTON
5517 #if !defined(NTDDI_VERSION) || (NTDDI_VERSION < NTDDI_LONGHORN)
5519 /* Simplistic emulation code for inet_pton that only works for IPv4 */
5520 /* These are not exposed because they do not set errno properly */
5523 inet_pton(int af
, const char *src
, void *dst
)
5525 if (af
== AF_INET
) {
5526 #if (SIZEOF_INT != 4)
5527 #error "Not sure if in_addr_t exists and int is not 32-bits."
5529 unsigned int packed_addr
;
5530 packed_addr
= inet_addr(src
);
5531 if (packed_addr
== INADDR_NONE
)
5533 memcpy(dst
, &packed_addr
, 4);
5536 /* Should set errno to EAFNOSUPPORT */
5541 inet_ntop(int af
, const void *src
, char *dst
, socklen_t size
)
5543 if (af
== AF_INET
) {
5544 struct in_addr packed_addr
;
5546 /* Should set errno to ENOSPC. */
5548 memcpy(&packed_addr
, src
, sizeof(packed_addr
));
5549 return strncpy(dst
, inet_ntoa(packed_addr
), size
);
5551 /* Should set errno to EAFNOSUPPORT */