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"
97 #define MAX(x, y) ((x) < (y) ? (y) : (x))
99 /* Socket object documentation */
100 PyDoc_STRVAR(sock_doc
,
101 "socket([family[, type[, proto]]]) -> socket object\n\
103 Open a socket of the given type. The family argument specifies the\n\
104 address family; it defaults to AF_INET. The type argument specifies\n\
105 whether this is a stream (SOCK_STREAM, this is the default)\n\
106 or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0,\n\
107 specifying the default protocol. Keyword arguments are accepted.\n\
109 A socket object represents one endpoint of a network connection.\n\
111 Methods of socket objects (keyword arguments not allowed):\n\
113 accept() -- accept a connection, returning new socket and client address\n\
114 bind(addr) -- bind the socket to a local address\n\
115 close() -- close the socket\n\
116 connect(addr) -- connect the socket to a remote address\n\
117 connect_ex(addr) -- connect, return an error code instead of an exception\n\
118 dup() -- return a new socket object identical to the current one [*]\n\
119 fileno() -- return underlying file descriptor\n\
120 getpeername() -- return remote address [*]\n\
121 getsockname() -- return local address\n\
122 getsockopt(level, optname[, buflen]) -- get socket options\n\
123 gettimeout() -- return timeout or None\n\
124 listen(n) -- start listening for incoming connections\n\
125 makefile([mode, [bufsize]]) -- return a file object for the socket [*]\n\
126 recv(buflen[, flags]) -- receive data\n\
127 recv_into(buffer[, nbytes[, flags]]) -- receive data (into a buffer)\n\
128 recvfrom(buflen[, flags]) -- receive data and sender\'s address\n\
129 recvfrom_into(buffer[, nbytes, [, flags])\n\
130 -- receive data and sender\'s address (into a buffer)\n\
131 sendall(data[, flags]) -- send all data\n\
132 send(data[, flags]) -- send data, may not send all of it\n\
133 sendto(data[, flags], addr) -- send data to a given address\n\
134 setblocking(0 | 1) -- set or clear the blocking I/O flag\n\
135 setsockopt(level, optname, value) -- set socket options\n\
136 settimeout(None | float) -- set or clear the timeout\n\
137 shutdown(how) -- shut down traffic in one or both directions\n\
139 [*] not available on all platforms!");
141 /* XXX This is a terrible mess of platform-dependent preprocessor hacks.
142 I hope some day someone can clean this up please... */
144 /* Hacks for gethostbyname_r(). On some non-Linux platforms, the configure
145 script doesn't get this right, so we hardcode some platform checks below.
146 On the other hand, not all Linux versions agree, so there the settings
147 computed by the configure script are needed! */
150 # undef HAVE_GETHOSTBYNAME_R_3_ARG
151 # undef HAVE_GETHOSTBYNAME_R_5_ARG
152 # undef HAVE_GETHOSTBYNAME_R_6_ARG
156 # undef HAVE_GETHOSTBYNAME_R
159 #ifdef HAVE_GETHOSTBYNAME_R
160 # if defined(_AIX) || defined(__osf__)
161 # define HAVE_GETHOSTBYNAME_R_3_ARG
162 # elif defined(__sun) || defined(__sgi)
163 # define HAVE_GETHOSTBYNAME_R_5_ARG
164 # elif defined(linux)
165 /* Rely on the configure script */
167 # undef HAVE_GETHOSTBYNAME_R
171 #if !defined(HAVE_GETHOSTBYNAME_R) && defined(WITH_THREAD) && \
173 # define USE_GETHOSTBYNAME_LOCK
176 /* To use __FreeBSD_version */
177 #ifdef HAVE_SYS_PARAM_H
178 #include <sys/param.h>
180 /* On systems on which getaddrinfo() is believed to not be thread-safe,
181 (this includes the getaddrinfo emulation) protect access with a lock. */
182 #if defined(WITH_THREAD) && (defined(__APPLE__) || \
183 (defined(__FreeBSD__) && __FreeBSD_version+0 < 503000) || \
184 defined(__OpenBSD__) || defined(__NetBSD__) || \
185 defined(__VMS) || !defined(HAVE_GETADDRINFO))
186 #define USE_GETADDRINFO_LOCK
189 #ifdef USE_GETADDRINFO_LOCK
190 #define ACQUIRE_GETADDRINFO_LOCK PyThread_acquire_lock(netdb_lock, 1);
191 #define RELEASE_GETADDRINFO_LOCK PyThread_release_lock(netdb_lock);
193 #define ACQUIRE_GETADDRINFO_LOCK
194 #define RELEASE_GETADDRINFO_LOCK
197 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
198 # include "pythread.h"
201 #if defined(PYCC_VACPP)
204 # include <sys/ioctl.h>
213 #if defined(PYOS_OS2)
215 # define INCL_DOSERRORS
216 # define INCL_NOPMAPI
220 #if defined(__sgi) && _COMPILER_VERSION>700 && !_SGIAPI
221 /* make sure that the reentrant (gethostbyaddr_r etc)
222 functions are declared correctly if compiling with
223 MIPSPro 7.x in ANSI C mode (default) */
225 /* XXX Using _SGIAPI is the wrong thing,
226 but I don't know what the right thing is. */
227 #undef _SGIAPI /* to avoid warning */
231 #include <sys/socket.h>
232 #include <sys/types.h>
233 #include <netinet/in.h>
235 #define HAVE_GETADDRINFO 1
236 #define HAVE_GETNAMEINFO 1
239 #define HAVE_INET_PTON
243 /* Irix 6.5 fails to define this variable at all. This is needed
244 for both GCC and SGI's compiler. I'd say that the SGI headers
245 are just busted. Same thing for Solaris. */
246 #if (defined(__sgi) || defined(sun)) && !defined(INET_ADDRSTRLEN)
247 #define INET_ADDRSTRLEN 16
250 /* Generic includes */
251 #ifdef HAVE_SYS_TYPES_H
252 #include <sys/types.h>
255 /* Generic socket object definitions and includes */
256 #define PySocket_BUILDING_SOCKET
257 #include "socketmodule.h"
259 /* Addressing includes */
263 /* Non-MS WINDOWS includes */
266 /* Headers needed for inet_ntoa() and inet_addr() */
268 # include <net/netdb.h>
269 # elif defined(PYOS_OS2) && defined(PYCC_VACPP)
271 typedef size_t socklen_t
;
273 # include <arpa/inet.h>
279 # include <sys/ioctl.h>
280 # include <socklib.h>
282 int h_errno
; /* not used */
283 # define INET_ADDRSTRLEN 16
288 /* MS_WINDOWS includes */
298 # define offsetof(type, member) ((size_t)(&((type *)0)->member))
302 # define O_NONBLOCK O_NDELAY
305 /* include Python's addrinfo.h unless it causes trouble */
306 #if defined(__sgi) && _COMPILER_VERSION>700 && defined(_SS_ALIGNSIZE)
307 /* Do not include addinfo.h on some newer IRIX versions.
308 * _SS_ALIGNSIZE is defined in sys/socket.h by 6.5.21,
309 * for example, but not by 6.5.10.
311 #elif defined(_MSC_VER) && _MSC_VER>1201
312 /* Do not include addrinfo.h for MSVC7 or greater. 'addrinfo' and
313 * EAI_* constants are defined in (the already included) ws2tcpip.h.
316 # include "addrinfo.h"
319 #ifndef HAVE_INET_PTON
320 #if !defined(NTDDI_VERSION) || (NTDDI_VERSION < NTDDI_LONGHORN)
321 int inet_pton(int af
, const char *src
, void *dst
);
322 const char *inet_ntop(int af
, const void *src
, char *dst
, socklen_t size
);
327 /* On OS X, getaddrinfo returns no error indication of lookup
328 failure, so we must use the emulation instead of the libinfo
329 implementation. Unfortunately, performing an autoconf test
330 for this bug would require DNS access for the machine performing
331 the configuration, which is not acceptable. Therefore, we
332 determine the bug just by checking for __APPLE__. If this bug
333 gets ever fixed, perhaps checking for sys/version.h would be
334 appropriate, which is 10/0 on the system with the bug. */
335 #ifndef HAVE_GETNAMEINFO
336 /* This bug seems to be fixed in Jaguar. Ths easiest way I could
337 Find to check for Jaguar is that it has getnameinfo(), which
338 older releases don't have */
339 #undef HAVE_GETADDRINFO
342 #ifdef HAVE_INET_ATON
343 #define USE_INET_ATON_WEAKLINK
348 /* I know this is a bad practice, but it is the easiest... */
349 #if !defined(HAVE_GETADDRINFO)
350 /* avoid clashes with the C library definition of the symbol. */
351 #define getaddrinfo fake_getaddrinfo
352 #define gai_strerror fake_gai_strerror
353 #define freeaddrinfo fake_freeaddrinfo
354 #include "getaddrinfo.c"
356 #if !defined(HAVE_GETNAMEINFO)
357 #define getnameinfo fake_getnameinfo
358 #include "getnameinfo.c"
361 #if defined(MS_WINDOWS) || defined(__BEOS__)
362 /* BeOS suffers from the same socket dichotomy as Win32... - [cjh] */
363 /* seem to be a few differences in the API */
364 #define SOCKETCLOSE closesocket
365 #define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */
369 #define EAFNOSUPPORT WSAEAFNOSUPPORT
370 #define snprintf _snprintf
373 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
374 #define SOCKETCLOSE soclose
375 #define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
379 #define SOCKETCLOSE close
382 #if defined(HAVE_BLUETOOTH_H) || defined(HAVE_BLUETOOTH_BLUETOOTH_H)
383 #define USE_BLUETOOTH 1
384 #if defined(__FreeBSD__)
385 #define BTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP
386 #define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM
387 #define BTPROTO_HCI BLUETOOTH_PROTO_HCI
388 #define SOL_HCI SOL_HCI_RAW
389 #define HCI_FILTER SO_HCI_RAW_FILTER
390 #define sockaddr_l2 sockaddr_l2cap
391 #define sockaddr_rc sockaddr_rfcomm
392 #define hci_dev hci_node
393 #define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb)
394 #define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)
395 #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
396 #elif defined(__NetBSD__)
397 #define sockaddr_l2 sockaddr_bt
398 #define sockaddr_rc sockaddr_bt
399 #define sockaddr_hci sockaddr_bt
400 #define sockaddr_sco sockaddr_bt
401 #define _BT_L2_MEMB(sa, memb) ((sa)->bt_##memb)
402 #define _BT_RC_MEMB(sa, memb) ((sa)->bt_##memb)
403 #define _BT_HCI_MEMB(sa, memb) ((sa)->bt_##memb)
404 #define _BT_SCO_MEMB(sa, memb) ((sa)->bt_##memb)
406 #define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb)
407 #define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb)
408 #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
409 #define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)
414 /* TCP/IP Services for VMS uses a maximum send/recv buffer length */
415 #define SEGMENT_SIZE (32 * 1024 -1)
418 #define SAS2SA(x) ((struct sockaddr *)(x))
421 * Constants for getnameinfo()
423 #if !defined(NI_MAXHOST)
424 #define NI_MAXHOST 1025
426 #if !defined(NI_MAXSERV)
427 #define NI_MAXSERV 32
430 /* XXX There's a problem here: *static* functions are not supposed to have
431 a Py prefix (or use CapitalizedWords). Later... */
433 /* Global variable holding the exception type for errors detected
434 by this module (but not argument type or memory errors, etc.). */
435 static PyObject
*socket_error
;
436 static PyObject
*socket_herror
;
437 static PyObject
*socket_gaierror
;
438 static PyObject
*socket_timeout
;
441 /* Global variable which is !=0 if Python is running in a RISC OS taskwindow */
442 static int taskwindow
;
445 /* A forward reference to the socket type object.
446 The sock_type variable contains pointers to various functions,
447 some of which call new_sockobject(), which uses sock_type, so
448 there has to be a circular reference. */
449 static PyTypeObject sock_type
;
451 #if defined(HAVE_POLL_H)
453 #elif defined(HAVE_SYS_POLL_H)
454 #include <sys/poll.h>
457 #ifdef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
458 /* Platform can select file descriptors beyond FD_SETSIZE */
459 #define IS_SELECTABLE(s) 1
460 #elif defined(HAVE_POLL)
461 /* Instead of select(), we'll use poll() since poll() works on any fd. */
462 #define IS_SELECTABLE(s) 1
463 /* Can we call select() with this socket without a buffer overrun? */
465 /* POSIX says selecting file descriptors beyond FD_SETSIZE
466 has undefined behaviour. If there's no timeout left, we don't have to
467 call select, so it's a safe, little white lie. */
468 #define IS_SELECTABLE(s) ((s)->sock_fd < FD_SETSIZE || s->sock_timeout <= 0.0)
474 PyErr_SetString(socket_error
, "unable to select on socket");
478 /* Convenience function to raise an error according to errno
479 and return a NULL pointer from a function. */
485 int err_no
= WSAGetLastError();
486 /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which
487 recognizes the error codes used by both GetLastError() and
490 return PyErr_SetExcFromWindowsErr(socket_error
, err_no
);
493 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
494 if (sock_errno() != NO_ERROR
) {
498 int myerrorcode
= sock_errno();
500 /* Retrieve socket-related error message from MPTN.MSG file */
501 rc
= DosGetMessage(NULL
, 0, outbuf
, sizeof(outbuf
),
502 myerrorcode
- SOCBASEERR
+ 26,
505 if (rc
== NO_ERROR
) {
508 /* OS/2 doesn't guarantee a terminator */
509 outbuf
[msglen
] = '\0';
510 if (strlen(outbuf
) > 0) {
511 /* If non-empty msg, trim CRLF */
512 char *lastc
= &outbuf
[ strlen(outbuf
)-1 ];
513 while (lastc
> outbuf
&&
514 isspace(Py_CHARMASK(*lastc
))) {
515 /* Trim trailing whitespace (CRLF) */
519 v
= Py_BuildValue("(is)", myerrorcode
, outbuf
);
521 PyErr_SetObject(socket_error
, v
);
530 if (_inet_error
.errnum
!= NULL
) {
532 v
= Py_BuildValue("(is)", errno
, _inet_err());
534 PyErr_SetObject(socket_error
, v
);
541 return PyErr_SetFromErrno(socket_error
);
546 set_herror(int h_error
)
550 #ifdef HAVE_HSTRERROR
551 v
= Py_BuildValue("(is)", h_error
, (char *)hstrerror(h_error
));
553 v
= Py_BuildValue("(is)", h_error
, "host not found");
556 PyErr_SetObject(socket_herror
, v
);
565 set_gaierror(int error
)
570 /* EAI_SYSTEM is not available on Windows XP. */
571 if (error
== EAI_SYSTEM
)
575 #ifdef HAVE_GAI_STRERROR
576 v
= Py_BuildValue("(is)", error
, gai_strerror(error
));
578 v
= Py_BuildValue("(is)", error
, "getaddrinfo failed");
581 PyErr_SetObject(socket_gaierror
, v
);
589 /* Function to send in segments */
591 sendsegmented(int sock_fd
, char *buf
, int len
, int flags
)
596 while (remaining
> 0) {
597 unsigned int segment
;
599 segment
= (remaining
>= SEGMENT_SIZE
? SEGMENT_SIZE
: remaining
);
600 n
= send(sock_fd
, buf
, segment
, flags
);
604 remaining
-= segment
;
612 /* Function to perform the setting of socket blocking mode
613 internally. block = (1 | 0). */
615 internal_setblocking(PySocketSockObject
*s
, int block
)
623 Py_BEGIN_ALLOW_THREADS
626 setsockopt(s
->sock_fd
, SOL_SOCKET
, SO_NONBLOCK
,
627 (void *)(&block
), sizeof(int));
631 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
633 ioctl(s
->sock_fd
, FIONBIO
, (caddr_t
)&block
, sizeof(block
));
636 ioctl(s
->sock_fd
, FIONBIO
, (unsigned int *)&block
);
637 #else /* !PYOS_OS2 && !__VMS */
638 delay_flag
= fcntl(s
->sock_fd
, F_GETFL
, 0);
640 delay_flag
&= (~O_NONBLOCK
);
642 delay_flag
|= O_NONBLOCK
;
643 fcntl(s
->sock_fd
, F_SETFL
, delay_flag
);
644 #endif /* !PYOS_OS2 */
645 #else /* MS_WINDOWS */
647 ioctlsocket(s
->sock_fd
, FIONBIO
, (u_long
*)&block
);
648 #endif /* MS_WINDOWS */
651 socketioctl(s
->sock_fd
, FIONBIO
, (u_long
*)&block
);
653 #endif /* __BEOS__ */
656 /* Since these don't return anything */
660 /* Do a select()/poll() on the socket, if necessary (sock_timeout > 0).
661 The argument writing indicates the direction.
662 This does not raise an exception; we'll let our caller do that
663 after they've reacquired the interpreter lock.
664 Returns 1 on timeout, -1 on error, 0 otherwise. */
666 internal_select(PySocketSockObject
*s
, int writing
)
670 /* Nothing to do unless we're in timeout mode (not non-blocking) */
671 if (s
->sock_timeout
<= 0.0)
674 /* Guard against closed socket */
678 /* Prefer poll, if available, since you can poll() any fd
679 * which can't be done with select(). */
682 struct pollfd pollfd
;
685 pollfd
.fd
= s
->sock_fd
;
686 pollfd
.events
= writing
? POLLOUT
: POLLIN
;
688 /* s->sock_timeout is in seconds, timeout in ms */
689 timeout
= (int)(s
->sock_timeout
* 1000 + 0.5);
690 n
= poll(&pollfd
, 1, timeout
);
694 /* Construct the arguments to select */
697 tv
.tv_sec
= (int)s
->sock_timeout
;
698 tv
.tv_usec
= (int)((s
->sock_timeout
- tv
.tv_sec
) * 1e6
);
700 FD_SET(s
->sock_fd
, &fds
);
702 /* See if the socket is ready */
704 n
= select(s
->sock_fd
+1, NULL
, &fds
, NULL
, &tv
);
706 n
= select(s
->sock_fd
+1, &fds
, NULL
, NULL
, &tv
);
717 /* Initialize a new socket object. */
719 static double defaulttimeout
= -1.0; /* Default timeout for new sockets */
722 init_sockobject(PySocketSockObject
*s
,
723 SOCKET_T fd
, int family
, int type
, int proto
)
729 s
->sock_family
= family
;
731 s
->sock_proto
= proto
;
732 s
->sock_timeout
= defaulttimeout
;
734 s
->errorhandler
= &set_error
;
736 if (defaulttimeout
>= 0.0)
737 internal_setblocking(s
, 0);
741 socketioctl(s
->sock_fd
, 0x80046679, (u_long
*)&block
);
746 /* Create a new socket object.
747 This just creates the object and initializes it.
748 If the creation fails, return NULL and set an exception (implicit
751 static PySocketSockObject
*
752 new_sockobject(SOCKET_T fd
, int family
, int type
, int proto
)
754 PySocketSockObject
*s
;
755 s
= (PySocketSockObject
*)
756 PyType_GenericNew(&sock_type
, NULL
, NULL
);
758 init_sockobject(s
, fd
, family
, type
, proto
);
763 /* Lock to allow python interpreter to continue, but only allow one
764 thread to be in gethostbyname or getaddrinfo */
765 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
766 PyThread_type_lock netdb_lock
;
770 /* Convert a string specifying a host name or one of a few symbolic
771 names to a numeric IP address. This usually calls gethostbyname()
772 to do the work; the names "" and "<broadcast>" are special.
773 Return the length (IPv4 should be 4 bytes), or negative if
774 an error occurred; then an exception is raised. */
777 setipaddr(char *name
, struct sockaddr
*addr_ret
, size_t addr_ret_size
, int af
)
779 struct addrinfo hints
, *res
;
784 memset((void *) addr_ret
, '\0', sizeof(*addr_ret
));
785 if (name
[0] == '\0') {
787 memset(&hints
, 0, sizeof(hints
));
788 hints
.ai_family
= af
;
789 hints
.ai_socktype
= SOCK_DGRAM
; /*dummy*/
790 hints
.ai_flags
= AI_PASSIVE
;
791 Py_BEGIN_ALLOW_THREADS
792 ACQUIRE_GETADDRINFO_LOCK
793 error
= getaddrinfo(NULL
, "0", &hints
, &res
);
795 /* We assume that those thread-unsafe getaddrinfo() versions
796 *are* safe regarding their return value, ie. that a
797 subsequent call to getaddrinfo() does not destroy the
798 outcome of the first call. */
799 RELEASE_GETADDRINFO_LOCK
804 switch (res
->ai_family
) {
815 PyErr_SetString(socket_error
,
816 "unsupported address family");
821 PyErr_SetString(socket_error
,
822 "wildcard resolved to multiple address");
825 if (res
->ai_addrlen
< addr_ret_size
)
826 addr_ret_size
= res
->ai_addrlen
;
827 memcpy(addr_ret
, res
->ai_addr
, addr_ret_size
);
831 if (name
[0] == '<' && strcmp(name
, "<broadcast>") == 0) {
832 struct sockaddr_in
*sin
;
833 if (af
!= AF_INET
&& af
!= AF_UNSPEC
) {
834 PyErr_SetString(socket_error
,
835 "address family mismatched");
838 sin
= (struct sockaddr_in
*)addr_ret
;
839 memset((void *) sin
, '\0', sizeof(*sin
));
840 sin
->sin_family
= AF_INET
;
841 #ifdef HAVE_SOCKADDR_SA_LEN
842 sin
->sin_len
= sizeof(*sin
);
844 sin
->sin_addr
.s_addr
= INADDR_BROADCAST
;
845 return sizeof(sin
->sin_addr
);
847 if (sscanf(name
, "%d.%d.%d.%d%c", &d1
, &d2
, &d3
, &d4
, &ch
) == 4 &&
848 0 <= d1
&& d1
<= 255 && 0 <= d2
&& d2
<= 255 &&
849 0 <= d3
&& d3
<= 255 && 0 <= d4
&& d4
<= 255) {
850 struct sockaddr_in
*sin
;
851 sin
= (struct sockaddr_in
*)addr_ret
;
852 sin
->sin_addr
.s_addr
= htonl(
853 ((long) d1
<< 24) | ((long) d2
<< 16) |
854 ((long) d3
<< 8) | ((long) d4
<< 0));
855 sin
->sin_family
= AF_INET
;
856 #ifdef HAVE_SOCKADDR_SA_LEN
857 sin
->sin_len
= sizeof(*sin
);
861 memset(&hints
, 0, sizeof(hints
));
862 hints
.ai_family
= af
;
863 Py_BEGIN_ALLOW_THREADS
864 ACQUIRE_GETADDRINFO_LOCK
865 error
= getaddrinfo(name
, NULL
, &hints
, &res
);
866 #if defined(__digital__) && defined(__unix__)
867 if (error
== EAI_NONAME
&& af
== AF_UNSPEC
) {
868 /* On Tru64 V5.1, numeric-to-addr conversion fails
869 if no address family is given. Assume IPv4 for now.*/
870 hints
.ai_family
= AF_INET
;
871 error
= getaddrinfo(name
, NULL
, &hints
, &res
);
875 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
880 if (res
->ai_addrlen
< addr_ret_size
)
881 addr_ret_size
= res
->ai_addrlen
;
882 memcpy((char *) addr_ret
, res
->ai_addr
, addr_ret_size
);
884 switch (addr_ret
->sa_family
) {
892 PyErr_SetString(socket_error
, "unknown address family");
898 /* Create a string object representing an IP address.
899 This is always a string of the form 'dd.dd.dd.dd' (with variable
903 makeipaddr(struct sockaddr
*addr
, int addrlen
)
905 char buf
[NI_MAXHOST
];
908 error
= getnameinfo(addr
, addrlen
, buf
, sizeof(buf
), NULL
, 0,
914 return PyString_FromString(buf
);
919 /* Convert a string representation of a Bluetooth address into a numeric
920 address. Returns the length (6), or raises an exception and returns -1 if
921 an error occurred. */
924 setbdaddr(char *name
, bdaddr_t
*bdaddr
)
926 unsigned int b0
, b1
, b2
, b3
, b4
, b5
;
930 n
= sscanf(name
, "%X:%X:%X:%X:%X:%X%c",
931 &b5
, &b4
, &b3
, &b2
, &b1
, &b0
, &ch
);
932 if (n
== 6 && (b0
| b1
| b2
| b3
| b4
| b5
) < 256) {
941 PyErr_SetString(socket_error
, "bad bluetooth address");
946 /* Create a string representation of the Bluetooth address. This is always a
947 string of the form 'XX:XX:XX:XX:XX:XX' where XX is a two digit hexadecimal
948 value (zero padded if necessary). */
951 makebdaddr(bdaddr_t
*bdaddr
)
953 char buf
[(6 * 2) + 5 + 1];
955 sprintf(buf
, "%02X:%02X:%02X:%02X:%02X:%02X",
956 bdaddr
->b
[5], bdaddr
->b
[4], bdaddr
->b
[3],
957 bdaddr
->b
[2], bdaddr
->b
[1], bdaddr
->b
[0]);
958 return PyString_FromString(buf
);
963 /* Create an object representing the given socket address,
964 suitable for passing it back to bind(), connect() etc.
965 The family field of the sockaddr structure is inspected
966 to determine what kind of address it really is. */
970 makesockaddr(int sockfd
, struct sockaddr
*addr
, int addrlen
, int proto
)
973 /* No address -- may be recvfrom() from known socket */
979 /* XXX: BeOS version of accept() doesn't set family correctly */
980 addr
->sa_family
= AF_INET
;
983 switch (addr
->sa_family
) {
987 struct sockaddr_in
*a
;
988 PyObject
*addrobj
= makeipaddr(addr
, sizeof(*a
));
989 PyObject
*ret
= NULL
;
991 a
= (struct sockaddr_in
*)addr
;
992 ret
= Py_BuildValue("Oi", addrobj
, ntohs(a
->sin_port
));
1001 struct sockaddr_un
*a
= (struct sockaddr_un
*) addr
;
1003 if (a
->sun_path
[0] == 0) { /* Linux abstract namespace */
1004 addrlen
-= (sizeof(*a
) - sizeof(a
->sun_path
));
1005 return PyString_FromStringAndSize(a
->sun_path
,
1011 /* regular NULL-terminated string */
1012 return PyString_FromString(a
->sun_path
);
1015 #endif /* AF_UNIX */
1017 #if defined(AF_NETLINK)
1020 struct sockaddr_nl
*a
= (struct sockaddr_nl
*) addr
;
1021 return Py_BuildValue("II", a
->nl_pid
, a
->nl_groups
);
1023 #endif /* AF_NETLINK */
1028 struct sockaddr_in6
*a
;
1029 PyObject
*addrobj
= makeipaddr(addr
, sizeof(*a
));
1030 PyObject
*ret
= NULL
;
1032 a
= (struct sockaddr_in6
*)addr
;
1033 ret
= Py_BuildValue("Oiii",
1035 ntohs(a
->sin6_port
),
1044 #ifdef USE_BLUETOOTH
1050 struct sockaddr_l2
*a
= (struct sockaddr_l2
*) addr
;
1051 PyObject
*addrobj
= makebdaddr(&_BT_L2_MEMB(a
, bdaddr
));
1052 PyObject
*ret
= NULL
;
1054 ret
= Py_BuildValue("Oi",
1056 _BT_L2_MEMB(a
, psm
));
1062 case BTPROTO_RFCOMM
:
1064 struct sockaddr_rc
*a
= (struct sockaddr_rc
*) addr
;
1065 PyObject
*addrobj
= makebdaddr(&_BT_RC_MEMB(a
, bdaddr
));
1066 PyObject
*ret
= NULL
;
1068 ret
= Py_BuildValue("Oi",
1070 _BT_RC_MEMB(a
, channel
));
1078 struct sockaddr_hci
*a
= (struct sockaddr_hci
*) addr
;
1079 PyObject
*ret
= NULL
;
1080 ret
= Py_BuildValue("i", _BT_HCI_MEMB(a
, dev
));
1084 #if !defined(__FreeBSD__)
1087 struct sockaddr_sco
*a
= (struct sockaddr_sco
*) addr
;
1088 return makebdaddr(&_BT_SCO_MEMB(a
, bdaddr
));
1095 #ifdef HAVE_NETPACKET_PACKET_H
1098 struct sockaddr_ll
*a
= (struct sockaddr_ll
*)addr
;
1101 /* need to look up interface name give index */
1102 if (a
->sll_ifindex
) {
1103 ifr
.ifr_ifindex
= a
->sll_ifindex
;
1104 if (ioctl(sockfd
, SIOCGIFNAME
, &ifr
) == 0)
1105 ifname
= ifr
.ifr_name
;
1107 return Py_BuildValue("shbhs#",
1109 ntohs(a
->sll_protocol
),
1117 #ifdef HAVE_LINUX_TIPC_H
1120 struct sockaddr_tipc
*a
= (struct sockaddr_tipc
*) addr
;
1121 if (a
->addrtype
== TIPC_ADDR_NAMESEQ
) {
1122 return Py_BuildValue("IIIII",
1124 a
->addr
.nameseq
.type
,
1125 a
->addr
.nameseq
.lower
,
1126 a
->addr
.nameseq
.upper
,
1128 } else if (a
->addrtype
== TIPC_ADDR_NAME
) {
1129 return Py_BuildValue("IIIII",
1131 a
->addr
.name
.name
.type
,
1132 a
->addr
.name
.name
.instance
,
1133 a
->addr
.name
.name
.instance
,
1135 } else if (a
->addrtype
== TIPC_ADDR_ID
) {
1136 return Py_BuildValue("IIIII",
1143 PyErr_SetString(PyExc_TypeError
,
1144 "Invalid address type");
1150 /* More cases here... */
1153 /* If we don't know the address family, don't raise an
1154 exception -- return it as a tuple. */
1155 return Py_BuildValue("is#",
1158 sizeof(addr
->sa_data
));
1164 /* Parse a socket address argument according to the socket object's
1165 address family. Return 1 if the address was in the proper format,
1166 0 of not. The address is returned through addr_ret, its length
1170 getsockaddrarg(PySocketSockObject
*s
, PyObject
*args
,
1171 struct sockaddr
*addr_ret
, int *len_ret
)
1173 switch (s
->sock_family
) {
1175 #if defined(AF_UNIX)
1178 struct sockaddr_un
* addr
;
1181 if (!PyArg_Parse(args
, "t#", &path
, &len
))
1184 addr
= (struct sockaddr_un
*)addr_ret
;
1186 if (len
> 0 && path
[0] == 0) {
1187 /* Linux abstract namespace extension */
1188 if (len
> sizeof addr
->sun_path
) {
1189 PyErr_SetString(socket_error
,
1190 "AF_UNIX path too long");
1197 /* regular NULL-terminated string */
1198 if (len
>= sizeof addr
->sun_path
) {
1199 PyErr_SetString(socket_error
,
1200 "AF_UNIX path too long");
1203 addr
->sun_path
[len
] = 0;
1205 addr
->sun_family
= s
->sock_family
;
1206 memcpy(addr
->sun_path
, path
, len
);
1207 #if defined(PYOS_OS2)
1208 *len_ret
= sizeof(*addr
);
1210 *len_ret
= len
+ sizeof(*addr
) - sizeof(addr
->sun_path
);
1214 #endif /* AF_UNIX */
1216 #if defined(AF_NETLINK)
1219 struct sockaddr_nl
* addr
;
1221 addr
= (struct sockaddr_nl
*)addr_ret
;
1222 if (!PyTuple_Check(args
)) {
1226 "AF_NETLINK address must be tuple, not %.500s",
1227 Py_TYPE(args
)->tp_name
);
1230 if (!PyArg_ParseTuple(args
, "II:getsockaddrarg", &pid
, &groups
))
1232 addr
->nl_family
= AF_NETLINK
;
1234 addr
->nl_groups
= groups
;
1235 *len_ret
= sizeof(*addr
);
1242 struct sockaddr_in
* addr
;
1245 if (!PyTuple_Check(args
)) {
1249 "AF_INET address must be tuple, not %.500s",
1250 Py_TYPE(args
)->tp_name
);
1253 if (!PyArg_ParseTuple(args
, "eti:getsockaddrarg",
1254 "idna", &host
, &port
))
1256 addr
=(struct sockaddr_in
*)addr_ret
;
1257 result
= setipaddr(host
, (struct sockaddr
*)addr
,
1258 sizeof(*addr
), AF_INET
);
1262 addr
->sin_family
= AF_INET
;
1263 addr
->sin_port
= htons((short)port
);
1264 *len_ret
= sizeof *addr
;
1271 struct sockaddr_in6
* addr
;
1273 int port
, flowinfo
, scope_id
, result
;
1274 flowinfo
= scope_id
= 0;
1275 if (!PyTuple_Check(args
)) {
1279 "AF_INET6 address must be tuple, not %.500s",
1280 Py_TYPE(args
)->tp_name
);
1283 if (!PyArg_ParseTuple(args
, "eti|ii",
1284 "idna", &host
, &port
, &flowinfo
,
1288 addr
= (struct sockaddr_in6
*)addr_ret
;
1289 result
= setipaddr(host
, (struct sockaddr
*)addr
,
1290 sizeof(*addr
), AF_INET6
);
1294 addr
->sin6_family
= s
->sock_family
;
1295 addr
->sin6_port
= htons((short)port
);
1296 addr
->sin6_flowinfo
= flowinfo
;
1297 addr
->sin6_scope_id
= scope_id
;
1298 *len_ret
= sizeof *addr
;
1303 #ifdef USE_BLUETOOTH
1306 switch (s
->sock_proto
) {
1309 struct sockaddr_l2
*addr
;
1312 addr
= (struct sockaddr_l2
*)addr_ret
;
1313 _BT_L2_MEMB(addr
, family
) = AF_BLUETOOTH
;
1314 if (!PyArg_ParseTuple(args
, "si", &straddr
,
1315 &_BT_L2_MEMB(addr
, psm
))) {
1316 PyErr_SetString(socket_error
, "getsockaddrarg: "
1320 if (setbdaddr(straddr
, &_BT_L2_MEMB(addr
, bdaddr
)) < 0)
1323 *len_ret
= sizeof *addr
;
1326 case BTPROTO_RFCOMM
:
1328 struct sockaddr_rc
*addr
;
1331 addr
= (struct sockaddr_rc
*)addr_ret
;
1332 _BT_RC_MEMB(addr
, family
) = AF_BLUETOOTH
;
1333 if (!PyArg_ParseTuple(args
, "si", &straddr
,
1334 &_BT_RC_MEMB(addr
, channel
))) {
1335 PyErr_SetString(socket_error
, "getsockaddrarg: "
1339 if (setbdaddr(straddr
, &_BT_RC_MEMB(addr
, bdaddr
)) < 0)
1342 *len_ret
= sizeof *addr
;
1347 struct sockaddr_hci
*addr
= (struct sockaddr_hci
*)addr_ret
;
1348 _BT_HCI_MEMB(addr
, family
) = AF_BLUETOOTH
;
1349 if (!PyArg_ParseTuple(args
, "i", &_BT_HCI_MEMB(addr
, dev
))) {
1350 PyErr_SetString(socket_error
, "getsockaddrarg: "
1354 *len_ret
= sizeof *addr
;
1357 #if !defined(__FreeBSD__)
1360 struct sockaddr_sco
*addr
;
1363 addr
= (struct sockaddr_sco
*)addr_ret
;
1364 _BT_SCO_MEMB(addr
, family
) = AF_BLUETOOTH
;
1365 straddr
= PyString_AsString(args
);
1366 if (straddr
== NULL
) {
1367 PyErr_SetString(socket_error
, "getsockaddrarg: "
1371 if (setbdaddr(straddr
, &_BT_SCO_MEMB(addr
, bdaddr
)) < 0)
1374 *len_ret
= sizeof *addr
;
1379 PyErr_SetString(socket_error
, "getsockaddrarg: unknown Bluetooth protocol");
1385 #ifdef HAVE_NETPACKET_PACKET_H
1388 struct sockaddr_ll
* addr
;
1390 char *interfaceName
;
1395 unsigned int halen
= 0;
1397 if (!PyTuple_Check(args
)) {
1401 "AF_PACKET address must be tuple, not %.500s",
1402 Py_TYPE(args
)->tp_name
);
1405 if (!PyArg_ParseTuple(args
, "si|iis#", &interfaceName
,
1406 &protoNumber
, &pkttype
, &hatype
,
1409 strncpy(ifr
.ifr_name
, interfaceName
, sizeof(ifr
.ifr_name
));
1410 ifr
.ifr_name
[(sizeof(ifr
.ifr_name
))-1] = '\0';
1411 if (ioctl(s
->sock_fd
, SIOCGIFINDEX
, &ifr
) < 0) {
1416 PyErr_SetString(PyExc_ValueError
,
1417 "Hardware address must be 8 bytes or less");
1420 addr
= (struct sockaddr_ll
*)addr_ret
;
1421 addr
->sll_family
= AF_PACKET
;
1422 addr
->sll_protocol
= htons((short)protoNumber
);
1423 addr
->sll_ifindex
= ifr
.ifr_ifindex
;
1424 addr
->sll_pkttype
= pkttype
;
1425 addr
->sll_hatype
= hatype
;
1427 memcpy(&addr
->sll_addr
, haddr
, halen
);
1429 addr
->sll_halen
= halen
;
1430 *len_ret
= sizeof *addr
;
1435 #ifdef HAVE_LINUX_TIPC_H
1438 unsigned int atype
, v1
, v2
, v3
;
1439 unsigned int scope
= TIPC_CLUSTER_SCOPE
;
1440 struct sockaddr_tipc
*addr
;
1442 if (!PyTuple_Check(args
)) {
1446 "AF_TIPC address must be tuple, not %.500s",
1447 Py_TYPE(args
)->tp_name
);
1451 if (!PyArg_ParseTuple(args
,
1452 "IIII|I;Invalid TIPC address format",
1453 &atype
, &v1
, &v2
, &v3
, &scope
))
1456 addr
= (struct sockaddr_tipc
*) addr_ret
;
1457 memset(addr
, 0, sizeof(struct sockaddr_tipc
));
1459 addr
->family
= AF_TIPC
;
1460 addr
->scope
= scope
;
1461 addr
->addrtype
= atype
;
1463 if (atype
== TIPC_ADDR_NAMESEQ
) {
1464 addr
->addr
.nameseq
.type
= v1
;
1465 addr
->addr
.nameseq
.lower
= v2
;
1466 addr
->addr
.nameseq
.upper
= v3
;
1467 } else if (atype
== TIPC_ADDR_NAME
) {
1468 addr
->addr
.name
.name
.type
= v1
;
1469 addr
->addr
.name
.name
.instance
= v2
;
1470 } else if (atype
== TIPC_ADDR_ID
) {
1471 addr
->addr
.id
.node
= v1
;
1472 addr
->addr
.id
.ref
= v2
;
1474 /* Shouldn't happen */
1475 PyErr_SetString(PyExc_TypeError
, "Invalid address type");
1479 *len_ret
= sizeof(*addr
);
1485 /* More cases here... */
1488 PyErr_SetString(socket_error
, "getsockaddrarg: bad family");
1495 /* Get the address length according to the socket object's address family.
1496 Return 1 if the family is known, 0 otherwise. The length is returned
1500 getsockaddrlen(PySocketSockObject
*s
, socklen_t
*len_ret
)
1502 switch (s
->sock_family
) {
1504 #if defined(AF_UNIX)
1507 *len_ret
= sizeof (struct sockaddr_un
);
1510 #endif /* AF_UNIX */
1511 #if defined(AF_NETLINK)
1514 *len_ret
= sizeof (struct sockaddr_nl
);
1521 *len_ret
= sizeof (struct sockaddr_in
);
1528 *len_ret
= sizeof (struct sockaddr_in6
);
1533 #ifdef USE_BLUETOOTH
1536 switch(s
->sock_proto
)
1540 *len_ret
= sizeof (struct sockaddr_l2
);
1542 case BTPROTO_RFCOMM
:
1543 *len_ret
= sizeof (struct sockaddr_rc
);
1546 *len_ret
= sizeof (struct sockaddr_hci
);
1548 #if !defined(__FreeBSD__)
1550 *len_ret
= sizeof (struct sockaddr_sco
);
1554 PyErr_SetString(socket_error
, "getsockaddrlen: "
1555 "unknown BT protocol");
1562 #ifdef HAVE_NETPACKET_PACKET_H
1565 *len_ret
= sizeof (struct sockaddr_ll
);
1570 #ifdef HAVE_LINUX_TIPC_H
1573 *len_ret
= sizeof (struct sockaddr_tipc
);
1578 /* More cases here... */
1581 PyErr_SetString(socket_error
, "getsockaddrlen: bad family");
1588 /* s.accept() method */
1591 sock_accept(PySocketSockObject
*s
)
1593 sock_addr_t addrbuf
;
1596 PyObject
*sock
= NULL
;
1597 PyObject
*addr
= NULL
;
1598 PyObject
*res
= NULL
;
1601 if (!getsockaddrlen(s
, &addrlen
))
1603 memset(&addrbuf
, 0, addrlen
);
1606 newfd
= INVALID_SOCKET
;
1611 if (!IS_SELECTABLE(s
))
1612 return select_error();
1614 Py_BEGIN_ALLOW_THREADS
1615 timeout
= internal_select(s
, 0);
1617 newfd
= accept(s
->sock_fd
, SAS2SA(&addrbuf
), &addrlen
);
1618 Py_END_ALLOW_THREADS
1621 PyErr_SetString(socket_timeout
, "timed out");
1626 if (newfd
== INVALID_SOCKET
)
1630 return s
->errorhandler();
1632 /* Create the new object with unspecified family,
1633 to avoid calls to bind() etc. on it. */
1634 sock
= (PyObject
*) new_sockobject(newfd
,
1643 addr
= makesockaddr(s
->sock_fd
, SAS2SA(&addrbuf
),
1644 addrlen
, s
->sock_proto
);
1648 res
= PyTuple_Pack(2, sock
, addr
);
1656 PyDoc_STRVAR(accept_doc
,
1657 "accept() -> (socket object, address info)\n\
1659 Wait for an incoming connection. Return a new socket representing the\n\
1660 connection, and the address of the client. For IP sockets, the address\n\
1661 info is a pair (hostaddr, port).");
1663 /* s.setblocking(flag) method. Argument:
1664 False -- non-blocking mode; same as settimeout(0)
1665 True -- blocking mode; same as settimeout(None)
1669 sock_setblocking(PySocketSockObject
*s
, PyObject
*arg
)
1673 block
= PyInt_AsLong(arg
);
1674 if (block
== -1 && PyErr_Occurred())
1677 s
->sock_timeout
= block
? -1.0 : 0.0;
1678 internal_setblocking(s
, block
);
1684 PyDoc_STRVAR(setblocking_doc
,
1685 "setblocking(flag)\n\
1687 Set the socket to blocking (flag is true) or non-blocking (false).\n\
1688 setblocking(True) is equivalent to settimeout(None);\n\
1689 setblocking(False) is equivalent to settimeout(0.0).");
1691 /* s.settimeout(timeout) method. Argument:
1692 None -- no timeout, blocking mode; same as setblocking(True)
1693 0.0 -- non-blocking mode; same as setblocking(False)
1694 > 0 -- timeout mode; operations time out after timeout seconds
1695 < 0 -- illegal; raises an exception
1698 sock_settimeout(PySocketSockObject
*s
, PyObject
*arg
)
1705 timeout
= PyFloat_AsDouble(arg
);
1706 if (timeout
< 0.0) {
1707 if (!PyErr_Occurred())
1708 PyErr_SetString(PyExc_ValueError
,
1709 "Timeout value out of range");
1714 s
->sock_timeout
= timeout
;
1715 internal_setblocking(s
, timeout
< 0.0);
1721 PyDoc_STRVAR(settimeout_doc
,
1722 "settimeout(timeout)\n\
1724 Set a timeout on socket operations. 'timeout' can be a float,\n\
1725 giving in seconds, or None. Setting a timeout of None disables\n\
1726 the timeout feature and is equivalent to setblocking(1).\n\
1727 Setting a timeout of zero is the same as setblocking(0).");
1729 /* s.gettimeout() method.
1730 Returns the timeout associated with a socket. */
1732 sock_gettimeout(PySocketSockObject
*s
)
1734 if (s
->sock_timeout
< 0.0) {
1739 return PyFloat_FromDouble(s
->sock_timeout
);
1742 PyDoc_STRVAR(gettimeout_doc
,
1743 "gettimeout() -> timeout\n\
1745 Returns the timeout in floating seconds associated with socket \n\
1746 operations. A timeout of None indicates that timeouts on socket \n\
1747 operations are disabled.");
1750 /* s.sleeptaskw(1 | 0) method */
1753 sock_sleeptaskw(PySocketSockObject
*s
,PyObject
*arg
)
1756 block
= PyInt_AsLong(arg
);
1757 if (block
== -1 && PyErr_Occurred())
1759 Py_BEGIN_ALLOW_THREADS
1760 socketioctl(s
->sock_fd
, 0x80046679, (u_long
*)&block
);
1761 Py_END_ALLOW_THREADS
1766 PyDoc_STRVAR(sleeptaskw_doc
,
1767 "sleeptaskw(flag)\n\
1769 Allow sleeps in taskwindows.");
1773 /* s.setsockopt() method.
1774 With an integer third argument, sets an integer option.
1775 With a string third argument, sets an option from a buffer;
1776 use optional built-in module 'struct' to encode the string. */
1779 sock_setsockopt(PySocketSockObject
*s
, PyObject
*args
)
1788 if (PyArg_ParseTuple(args
, "iii:setsockopt",
1789 &level
, &optname
, &flag
)) {
1790 buf
= (char *) &flag
;
1791 buflen
= sizeof flag
;
1795 if (!PyArg_ParseTuple(args
, "iis#:setsockopt",
1796 &level
, &optname
, &buf
, &buflen
))
1799 res
= setsockopt(s
->sock_fd
, level
, optname
, (void *)buf
, buflen
);
1801 return s
->errorhandler();
1806 PyDoc_STRVAR(setsockopt_doc
,
1807 "setsockopt(level, option, value)\n\
1809 Set a socket option. See the Unix manual for level and option.\n\
1810 The value argument can either be an integer or a string.");
1813 /* s.getsockopt() method.
1814 With two arguments, retrieves an integer option.
1815 With a third integer argument, retrieves a string buffer of that size;
1816 use optional built-in module 'struct' to decode the string. */
1819 sock_getsockopt(PySocketSockObject
*s
, PyObject
*args
)
1825 socklen_t buflen
= 0;
1828 /* We have incomplete socket support. */
1829 PyErr_SetString(socket_error
, "getsockopt not supported");
1833 if (!PyArg_ParseTuple(args
, "ii|i:getsockopt",
1834 &level
, &optname
, &buflen
))
1839 socklen_t flagsize
= sizeof flag
;
1840 res
= getsockopt(s
->sock_fd
, level
, optname
,
1841 (void *)&flag
, &flagsize
);
1843 return s
->errorhandler();
1844 return PyInt_FromLong(flag
);
1847 /* socklen_t is unsigned so no negative test is needed,
1848 test buflen == 0 is previously done */
1849 if (buflen
> 1024) {
1851 if (buflen
<= 0 || buflen
> 1024) {
1853 PyErr_SetString(socket_error
,
1854 "getsockopt buflen out of range");
1857 buf
= PyString_FromStringAndSize((char *)NULL
, buflen
);
1860 res
= getsockopt(s
->sock_fd
, level
, optname
,
1861 (void *)PyString_AS_STRING(buf
), &buflen
);
1864 return s
->errorhandler();
1866 _PyString_Resize(&buf
, buflen
);
1868 #endif /* __BEOS__ */
1871 PyDoc_STRVAR(getsockopt_doc
,
1872 "getsockopt(level, option[, buffersize]) -> value\n\
1874 Get a socket option. See the Unix manual for level and option.\n\
1875 If a nonzero buffersize argument is given, the return value is a\n\
1876 string of that length; otherwise it is an integer.");
1879 /* s.bind(sockaddr) method */
1882 sock_bind(PySocketSockObject
*s
, PyObject
*addro
)
1884 sock_addr_t addrbuf
;
1888 if (!getsockaddrarg(s
, addro
, SAS2SA(&addrbuf
), &addrlen
))
1890 Py_BEGIN_ALLOW_THREADS
1891 res
= bind(s
->sock_fd
, SAS2SA(&addrbuf
), addrlen
);
1892 Py_END_ALLOW_THREADS
1894 return s
->errorhandler();
1899 PyDoc_STRVAR(bind_doc
,
1902 Bind the socket to a local address. For IP sockets, the address is a\n\
1903 pair (host, port); the host must refer to the local host. For raw packet\n\
1904 sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");
1907 /* s.close() method.
1908 Set the file descriptor to -1 so operations tried subsequently
1909 will surely fail. */
1912 sock_close(PySocketSockObject
*s
)
1916 if ((fd
= s
->sock_fd
) != -1) {
1918 Py_BEGIN_ALLOW_THREADS
1919 (void) SOCKETCLOSE(fd
);
1920 Py_END_ALLOW_THREADS
1926 PyDoc_STRVAR(close_doc
,
1929 Close the socket. It cannot be used after this call.");
1932 internal_connect(PySocketSockObject
*s
, struct sockaddr
*addr
, int addrlen
,
1938 res
= connect(s
->sock_fd
, addr
, addrlen
);
1942 if (s
->sock_timeout
> 0.0) {
1943 if (res
< 0 && WSAGetLastError() == WSAEWOULDBLOCK
&&
1945 /* This is a mess. Best solution: trust select */
1949 tv
.tv_sec
= (int)s
->sock_timeout
;
1950 tv
.tv_usec
= (int)((s
->sock_timeout
- tv
.tv_sec
) * 1e6
);
1952 FD_SET(s
->sock_fd
, &fds
);
1954 FD_SET(s
->sock_fd
, &fds_exc
);
1955 res
= select(s
->sock_fd
+1, NULL
, &fds
, &fds_exc
, &tv
);
1957 res
= WSAEWOULDBLOCK
;
1959 } else if (res
> 0) {
1960 if (FD_ISSET(s
->sock_fd
, &fds
))
1961 /* The socket is in the writeable set - this
1965 /* As per MS docs, we need to call getsockopt()
1966 to get the underlying error */
1967 int res_size
= sizeof res
;
1968 /* It must be in the exception set */
1969 assert(FD_ISSET(s
->sock_fd
, &fds_exc
));
1970 if (0 == getsockopt(s
->sock_fd
, SOL_SOCKET
, SO_ERROR
,
1971 (char *)&res
, &res_size
))
1972 /* getsockopt also clears WSAGetLastError,
1973 so reset it back. */
1974 WSASetLastError(res
);
1976 res
= WSAGetLastError();
1979 /* else if (res < 0) an error occurred */
1984 res
= WSAGetLastError();
1988 if (s
->sock_timeout
> 0.0) {
1989 if (res
< 0 && errno
== EINPROGRESS
&& IS_SELECTABLE(s
)) {
1990 timeout
= internal_select(s
, 1);
1992 res
= connect(s
->sock_fd
, addr
, addrlen
);
1993 if (res
< 0 && errno
== EISCONN
)
1996 else if (timeout
== -1)
1997 res
= errno
; /* had error */
1999 res
= EWOULDBLOCK
; /* timed out */
2007 *timeoutp
= timeout
;
2012 /* s.connect(sockaddr) method */
2015 sock_connect(PySocketSockObject
*s
, PyObject
*addro
)
2017 sock_addr_t addrbuf
;
2022 if (!getsockaddrarg(s
, addro
, SAS2SA(&addrbuf
), &addrlen
))
2025 Py_BEGIN_ALLOW_THREADS
2026 res
= internal_connect(s
, SAS2SA(&addrbuf
), addrlen
, &timeout
);
2027 Py_END_ALLOW_THREADS
2030 PyErr_SetString(socket_timeout
, "timed out");
2034 return s
->errorhandler();
2039 PyDoc_STRVAR(connect_doc
,
2040 "connect(address)\n\
2042 Connect the socket to a remote address. For IP sockets, the address\n\
2043 is a pair (host, port).");
2046 /* s.connect_ex(sockaddr) method */
2049 sock_connect_ex(PySocketSockObject
*s
, PyObject
*addro
)
2051 sock_addr_t addrbuf
;
2056 if (!getsockaddrarg(s
, addro
, SAS2SA(&addrbuf
), &addrlen
))
2059 Py_BEGIN_ALLOW_THREADS
2060 res
= internal_connect(s
, SAS2SA(&addrbuf
), addrlen
, &timeout
);
2061 Py_END_ALLOW_THREADS
2063 /* Signals are not errors (though they may raise exceptions). Adapted
2064 from PyErr_SetFromErrnoWithFilenameObject(). */
2066 if (res
== EINTR
&& PyErr_CheckSignals())
2070 return PyInt_FromLong((long) res
);
2073 PyDoc_STRVAR(connect_ex_doc
,
2074 "connect_ex(address) -> errno\n\
2076 This is like connect(address), but returns an error code (the errno value)\n\
2077 instead of raising an exception when an error occurs.");
2080 /* s.fileno() method */
2083 sock_fileno(PySocketSockObject
*s
)
2085 #if SIZEOF_SOCKET_T <= SIZEOF_LONG
2086 return PyInt_FromLong((long) s
->sock_fd
);
2088 return PyLong_FromLongLong((PY_LONG_LONG
)s
->sock_fd
);
2092 PyDoc_STRVAR(fileno_doc
,
2093 "fileno() -> integer\n\
2095 Return the integer file descriptor of the socket.");
2099 /* s.dup() method */
2102 sock_dup(PySocketSockObject
*s
)
2107 newfd
= dup(s
->sock_fd
);
2109 return s
->errorhandler();
2110 sock
= (PyObject
*) new_sockobject(newfd
,
2119 PyDoc_STRVAR(dup_doc
,
2120 "dup() -> socket object\n\
2122 Return a new socket object connected to the same system resource.");
2127 /* s.getsockname() method */
2130 sock_getsockname(PySocketSockObject
*s
)
2132 sock_addr_t addrbuf
;
2136 if (!getsockaddrlen(s
, &addrlen
))
2138 memset(&addrbuf
, 0, addrlen
);
2139 Py_BEGIN_ALLOW_THREADS
2140 res
= getsockname(s
->sock_fd
, SAS2SA(&addrbuf
), &addrlen
);
2141 Py_END_ALLOW_THREADS
2143 return s
->errorhandler();
2144 return makesockaddr(s
->sock_fd
, SAS2SA(&addrbuf
), addrlen
,
2148 PyDoc_STRVAR(getsockname_doc
,
2149 "getsockname() -> address info\n\
2151 Return the address of the local endpoint. For IP sockets, the address\n\
2152 info is a pair (hostaddr, port).");
2155 #ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
2156 /* s.getpeername() method */
2159 sock_getpeername(PySocketSockObject
*s
)
2161 sock_addr_t addrbuf
;
2165 if (!getsockaddrlen(s
, &addrlen
))
2167 memset(&addrbuf
, 0, addrlen
);
2168 Py_BEGIN_ALLOW_THREADS
2169 res
= getpeername(s
->sock_fd
, SAS2SA(&addrbuf
), &addrlen
);
2170 Py_END_ALLOW_THREADS
2172 return s
->errorhandler();
2173 return makesockaddr(s
->sock_fd
, SAS2SA(&addrbuf
), addrlen
,
2177 PyDoc_STRVAR(getpeername_doc
,
2178 "getpeername() -> address info\n\
2180 Return the address of the remote endpoint. For IP sockets, the address\n\
2181 info is a pair (hostaddr, port).");
2183 #endif /* HAVE_GETPEERNAME */
2186 /* s.listen(n) method */
2189 sock_listen(PySocketSockObject
*s
, PyObject
*arg
)
2194 backlog
= PyInt_AsLong(arg
);
2195 if (backlog
== -1 && PyErr_Occurred())
2197 Py_BEGIN_ALLOW_THREADS
2200 res
= listen(s
->sock_fd
, backlog
);
2201 Py_END_ALLOW_THREADS
2203 return s
->errorhandler();
2208 PyDoc_STRVAR(listen_doc
,
2211 Enable a server to accept connections. The backlog argument must be at\n\
2212 least 1; it specifies the number of unaccepted connection that the system\n\
2213 will allow before refusing new connections.");
2217 /* s.makefile(mode) method.
2218 Create a new open file object referring to a dupped version of
2219 the socket's file descriptor. (The dup() call is necessary so
2220 that the open file and socket objects may be closed independent
2222 The mode argument specifies 'r' or 'w' passed to fdopen(). */
2225 sock_makefile(PySocketSockObject
*s
, PyObject
*args
)
2227 extern int fclose(FILE *);
2242 if (!PyArg_ParseTuple(args
, "|si:makefile", &mode
, &bufsize
))
2245 if (strcmp(mode
,"rb") == 0) {
2249 if (strcmp(mode
,"wb") == 0) {
2255 if (((fd
= _open_osfhandle(s
->sock_fd
, _O_BINARY
)) < 0) ||
2256 ((fd
= dup(fd
)) < 0) || ((fp
= fdopen(fd
, mode
)) == NULL
))
2258 if ((fd
= dup(s
->sock_fd
)) < 0 || (fp
= fdopen(fd
, mode
)) == NULL
)
2263 return s
->errorhandler();
2265 f
= PyFile_FromFile(fp
, "<socket>", mode
, fclose
);
2267 PyFile_SetBufSize(f
, bufsize
);
2271 PyDoc_STRVAR(makefile_doc
,
2272 "makefile([mode[, buffersize]]) -> file object\n\
2274 Return a regular file object corresponding to the socket.\n\
2275 The mode and buffersize arguments are as for the built-in open() function.");
2280 * This is the guts of the recv() and recv_into() methods, which reads into a
2281 * char buffer. If you have any inc/dec ref to do to the objects that contain
2282 * the buffer, do it in the caller. This function returns the number of bytes
2283 * succesfully read. If there was an error, it returns -1. Note that it is
2284 * also possible that we return a number of bytes smaller than the request
2288 sock_recv_guts(PySocketSockObject
*s
, char* cbuf
, int len
, int flags
)
2290 ssize_t outlen
= -1;
2297 if (!IS_SELECTABLE(s
)) {
2303 Py_BEGIN_ALLOW_THREADS
2304 timeout
= internal_select(s
, 0);
2306 outlen
= recv(s
->sock_fd
, cbuf
, len
, flags
);
2307 Py_END_ALLOW_THREADS
2310 PyErr_SetString(socket_timeout
, "timed out");
2314 /* Note: the call to errorhandler() ALWAYS indirectly returned
2315 NULL, so ignore its return value */
2322 while (remaining
!= 0) {
2323 unsigned int segment
;
2326 segment
= remaining
/SEGMENT_SIZE
;
2328 segment
= SEGMENT_SIZE
;
2331 segment
= remaining
;
2334 Py_BEGIN_ALLOW_THREADS
2335 timeout
= internal_select(s
, 0);
2337 nread
= recv(s
->sock_fd
, read_buf
, segment
, flags
);
2338 Py_END_ALLOW_THREADS
2341 PyErr_SetString(socket_timeout
, "timed out");
2348 if (nread
!= remaining
) {
2353 remaining
-= segment
;
2354 read_buf
+= segment
;
2356 outlen
= read_buf
- cbuf
;
2363 /* s.recv(nbytes [,flags]) method */
2366 sock_recv(PySocketSockObject
*s
, PyObject
*args
)
2368 int recvlen
, flags
= 0;
2372 if (!PyArg_ParseTuple(args
, "i|i:recv", &recvlen
, &flags
))
2376 PyErr_SetString(PyExc_ValueError
,
2377 "negative buffersize in recv");
2381 /* Allocate a new string. */
2382 buf
= PyString_FromStringAndSize((char *) 0, recvlen
);
2387 outlen
= sock_recv_guts(s
, PyString_AS_STRING(buf
), recvlen
, flags
);
2389 /* An error occurred, release the string and return an
2394 if (outlen
!= recvlen
) {
2395 /* We did not read as many bytes as we anticipated, resize the
2396 string if possible and be succesful. */
2397 if (_PyString_Resize(&buf
, outlen
) < 0)
2398 /* Oopsy, not so succesful after all. */
2405 PyDoc_STRVAR(recv_doc
,
2406 "recv(buffersize[, flags]) -> data\n\
2408 Receive up to buffersize bytes from the socket. For the optional flags\n\
2409 argument, see the Unix manual. When no data is available, block until\n\
2410 at least one byte is available or until the remote end is closed. When\n\
2411 the remote end is closed and all data is read, return the empty string.");
2414 /* s.recv_into(buffer, [nbytes [,flags]]) method */
2417 sock_recv_into(PySocketSockObject
*s
, PyObject
*args
, PyObject
*kwds
)
2419 static char *kwlist
[] = {"buffer", "nbytes", "flags", 0};
2421 int recvlen
= 0, flags
= 0;
2426 /* Get the buffer's memory */
2427 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "w#|ii:recv_into", kwlist
,
2428 &buf
, &buflen
, &recvlen
, &flags
))
2430 assert(buf
!= 0 && buflen
> 0);
2433 PyErr_SetString(PyExc_ValueError
,
2434 "negative buffersize in recv_into");
2438 /* If nbytes was not specified, use the buffer's length */
2442 /* Check if the buffer is large enough */
2443 if (buflen
< recvlen
) {
2444 PyErr_SetString(PyExc_ValueError
,
2445 "buffer too small for requested bytes");
2450 readlen
= sock_recv_guts(s
, buf
, recvlen
, flags
);
2452 /* Return an error. */
2456 /* Return the number of bytes read. Note that we do not do anything
2457 special here in the case that readlen < recvlen. */
2458 return PyInt_FromSsize_t(readlen
);
2461 PyDoc_STRVAR(recv_into_doc
,
2462 "recv_into(buffer, [nbytes[, flags]]) -> nbytes_read\n\
2464 A version of recv() that stores its data into a buffer rather than creating \n\
2465 a new string. Receive up to buffersize bytes from the socket. If buffersize \n\
2466 is not specified (or 0), receive up to the size available in the given buffer.\n\
2468 See recv() for documentation about the flags.");
2472 * This is the guts of the recvfrom() and recvfrom_into() methods, which reads
2473 * into a char buffer. If you have any inc/def ref to do to the objects that
2474 * contain the buffer, do it in the caller. This function returns the number
2475 * of bytes succesfully read. If there was an error, it returns -1. Note
2476 * that it is also possible that we return a number of bytes smaller than the
2479 * 'addr' is a return value for the address object. Note that you must decref
2483 sock_recvfrom_guts(PySocketSockObject
*s
, char* cbuf
, int len
, int flags
,
2486 sock_addr_t addrbuf
;
2493 if (!getsockaddrlen(s
, &addrlen
))
2496 if (!IS_SELECTABLE(s
)) {
2501 Py_BEGIN_ALLOW_THREADS
2502 memset(&addrbuf
, 0, addrlen
);
2503 timeout
= internal_select(s
, 0);
2506 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
2507 n
= recvfrom(s
->sock_fd
, cbuf
, len
, flags
,
2508 SAS2SA(&addrbuf
), &addrlen
);
2510 n
= recvfrom(s
->sock_fd
, cbuf
, len
, flags
,
2511 (void *) &addrbuf
, &addrlen
);
2514 n
= recvfrom(s
->sock_fd
, cbuf
, len
, flags
,
2515 SAS2SA(&addrbuf
), &addrlen
);
2518 Py_END_ALLOW_THREADS
2521 PyErr_SetString(socket_timeout
, "timed out");
2529 if (!(*addr
= makesockaddr(s
->sock_fd
, SAS2SA(&addrbuf
),
2530 addrlen
, s
->sock_proto
)))
2536 /* s.recvfrom(nbytes [,flags]) method */
2539 sock_recvfrom(PySocketSockObject
*s
, PyObject
*args
)
2541 PyObject
*buf
= NULL
;
2542 PyObject
*addr
= NULL
;
2543 PyObject
*ret
= NULL
;
2544 int recvlen
, flags
= 0;
2547 if (!PyArg_ParseTuple(args
, "i|i:recvfrom", &recvlen
, &flags
))
2551 PyErr_SetString(PyExc_ValueError
,
2552 "negative buffersize in recvfrom");
2556 buf
= PyString_FromStringAndSize((char *) 0, recvlen
);
2560 outlen
= sock_recvfrom_guts(s
, PyString_AS_STRING(buf
),
2561 recvlen
, flags
, &addr
);
2566 if (outlen
!= recvlen
) {
2567 /* We did not read as many bytes as we anticipated, resize the
2568 string if possible and be succesful. */
2569 if (_PyString_Resize(&buf
, outlen
) < 0)
2570 /* Oopsy, not so succesful after all. */
2574 ret
= PyTuple_Pack(2, buf
, addr
);
2582 PyDoc_STRVAR(recvfrom_doc
,
2583 "recvfrom(buffersize[, flags]) -> (data, address info)\n\
2585 Like recv(buffersize, flags) but also return the sender's address info.");
2588 /* s.recvfrom_into(buffer[, nbytes [,flags]]) method */
2591 sock_recvfrom_into(PySocketSockObject
*s
, PyObject
*args
, PyObject
* kwds
)
2593 static char *kwlist
[] = {"buffer", "nbytes", "flags", 0};
2595 int recvlen
= 0, flags
= 0;
2600 PyObject
*addr
= NULL
;
2602 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "w#|ii:recvfrom_into",
2603 kwlist
, &buf
, &buflen
,
2606 assert(buf
!= 0 && buflen
> 0);
2609 PyErr_SetString(PyExc_ValueError
,
2610 "negative buffersize in recvfrom_into");
2614 /* If nbytes was not specified, use the buffer's length */
2618 readlen
= sock_recvfrom_guts(s
, buf
, recvlen
, flags
, &addr
);
2620 /* Return an error */
2625 /* Return the number of bytes read and the address. Note that we do
2626 not do anything special here in the case that readlen < recvlen. */
2627 return Py_BuildValue("lN", readlen
, addr
);
2630 PyDoc_STRVAR(recvfrom_into_doc
,
2631 "recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)\n\
2633 Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.");
2636 /* s.send(data [,flags]) method */
2639 sock_send(PySocketSockObject
*s
, PyObject
*args
)
2642 int len
, n
= -1, flags
= 0, timeout
;
2644 if (!PyArg_ParseTuple(args
, "s#|i:send", &buf
, &len
, &flags
))
2647 if (!IS_SELECTABLE(s
))
2648 return select_error();
2650 Py_BEGIN_ALLOW_THREADS
2651 timeout
= internal_select(s
, 1);
2654 n
= sendsegmented(s
->sock_fd
, buf
, len
, flags
);
2656 n
= send(s
->sock_fd
, buf
, len
, flags
);
2658 Py_END_ALLOW_THREADS
2661 PyErr_SetString(socket_timeout
, "timed out");
2665 return s
->errorhandler();
2666 return PyInt_FromLong((long)n
);
2669 PyDoc_STRVAR(send_doc
,
2670 "send(data[, flags]) -> count\n\
2672 Send a data string to the socket. For the optional flags\n\
2673 argument, see the Unix manual. Return the number of bytes\n\
2674 sent; this may be less than len(data) if the network is busy.");
2677 /* s.sendall(data [,flags]) method */
2680 sock_sendall(PySocketSockObject
*s
, PyObject
*args
)
2683 int len
, n
= -1, flags
= 0, timeout
;
2685 if (!PyArg_ParseTuple(args
, "s#|i:sendall", &buf
, &len
, &flags
))
2688 if (!IS_SELECTABLE(s
))
2689 return select_error();
2691 Py_BEGIN_ALLOW_THREADS
2693 timeout
= internal_select(s
, 1);
2698 n
= sendsegmented(s
->sock_fd
, buf
, len
, flags
);
2700 n
= send(s
->sock_fd
, buf
, len
, flags
);
2707 Py_END_ALLOW_THREADS
2710 PyErr_SetString(socket_timeout
, "timed out");
2714 return s
->errorhandler();
2720 PyDoc_STRVAR(sendall_doc
,
2721 "sendall(data[, flags])\n\
2723 Send a data string to the socket. For the optional flags\n\
2724 argument, see the Unix manual. This calls send() repeatedly\n\
2725 until all data is sent. If an error occurs, it's impossible\n\
2726 to tell how much data has been sent.");
2729 /* s.sendto(data, [flags,] sockaddr) method */
2732 sock_sendto(PySocketSockObject
*s
, PyObject
*args
)
2736 sock_addr_t addrbuf
;
2737 int addrlen
, len
, n
= -1, flags
, timeout
;
2740 if (!PyArg_ParseTuple(args
, "s#O:sendto", &buf
, &len
, &addro
)) {
2742 if (!PyArg_ParseTuple(args
, "s#iO:sendto",
2743 &buf
, &len
, &flags
, &addro
))
2747 if (!IS_SELECTABLE(s
))
2748 return select_error();
2750 if (!getsockaddrarg(s
, addro
, SAS2SA(&addrbuf
), &addrlen
))
2753 Py_BEGIN_ALLOW_THREADS
2754 timeout
= internal_select(s
, 1);
2756 n
= sendto(s
->sock_fd
, buf
, len
, flags
, SAS2SA(&addrbuf
), addrlen
);
2757 Py_END_ALLOW_THREADS
2760 PyErr_SetString(socket_timeout
, "timed out");
2764 return s
->errorhandler();
2765 return PyInt_FromLong((long)n
);
2768 PyDoc_STRVAR(sendto_doc
,
2769 "sendto(data[, flags], address) -> count\n\
2771 Like send(data, flags) but allows specifying the destination address.\n\
2772 For IP sockets, the address is a pair (hostaddr, port).");
2775 /* s.shutdown(how) method */
2778 sock_shutdown(PySocketSockObject
*s
, PyObject
*arg
)
2783 how
= PyInt_AsLong(arg
);
2784 if (how
== -1 && PyErr_Occurred())
2786 Py_BEGIN_ALLOW_THREADS
2787 res
= shutdown(s
->sock_fd
, how
);
2788 Py_END_ALLOW_THREADS
2790 return s
->errorhandler();
2795 PyDoc_STRVAR(shutdown_doc
,
2798 Shut down the reading side of the socket (flag == SHUT_RD), the writing side\n\
2799 of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).");
2803 sock_ioctl(PySocketSockObject
*s
, PyObject
*arg
)
2805 unsigned long cmd
= SIO_RCVALL
;
2806 unsigned int option
= RCVALL_ON
;
2809 if (!PyArg_ParseTuple(arg
, "kI:ioctl", &cmd
, &option
))
2812 if (WSAIoctl(s
->sock_fd
, cmd
, &option
, sizeof(option
),
2813 NULL
, 0, &recv
, NULL
, NULL
) == SOCKET_ERROR
) {
2816 return PyLong_FromUnsignedLong(recv
);
2818 PyDoc_STRVAR(sock_ioctl_doc
,
2819 "ioctl(cmd, option) -> long\n\
2821 Control the socket with WSAIoctl syscall. Currently only socket.SIO_RCVALL\n\
2822 is supported as control. Options must be one of the socket.RCVALL_*\n\
2827 /* List of methods for socket objects */
2829 static PyMethodDef sock_methods
[] = {
2830 {"accept", (PyCFunction
)sock_accept
, METH_NOARGS
,
2832 {"bind", (PyCFunction
)sock_bind
, METH_O
,
2834 {"close", (PyCFunction
)sock_close
, METH_NOARGS
,
2836 {"connect", (PyCFunction
)sock_connect
, METH_O
,
2838 {"connect_ex", (PyCFunction
)sock_connect_ex
, METH_O
,
2841 {"dup", (PyCFunction
)sock_dup
, METH_NOARGS
,
2844 {"fileno", (PyCFunction
)sock_fileno
, METH_NOARGS
,
2846 #ifdef HAVE_GETPEERNAME
2847 {"getpeername", (PyCFunction
)sock_getpeername
,
2848 METH_NOARGS
, getpeername_doc
},
2850 {"getsockname", (PyCFunction
)sock_getsockname
,
2851 METH_NOARGS
, getsockname_doc
},
2852 {"getsockopt", (PyCFunction
)sock_getsockopt
, METH_VARARGS
,
2855 {"ioctl", (PyCFunction
)sock_ioctl
, METH_VARARGS
,
2858 {"listen", (PyCFunction
)sock_listen
, METH_O
,
2861 {"makefile", (PyCFunction
)sock_makefile
, METH_VARARGS
,
2864 {"recv", (PyCFunction
)sock_recv
, METH_VARARGS
,
2866 {"recv_into", (PyCFunction
)sock_recv_into
, METH_VARARGS
| METH_KEYWORDS
,
2868 {"recvfrom", (PyCFunction
)sock_recvfrom
, METH_VARARGS
,
2870 {"recvfrom_into", (PyCFunction
)sock_recvfrom_into
, METH_VARARGS
| METH_KEYWORDS
,
2872 {"send", (PyCFunction
)sock_send
, METH_VARARGS
,
2874 {"sendall", (PyCFunction
)sock_sendall
, METH_VARARGS
,
2876 {"sendto", (PyCFunction
)sock_sendto
, METH_VARARGS
,
2878 {"setblocking", (PyCFunction
)sock_setblocking
, METH_O
,
2880 {"settimeout", (PyCFunction
)sock_settimeout
, METH_O
,
2882 {"gettimeout", (PyCFunction
)sock_gettimeout
, METH_NOARGS
,
2884 {"setsockopt", (PyCFunction
)sock_setsockopt
, METH_VARARGS
,
2886 {"shutdown", (PyCFunction
)sock_shutdown
, METH_O
,
2889 {"sleeptaskw", (PyCFunction
)sock_sleeptaskw
, METH_O
,
2892 {NULL
, NULL
} /* sentinel */
2895 /* SockObject members */
2896 static PyMemberDef sock_memberlist
[] = {
2897 {"family", T_INT
, offsetof(PySocketSockObject
, sock_family
), READONLY
, "the socket family"},
2898 {"type", T_INT
, offsetof(PySocketSockObject
, sock_type
), READONLY
, "the socket type"},
2899 {"proto", T_INT
, offsetof(PySocketSockObject
, sock_proto
), READONLY
, "the socket protocol"},
2900 {"timeout", T_DOUBLE
, offsetof(PySocketSockObject
, sock_timeout
), READONLY
, "the socket timeout"},
2904 /* Deallocate a socket object in response to the last Py_DECREF().
2905 First close the file description. */
2908 sock_dealloc(PySocketSockObject
*s
)
2910 if (s
->sock_fd
!= -1)
2911 (void) SOCKETCLOSE(s
->sock_fd
);
2912 Py_TYPE(s
)->tp_free((PyObject
*)s
);
2917 sock_repr(PySocketSockObject
*s
)
2920 #if SIZEOF_SOCKET_T > SIZEOF_LONG
2921 if (s
->sock_fd
> LONG_MAX
) {
2922 /* this can occur on Win64, and actually there is a special
2923 ugly printf formatter for decimal pointer length integer
2924 printing, only bother if necessary*/
2925 PyErr_SetString(PyExc_OverflowError
,
2926 "no printf formatter to display "
2927 "the socket descriptor in decimal");
2933 "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
2934 (long)s
->sock_fd
, s
->sock_family
,
2937 return PyString_FromString(buf
);
2941 /* Create a new, uninitialized socket object. */
2944 sock_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
2948 new = type
->tp_alloc(type
, 0);
2950 ((PySocketSockObject
*)new)->sock_fd
= -1;
2951 ((PySocketSockObject
*)new)->sock_timeout
= -1.0;
2952 ((PySocketSockObject
*)new)->errorhandler
= &set_error
;
2958 /* Initialize a new socket object. */
2962 sock_initobj(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
2964 PySocketSockObject
*s
= (PySocketSockObject
*)self
;
2966 int family
= AF_INET
, type
= SOCK_STREAM
, proto
= 0;
2967 static char *keywords
[] = {"family", "type", "proto", 0};
2969 if (!PyArg_ParseTupleAndKeywords(args
, kwds
,
2970 "|iii:socket", keywords
,
2971 &family
, &type
, &proto
))
2974 Py_BEGIN_ALLOW_THREADS
2975 fd
= socket(family
, type
, proto
);
2976 Py_END_ALLOW_THREADS
2979 if (fd
== INVALID_SOCKET
)
2987 init_sockobject(s
, fd
, family
, type
, proto
);
2994 /* Type object for socket objects. */
2996 static PyTypeObject sock_type
= {
2997 PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */
2998 "_socket.socket", /* tp_name */
2999 sizeof(PySocketSockObject
), /* tp_basicsize */
3000 0, /* tp_itemsize */
3001 (destructor
)sock_dealloc
, /* tp_dealloc */
3006 (reprfunc
)sock_repr
, /* tp_repr */
3007 0, /* tp_as_number */
3008 0, /* tp_as_sequence */
3009 0, /* tp_as_mapping */
3013 PyObject_GenericGetAttr
, /* tp_getattro */
3014 0, /* tp_setattro */
3015 0, /* tp_as_buffer */
3016 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
3017 sock_doc
, /* tp_doc */
3018 0, /* tp_traverse */
3020 0, /* tp_richcompare */
3021 0, /* tp_weaklistoffset */
3023 0, /* tp_iternext */
3024 sock_methods
, /* tp_methods */
3025 sock_memberlist
, /* tp_members */
3029 0, /* tp_descr_get */
3030 0, /* tp_descr_set */
3031 0, /* tp_dictoffset */
3032 sock_initobj
, /* tp_init */
3033 PyType_GenericAlloc
, /* tp_alloc */
3034 sock_new
, /* tp_new */
3035 PyObject_Del
, /* tp_free */
3039 /* Python interface to gethostname(). */
3043 socket_gethostname(PyObject
*self
, PyObject
*unused
)
3047 Py_BEGIN_ALLOW_THREADS
3048 res
= gethostname(buf
, (int) sizeof buf
- 1);
3049 Py_END_ALLOW_THREADS
3052 buf
[sizeof buf
- 1] = '\0';
3053 return PyString_FromString(buf
);
3056 PyDoc_STRVAR(gethostname_doc
,
3057 "gethostname() -> string\n\
3059 Return the current host name.");
3062 /* Python interface to gethostbyname(name). */
3066 socket_gethostbyname(PyObject
*self
, PyObject
*args
)
3069 sock_addr_t addrbuf
;
3071 if (!PyArg_ParseTuple(args
, "s:gethostbyname", &name
))
3073 if (setipaddr(name
, SAS2SA(&addrbuf
), sizeof(addrbuf
), AF_INET
) < 0)
3075 return makeipaddr(SAS2SA(&addrbuf
), sizeof(struct sockaddr_in
));
3078 PyDoc_STRVAR(gethostbyname_doc
,
3079 "gethostbyname(host) -> address\n\
3081 Return the IP address (a string of the form '255.255.255.255') for a host.");
3084 /* Convenience function common to gethostbyname_ex and gethostbyaddr */
3087 gethost_common(struct hostent
*h
, struct sockaddr
*addr
, int alen
, int af
)
3090 PyObject
*rtn_tuple
= (PyObject
*)NULL
;
3091 PyObject
*name_list
= (PyObject
*)NULL
;
3092 PyObject
*addr_list
= (PyObject
*)NULL
;
3096 /* Let's get real error message to return */
3098 set_herror(h_errno
);
3100 PyErr_SetString(socket_error
, "host not found");
3105 if (h
->h_addrtype
!= af
) {
3106 #ifdef HAVE_STRERROR
3107 /* Let's get real error message to return */
3108 PyErr_SetString(socket_error
,
3109 (char *)strerror(EAFNOSUPPORT
));
3113 "Address family not supported by protocol family");
3121 if (alen
< sizeof(struct sockaddr_in
))
3127 if (alen
< sizeof(struct sockaddr_in6
))
3134 if ((name_list
= PyList_New(0)) == NULL
)
3137 if ((addr_list
= PyList_New(0)) == NULL
)
3140 /* SF #1511317: h_aliases can be NULL */
3142 for (pch
= h
->h_aliases
; *pch
!= NULL
; pch
++) {
3144 tmp
= PyString_FromString(*pch
);
3148 status
= PyList_Append(name_list
, tmp
);
3156 for (pch
= h
->h_addr_list
; *pch
!= NULL
; pch
++) {
3163 struct sockaddr_in sin
;
3164 memset(&sin
, 0, sizeof(sin
));
3165 sin
.sin_family
= af
;
3166 #ifdef HAVE_SOCKADDR_SA_LEN
3167 sin
.sin_len
= sizeof(sin
);
3169 memcpy(&sin
.sin_addr
, *pch
, sizeof(sin
.sin_addr
));
3170 tmp
= makeipaddr((struct sockaddr
*)&sin
, sizeof(sin
));
3172 if (pch
== h
->h_addr_list
&& alen
>= sizeof(sin
))
3173 memcpy((char *) addr
, &sin
, sizeof(sin
));
3180 struct sockaddr_in6 sin6
;
3181 memset(&sin6
, 0, sizeof(sin6
));
3182 sin6
.sin6_family
= af
;
3183 #ifdef HAVE_SOCKADDR_SA_LEN
3184 sin6
.sin6_len
= sizeof(sin6
);
3186 memcpy(&sin6
.sin6_addr
, *pch
, sizeof(sin6
.sin6_addr
));
3187 tmp
= makeipaddr((struct sockaddr
*)&sin6
,
3190 if (pch
== h
->h_addr_list
&& alen
>= sizeof(sin6
))
3191 memcpy((char *) addr
, &sin6
, sizeof(sin6
));
3196 default: /* can't happen */
3197 PyErr_SetString(socket_error
,
3198 "unsupported address family");
3205 status
= PyList_Append(addr_list
, tmp
);
3212 rtn_tuple
= Py_BuildValue("sOO", h
->h_name
, name_list
, addr_list
);
3215 Py_XDECREF(name_list
);
3216 Py_XDECREF(addr_list
);
3221 /* Python interface to gethostbyname_ex(name). */
3225 socket_gethostbyname_ex(PyObject
*self
, PyObject
*args
)
3230 struct sockaddr_storage addr
;
3232 struct sockaddr_in addr
;
3234 struct sockaddr
*sa
;
3236 #ifdef HAVE_GETHOSTBYNAME_R
3237 struct hostent hp_allocated
;
3238 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
3239 struct hostent_data data
;
3242 int buf_len
= (sizeof buf
) - 1;
3245 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3248 #endif /* HAVE_GETHOSTBYNAME_R */
3250 if (!PyArg_ParseTuple(args
, "s:gethostbyname_ex", &name
))
3252 if (setipaddr(name
, (struct sockaddr
*)&addr
, sizeof(addr
), AF_INET
) < 0)
3254 Py_BEGIN_ALLOW_THREADS
3255 #ifdef HAVE_GETHOSTBYNAME_R
3256 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3257 result
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
,
3259 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
3260 h
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
, &errnop
);
3261 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
3262 memset((void *) &data
, '\0', sizeof(data
));
3263 result
= gethostbyname_r(name
, &hp_allocated
, &data
);
3264 h
= (result
!= 0) ? NULL
: &hp_allocated
;
3266 #else /* not HAVE_GETHOSTBYNAME_R */
3267 #ifdef USE_GETHOSTBYNAME_LOCK
3268 PyThread_acquire_lock(netdb_lock
, 1);
3270 h
= gethostbyname(name
);
3271 #endif /* HAVE_GETHOSTBYNAME_R */
3272 Py_END_ALLOW_THREADS
3273 /* Some C libraries would require addr.__ss_family instead of
3275 Therefore, we cast the sockaddr_storage into sockaddr to
3276 access sa_family. */
3277 sa
= (struct sockaddr
*)&addr
;
3278 ret
= gethost_common(h
, (struct sockaddr
*)&addr
, sizeof(addr
),
3280 #ifdef USE_GETHOSTBYNAME_LOCK
3281 PyThread_release_lock(netdb_lock
);
3286 PyDoc_STRVAR(ghbn_ex_doc
,
3287 "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
3289 Return the true host name, a list of aliases, and a list of IP addresses,\n\
3290 for a host. The host argument is a string giving a host name or IP number.");
3293 /* Python interface to gethostbyaddr(IP). */
3297 socket_gethostbyaddr(PyObject
*self
, PyObject
*args
)
3300 struct sockaddr_storage addr
;
3302 struct sockaddr_in addr
;
3304 struct sockaddr
*sa
= (struct sockaddr
*)&addr
;
3308 #ifdef HAVE_GETHOSTBYNAME_R
3309 struct hostent hp_allocated
;
3310 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
3311 struct hostent_data data
;
3314 int buf_len
= (sizeof buf
) - 1;
3317 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3320 #endif /* HAVE_GETHOSTBYNAME_R */
3325 if (!PyArg_ParseTuple(args
, "s:gethostbyaddr", &ip_num
))
3328 if (setipaddr(ip_num
, sa
, sizeof(addr
), af
) < 0)
3335 ap
= (char *)&((struct sockaddr_in
*)sa
)->sin_addr
;
3336 al
= sizeof(((struct sockaddr_in
*)sa
)->sin_addr
);
3340 ap
= (char *)&((struct sockaddr_in6
*)sa
)->sin6_addr
;
3341 al
= sizeof(((struct sockaddr_in6
*)sa
)->sin6_addr
);
3345 PyErr_SetString(socket_error
, "unsupported address family");
3348 Py_BEGIN_ALLOW_THREADS
3349 #ifdef HAVE_GETHOSTBYNAME_R
3350 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3351 result
= gethostbyaddr_r(ap
, al
, af
,
3352 &hp_allocated
, buf
, buf_len
,
3354 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
3355 h
= gethostbyaddr_r(ap
, al
, af
,
3356 &hp_allocated
, buf
, buf_len
, &errnop
);
3357 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
3358 memset((void *) &data
, '\0', sizeof(data
));
3359 result
= gethostbyaddr_r(ap
, al
, af
, &hp_allocated
, &data
);
3360 h
= (result
!= 0) ? NULL
: &hp_allocated
;
3362 #else /* not HAVE_GETHOSTBYNAME_R */
3363 #ifdef USE_GETHOSTBYNAME_LOCK
3364 PyThread_acquire_lock(netdb_lock
, 1);
3366 h
= gethostbyaddr(ap
, al
, af
);
3367 #endif /* HAVE_GETHOSTBYNAME_R */
3368 Py_END_ALLOW_THREADS
3369 ret
= gethost_common(h
, (struct sockaddr
*)&addr
, sizeof(addr
), af
);
3370 #ifdef USE_GETHOSTBYNAME_LOCK
3371 PyThread_release_lock(netdb_lock
);
3376 PyDoc_STRVAR(gethostbyaddr_doc
,
3377 "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
3379 Return the true host name, a list of aliases, and a list of IP addresses,\n\
3380 for a host. The host argument is a string giving a host name or IP number.");
3383 /* Python interface to getservbyname(name).
3384 This only returns the port number, since the other info is already
3385 known or not useful (like the list of aliases). */
3389 socket_getservbyname(PyObject
*self
, PyObject
*args
)
3391 char *name
, *proto
=NULL
;
3393 if (!PyArg_ParseTuple(args
, "s|s:getservbyname", &name
, &proto
))
3395 Py_BEGIN_ALLOW_THREADS
3396 sp
= getservbyname(name
, proto
);
3397 Py_END_ALLOW_THREADS
3399 PyErr_SetString(socket_error
, "service/proto not found");
3402 return PyInt_FromLong((long) ntohs(sp
->s_port
));
3405 PyDoc_STRVAR(getservbyname_doc
,
3406 "getservbyname(servicename[, protocolname]) -> integer\n\
3408 Return a port number from a service name and protocol name.\n\
3409 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3410 otherwise any protocol will match.");
3413 /* Python interface to getservbyport(port).
3414 This only returns the service name, since the other info is already
3415 known or not useful (like the list of aliases). */
3419 socket_getservbyport(PyObject
*self
, PyObject
*args
)
3421 unsigned short port
;
3424 if (!PyArg_ParseTuple(args
, "H|s:getservbyport", &port
, &proto
))
3426 Py_BEGIN_ALLOW_THREADS
3427 sp
= getservbyport(htons(port
), proto
);
3428 Py_END_ALLOW_THREADS
3430 PyErr_SetString(socket_error
, "port/proto not found");
3433 return PyString_FromString(sp
->s_name
);
3436 PyDoc_STRVAR(getservbyport_doc
,
3437 "getservbyport(port[, protocolname]) -> string\n\
3439 Return the service name from a port number and protocol name.\n\
3440 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3441 otherwise any protocol will match.");
3443 /* Python interface to getprotobyname(name).
3444 This only returns the protocol number, since the other info is
3445 already known or not useful (like the list of aliases). */
3449 socket_getprotobyname(PyObject
*self
, PyObject
*args
)
3452 struct protoent
*sp
;
3454 /* Not available in BeOS yet. - [cjh] */
3455 PyErr_SetString(socket_error
, "getprotobyname not supported");
3458 if (!PyArg_ParseTuple(args
, "s:getprotobyname", &name
))
3460 Py_BEGIN_ALLOW_THREADS
3461 sp
= getprotobyname(name
);
3462 Py_END_ALLOW_THREADS
3464 PyErr_SetString(socket_error
, "protocol not found");
3467 return PyInt_FromLong((long) sp
->p_proto
);
3471 PyDoc_STRVAR(getprotobyname_doc
,
3472 "getprotobyname(name) -> integer\n\
3474 Return the protocol number for the named protocol. (Rarely used.)");
3477 #ifdef HAVE_SOCKETPAIR
3478 /* Create a pair of sockets using the socketpair() function.
3479 Arguments as for socket() except the default family is AF_UNIX if
3480 defined on the platform; otherwise, the default is AF_INET. */
3484 socket_socketpair(PyObject
*self
, PyObject
*args
)
3486 PySocketSockObject
*s0
= NULL
, *s1
= NULL
;
3488 int family
, type
= SOCK_STREAM
, proto
= 0;
3489 PyObject
*res
= NULL
;
3491 #if defined(AF_UNIX)
3496 if (!PyArg_ParseTuple(args
, "|iii:socketpair",
3497 &family
, &type
, &proto
))
3499 /* Create a pair of socket fds */
3500 if (socketpair(family
, type
, proto
, sv
) < 0)
3502 s0
= new_sockobject(sv
[0], family
, type
, proto
);
3505 s1
= new_sockobject(sv
[1], family
, type
, proto
);
3508 res
= PyTuple_Pack(2, s0
, s1
);
3522 PyDoc_STRVAR(socketpair_doc
,
3523 "socketpair([family[, type[, proto]]]) -> (socket object, socket object)\n\
3525 Create a pair of socket objects from the sockets returned by the platform\n\
3526 socketpair() function.\n\
3527 The arguments are the same as for socket() except the default family is\n\
3528 AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");
3530 #endif /* HAVE_SOCKETPAIR */
3534 /* Create a socket object from a numeric file description.
3535 Useful e.g. if stdin is a socket.
3536 Additional arguments as for socket(). */
3540 socket_fromfd(PyObject
*self
, PyObject
*args
)
3542 PySocketSockObject
*s
;
3544 int family
, type
, proto
= 0;
3545 if (!PyArg_ParseTuple(args
, "iii|i:fromfd",
3546 &fd
, &family
, &type
, &proto
))
3548 /* Dup the fd so it and the socket can be closed independently */
3552 s
= new_sockobject(fd
, family
, type
, proto
);
3553 return (PyObject
*) s
;
3556 PyDoc_STRVAR(fromfd_doc
,
3557 "fromfd(fd, family, type[, proto]) -> socket object\n\
3559 Create a socket object from a duplicate of the given\n\
3561 The remaining arguments are the same as for socket().");
3567 socket_ntohs(PyObject
*self
, PyObject
*args
)
3571 if (!PyArg_ParseTuple(args
, "i:ntohs", &x1
)) {
3575 PyErr_SetString(PyExc_OverflowError
,
3576 "can't convert negative number to unsigned long");
3579 x2
= (unsigned int)ntohs((unsigned short)x1
);
3580 return PyInt_FromLong(x2
);
3583 PyDoc_STRVAR(ntohs_doc
,
3584 "ntohs(integer) -> integer\n\
3586 Convert a 16-bit integer from network to host byte order.");
3590 socket_ntohl(PyObject
*self
, PyObject
*arg
)
3594 if (PyInt_Check(arg
)) {
3595 x
= PyInt_AS_LONG(arg
);
3596 if (x
== (unsigned long) -1 && PyErr_Occurred())
3599 PyErr_SetString(PyExc_OverflowError
,
3600 "can't convert negative number to unsigned long");
3604 else if (PyLong_Check(arg
)) {
3605 x
= PyLong_AsUnsignedLong(arg
);
3606 if (x
== (unsigned long) -1 && PyErr_Occurred())
3611 /* only want the trailing 32 bits */
3612 y
= x
& 0xFFFFFFFFUL
;
3614 return PyErr_Format(PyExc_OverflowError
,
3615 "long int larger than 32 bits");
3621 return PyErr_Format(PyExc_TypeError
,
3622 "expected int/long, %s found",
3623 Py_TYPE(arg
)->tp_name
);
3624 if (x
== (unsigned long) -1 && PyErr_Occurred())
3626 return PyLong_FromUnsignedLong(ntohl(x
));
3629 PyDoc_STRVAR(ntohl_doc
,
3630 "ntohl(integer) -> integer\n\
3632 Convert a 32-bit integer from network to host byte order.");
3636 socket_htons(PyObject
*self
, PyObject
*args
)
3640 if (!PyArg_ParseTuple(args
, "i:htons", &x1
)) {
3644 PyErr_SetString(PyExc_OverflowError
,
3645 "can't convert negative number to unsigned long");
3648 x2
= (unsigned int)htons((unsigned short)x1
);
3649 return PyInt_FromLong(x2
);
3652 PyDoc_STRVAR(htons_doc
,
3653 "htons(integer) -> integer\n\
3655 Convert a 16-bit integer from host to network byte order.");
3659 socket_htonl(PyObject
*self
, PyObject
*arg
)
3663 if (PyInt_Check(arg
)) {
3664 x
= PyInt_AS_LONG(arg
);
3665 if (x
== (unsigned long) -1 && PyErr_Occurred())
3668 PyErr_SetString(PyExc_OverflowError
,
3669 "can't convert negative number to unsigned long");
3673 else if (PyLong_Check(arg
)) {
3674 x
= PyLong_AsUnsignedLong(arg
);
3675 if (x
== (unsigned long) -1 && PyErr_Occurred())
3680 /* only want the trailing 32 bits */
3681 y
= x
& 0xFFFFFFFFUL
;
3683 return PyErr_Format(PyExc_OverflowError
,
3684 "long int larger than 32 bits");
3690 return PyErr_Format(PyExc_TypeError
,
3691 "expected int/long, %s found",
3692 Py_TYPE(arg
)->tp_name
);
3693 return PyLong_FromUnsignedLong(htonl((unsigned long)x
));
3696 PyDoc_STRVAR(htonl_doc
,
3697 "htonl(integer) -> integer\n\
3699 Convert a 32-bit integer from host to network byte order.");
3701 /* socket.inet_aton() and socket.inet_ntoa() functions. */
3703 PyDoc_STRVAR(inet_aton_doc
,
3704 "inet_aton(string) -> packed 32-bit IP representation\n\
3706 Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
3707 binary format used in low-level network functions.");
3710 socket_inet_aton(PyObject
*self
, PyObject
*args
)
3713 #define INADDR_NONE (-1)
3715 #ifdef HAVE_INET_ATON
3719 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
3720 /* Have to use inet_addr() instead */
3721 unsigned long packed_addr
;
3725 if (!PyArg_ParseTuple(args
, "s:inet_aton", &ip_addr
))
3729 #ifdef HAVE_INET_ATON
3731 #ifdef USE_INET_ATON_WEAKLINK
3732 if (inet_aton
!= NULL
) {
3734 if (inet_aton(ip_addr
, &buf
))
3735 return PyString_FromStringAndSize((char *)(&buf
),
3738 PyErr_SetString(socket_error
,
3739 "illegal IP address string passed to inet_aton");
3742 #ifdef USE_INET_ATON_WEAKLINK
3748 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
3750 /* special-case this address as inet_addr might return INADDR_NONE
3752 if (strcmp(ip_addr
, "255.255.255.255") == 0) {
3753 packed_addr
= 0xFFFFFFFF;
3756 packed_addr
= inet_addr(ip_addr
);
3758 if (packed_addr
== INADDR_NONE
) { /* invalid address */
3759 PyErr_SetString(socket_error
,
3760 "illegal IP address string passed to inet_aton");
3764 return PyString_FromStringAndSize((char *) &packed_addr
,
3765 sizeof(packed_addr
));
3767 #ifdef USE_INET_ATON_WEAKLINK
3774 PyDoc_STRVAR(inet_ntoa_doc
,
3775 "inet_ntoa(packed_ip) -> ip_address_string\n\
3777 Convert an IP address from 32-bit packed binary format to string format");
3780 socket_inet_ntoa(PyObject
*self
, PyObject
*args
)
3784 struct in_addr packed_addr
;
3786 if (!PyArg_ParseTuple(args
, "s#:inet_ntoa", &packed_str
, &addr_len
)) {
3790 if (addr_len
!= sizeof(packed_addr
)) {
3791 PyErr_SetString(socket_error
,
3792 "packed IP wrong length for inet_ntoa");
3796 memcpy(&packed_addr
, packed_str
, addr_len
);
3798 return PyString_FromString(inet_ntoa(packed_addr
));
3801 #ifdef HAVE_INET_PTON
3803 PyDoc_STRVAR(inet_pton_doc
,
3804 "inet_pton(af, ip) -> packed IP address string\n\
3806 Convert an IP address from string format to a packed string suitable\n\
3807 for use with low-level network functions.");
3810 socket_inet_pton(PyObject
*self
, PyObject
*args
)
3816 char packed
[MAX(sizeof(struct in_addr
), sizeof(struct in6_addr
))];
3818 char packed
[sizeof(struct in_addr
)];
3820 if (!PyArg_ParseTuple(args
, "is:inet_pton", &af
, &ip
)) {
3824 #if !defined(ENABLE_IPV6) && defined(AF_INET6)
3825 if(af
== AF_INET6
) {
3826 PyErr_SetString(socket_error
,
3827 "can't use AF_INET6, IPv6 is disabled");
3832 retval
= inet_pton(af
, ip
, packed
);
3834 PyErr_SetFromErrno(socket_error
);
3836 } else if (retval
== 0) {
3837 PyErr_SetString(socket_error
,
3838 "illegal IP address string passed to inet_pton");
3840 } else if (af
== AF_INET
) {
3841 return PyString_FromStringAndSize(packed
,
3842 sizeof(struct in_addr
));
3844 } else if (af
== AF_INET6
) {
3845 return PyString_FromStringAndSize(packed
,
3846 sizeof(struct in6_addr
));
3849 PyErr_SetString(socket_error
, "unknown address family");
3854 PyDoc_STRVAR(inet_ntop_doc
,
3855 "inet_ntop(af, packed_ip) -> string formatted IP address\n\
3857 Convert a packed IP address of the given family to string format.");
3860 socket_inet_ntop(PyObject
*self
, PyObject
*args
)
3867 char ip
[MAX(INET_ADDRSTRLEN
, INET6_ADDRSTRLEN
) + 1];
3869 char ip
[INET_ADDRSTRLEN
+ 1];
3872 /* Guarantee NUL-termination for PyString_FromString() below */
3873 memset((void *) &ip
[0], '\0', sizeof(ip
));
3875 if (!PyArg_ParseTuple(args
, "is#:inet_ntop", &af
, &packed
, &len
)) {
3879 if (af
== AF_INET
) {
3880 if (len
!= sizeof(struct in_addr
)) {
3881 PyErr_SetString(PyExc_ValueError
,
3882 "invalid length of packed IP address string");
3886 } else if (af
== AF_INET6
) {
3887 if (len
!= sizeof(struct in6_addr
)) {
3888 PyErr_SetString(PyExc_ValueError
,
3889 "invalid length of packed IP address string");
3894 PyErr_Format(PyExc_ValueError
,
3895 "unknown address family %d", af
);
3899 retval
= inet_ntop(af
, packed
, ip
, sizeof(ip
));
3901 PyErr_SetFromErrno(socket_error
);
3904 return PyString_FromString(retval
);
3908 PyErr_SetString(PyExc_RuntimeError
, "invalid handling of inet_ntop");
3912 #endif /* HAVE_INET_PTON */
3914 /* Python interface to getaddrinfo(host, port). */
3918 socket_getaddrinfo(PyObject
*self
, PyObject
*args
)
3920 struct addrinfo hints
, *res
;
3921 struct addrinfo
*res0
= NULL
;
3922 PyObject
*hobj
= NULL
;
3923 PyObject
*pobj
= (PyObject
*)NULL
;
3926 int family
, socktype
, protocol
, flags
;
3928 PyObject
*all
= (PyObject
*)NULL
;
3929 PyObject
*single
= (PyObject
*)NULL
;
3930 PyObject
*idna
= NULL
;
3932 family
= socktype
= protocol
= flags
= 0;
3934 if (!PyArg_ParseTuple(args
, "OO|iiii:getaddrinfo",
3935 &hobj
, &pobj
, &family
, &socktype
,
3936 &protocol
, &flags
)) {
3939 if (hobj
== Py_None
) {
3941 } else if (PyUnicode_Check(hobj
)) {
3942 idna
= PyObject_CallMethod(hobj
, "encode", "s", "idna");
3945 hptr
= PyString_AsString(idna
);
3946 } else if (PyString_Check(hobj
)) {
3947 hptr
= PyString_AsString(hobj
);
3949 PyErr_SetString(PyExc_TypeError
,
3950 "getaddrinfo() argument 1 must be string or None");
3953 if (PyInt_Check(pobj
)) {
3954 PyOS_snprintf(pbuf
, sizeof(pbuf
), "%ld", PyInt_AsLong(pobj
));
3956 } else if (PyString_Check(pobj
)) {
3957 pptr
= PyString_AsString(pobj
);
3958 } else if (pobj
== Py_None
) {
3959 pptr
= (char *)NULL
;
3961 PyErr_SetString(socket_error
, "Int or String expected");
3964 memset(&hints
, 0, sizeof(hints
));
3965 hints
.ai_family
= family
;
3966 hints
.ai_socktype
= socktype
;
3967 hints
.ai_protocol
= protocol
;
3968 hints
.ai_flags
= flags
;
3969 Py_BEGIN_ALLOW_THREADS
3970 ACQUIRE_GETADDRINFO_LOCK
3971 error
= getaddrinfo(hptr
, pptr
, &hints
, &res0
);
3972 Py_END_ALLOW_THREADS
3973 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
3975 set_gaierror(error
);
3979 if ((all
= PyList_New(0)) == NULL
)
3981 for (res
= res0
; res
; res
= res
->ai_next
) {
3983 makesockaddr(-1, res
->ai_addr
, res
->ai_addrlen
, protocol
);
3986 single
= Py_BuildValue("iiisO", res
->ai_family
,
3987 res
->ai_socktype
, res
->ai_protocol
,
3988 res
->ai_canonname
? res
->ai_canonname
: "",
3994 if (PyList_Append(all
, single
))
4008 return (PyObject
*)NULL
;
4011 PyDoc_STRVAR(getaddrinfo_doc
,
4012 "getaddrinfo(host, port [, family, socktype, proto, flags])\n\
4013 -> list of (family, socktype, proto, canonname, sockaddr)\n\
4015 Resolve host and port into addrinfo struct.");
4017 /* Python interface to getnameinfo(sa, flags). */
4021 socket_getnameinfo(PyObject
*self
, PyObject
*args
)
4023 PyObject
*sa
= (PyObject
*)NULL
;
4026 int port
, flowinfo
, scope_id
;
4027 char hbuf
[NI_MAXHOST
], pbuf
[NI_MAXSERV
];
4028 struct addrinfo hints
, *res
= NULL
;
4030 PyObject
*ret
= (PyObject
*)NULL
;
4032 flags
= flowinfo
= scope_id
= 0;
4033 if (!PyArg_ParseTuple(args
, "Oi:getnameinfo", &sa
, &flags
))
4035 if (!PyArg_ParseTuple(sa
, "si|ii",
4036 &hostp
, &port
, &flowinfo
, &scope_id
))
4038 PyOS_snprintf(pbuf
, sizeof(pbuf
), "%d", port
);
4039 memset(&hints
, 0, sizeof(hints
));
4040 hints
.ai_family
= AF_UNSPEC
;
4041 hints
.ai_socktype
= SOCK_DGRAM
; /* make numeric port happy */
4042 Py_BEGIN_ALLOW_THREADS
4043 ACQUIRE_GETADDRINFO_LOCK
4044 error
= getaddrinfo(hostp
, pbuf
, &hints
, &res
);
4045 Py_END_ALLOW_THREADS
4046 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
4048 set_gaierror(error
);
4052 PyErr_SetString(socket_error
,
4053 "sockaddr resolved to multiple addresses");
4056 switch (res
->ai_family
) {
4061 if (PyArg_ParseTuple(sa
, "si", &t1
, &t2
) == 0) {
4062 PyErr_SetString(socket_error
,
4063 "IPv4 sockaddr must be 2 tuple");
4071 struct sockaddr_in6
*sin6
;
4072 sin6
= (struct sockaddr_in6
*)res
->ai_addr
;
4073 sin6
->sin6_flowinfo
= flowinfo
;
4074 sin6
->sin6_scope_id
= scope_id
;
4079 error
= getnameinfo(res
->ai_addr
, res
->ai_addrlen
,
4080 hbuf
, sizeof(hbuf
), pbuf
, sizeof(pbuf
), flags
);
4082 set_gaierror(error
);
4085 ret
= Py_BuildValue("ss", hbuf
, pbuf
);
4093 PyDoc_STRVAR(getnameinfo_doc
,
4094 "getnameinfo(sockaddr, flags) --> (host, port)\n\
4096 Get host and port for a sockaddr.");
4099 /* Python API to getting and setting the default timeout value. */
4102 socket_getdefaulttimeout(PyObject
*self
)
4104 if (defaulttimeout
< 0.0) {
4109 return PyFloat_FromDouble(defaulttimeout
);
4112 PyDoc_STRVAR(getdefaulttimeout_doc
,
4113 "getdefaulttimeout() -> timeout\n\
4115 Returns the default timeout in floating seconds for new socket objects.\n\
4116 A value of None indicates that new socket objects have no timeout.\n\
4117 When the socket module is first imported, the default is None.");
4120 socket_setdefaulttimeout(PyObject
*self
, PyObject
*arg
)
4127 timeout
= PyFloat_AsDouble(arg
);
4128 if (timeout
< 0.0) {
4129 if (!PyErr_Occurred())
4130 PyErr_SetString(PyExc_ValueError
,
4131 "Timeout value out of range");
4136 defaulttimeout
= timeout
;
4142 PyDoc_STRVAR(setdefaulttimeout_doc
,
4143 "setdefaulttimeout(timeout)\n\
4145 Set the default timeout in floating seconds for new socket objects.\n\
4146 A value of None indicates that new socket objects have no timeout.\n\
4147 When the socket module is first imported, the default is None.");
4150 /* List of functions exported by this module. */
4152 static PyMethodDef socket_methods
[] = {
4153 {"gethostbyname", socket_gethostbyname
,
4154 METH_VARARGS
, gethostbyname_doc
},
4155 {"gethostbyname_ex", socket_gethostbyname_ex
,
4156 METH_VARARGS
, ghbn_ex_doc
},
4157 {"gethostbyaddr", socket_gethostbyaddr
,
4158 METH_VARARGS
, gethostbyaddr_doc
},
4159 {"gethostname", socket_gethostname
,
4160 METH_NOARGS
, gethostname_doc
},
4161 {"getservbyname", socket_getservbyname
,
4162 METH_VARARGS
, getservbyname_doc
},
4163 {"getservbyport", socket_getservbyport
,
4164 METH_VARARGS
, getservbyport_doc
},
4165 {"getprotobyname", socket_getprotobyname
,
4166 METH_VARARGS
, getprotobyname_doc
},
4168 {"fromfd", socket_fromfd
,
4169 METH_VARARGS
, fromfd_doc
},
4171 #ifdef HAVE_SOCKETPAIR
4172 {"socketpair", socket_socketpair
,
4173 METH_VARARGS
, socketpair_doc
},
4175 {"ntohs", socket_ntohs
,
4176 METH_VARARGS
, ntohs_doc
},
4177 {"ntohl", socket_ntohl
,
4179 {"htons", socket_htons
,
4180 METH_VARARGS
, htons_doc
},
4181 {"htonl", socket_htonl
,
4183 {"inet_aton", socket_inet_aton
,
4184 METH_VARARGS
, inet_aton_doc
},
4185 {"inet_ntoa", socket_inet_ntoa
,
4186 METH_VARARGS
, inet_ntoa_doc
},
4187 #ifdef HAVE_INET_PTON
4188 {"inet_pton", socket_inet_pton
,
4189 METH_VARARGS
, inet_pton_doc
},
4190 {"inet_ntop", socket_inet_ntop
,
4191 METH_VARARGS
, inet_ntop_doc
},
4193 {"getaddrinfo", socket_getaddrinfo
,
4194 METH_VARARGS
, getaddrinfo_doc
},
4195 {"getnameinfo", socket_getnameinfo
,
4196 METH_VARARGS
, getnameinfo_doc
},
4197 {"getdefaulttimeout", (PyCFunction
)socket_getdefaulttimeout
,
4198 METH_NOARGS
, getdefaulttimeout_doc
},
4199 {"setdefaulttimeout", socket_setdefaulttimeout
,
4200 METH_O
, setdefaulttimeout_doc
},
4201 {NULL
, NULL
} /* Sentinel */
4206 #define OS_INIT_DEFINED
4214 _kernel_swi(0x43380, &r
, &r
);
4215 taskwindow
= r
.r
[0];
4224 #define OS_INIT_DEFINED
4226 /* Additional initialization and cleanup for Windows */
4240 ret
= WSAStartup(0x0101, &WSAData
);
4242 case 0: /* No error */
4243 Py_AtExit(os_cleanup
);
4244 return 1; /* Success */
4245 case WSASYSNOTREADY
:
4246 PyErr_SetString(PyExc_ImportError
,
4247 "WSAStartup failed: network not ready");
4249 case WSAVERNOTSUPPORTED
:
4253 "WSAStartup failed: requested version not supported");
4256 PyOS_snprintf(buf
, sizeof(buf
),
4257 "WSAStartup failed: error code %d", ret
);
4258 PyErr_SetString(PyExc_ImportError
, buf
);
4261 return 0; /* Failure */
4264 #endif /* MS_WINDOWS */
4268 #define OS_INIT_DEFINED
4270 /* Additional initialization for OS/2 */
4277 int rc
= sock_init();
4280 return 1; /* Success */
4283 PyOS_snprintf(reason
, sizeof(reason
),
4284 "OS/2 TCP/IP Error# %d", sock_errno());
4285 PyErr_SetString(PyExc_ImportError
, reason
);
4287 return 0; /* Failure */
4289 /* No need to initialise sockets with GCC/EMX */
4290 return 1; /* Success */
4294 #endif /* PYOS_OS2 */
4297 #ifndef OS_INIT_DEFINED
4301 return 1; /* Success */
4306 /* C API table - always add new things to the end for binary
4309 PySocketModule_APIObject PySocketModuleAPI
=
4316 /* Initialize the _socket module.
4318 This module is actually called "_socket", and there's a wrapper
4319 "socket.py" which implements some additional functionality. On some
4320 platforms (e.g. Windows and OS/2), socket.py also implements a
4321 wrapper for the socket type that provides missing functionality such
4322 as makefile(), dup() and fromfd(). The import of "_socket" may fail
4323 with an ImportError exception if os-specific initialization fails.
4324 On Windows, this does WINSOCK initialization. When WINSOCK is
4325 initialized succesfully, a call to WSACleanup() is scheduled to be
4329 PyDoc_STRVAR(socket_doc
,
4330 "Implementation module for socket operations.\n\
4332 See the socket module for documentation.");
4337 PyObject
*m
, *has_ipv6
, *tmp
;
4342 Py_TYPE(&sock_type
) = &PyType_Type
;
4343 m
= Py_InitModule3(PySocket_MODULE_NAME
,
4349 socket_error
= PyErr_NewException("socket.error",
4350 PyExc_IOError
, NULL
);
4351 if (socket_error
== NULL
)
4353 PySocketModuleAPI
.error
= socket_error
;
4354 Py_INCREF(socket_error
);
4355 PyModule_AddObject(m
, "error", socket_error
);
4356 socket_herror
= PyErr_NewException("socket.herror",
4357 socket_error
, NULL
);
4358 if (socket_herror
== NULL
)
4360 Py_INCREF(socket_herror
);
4361 PyModule_AddObject(m
, "herror", socket_herror
);
4362 socket_gaierror
= PyErr_NewException("socket.gaierror", socket_error
,
4364 if (socket_gaierror
== NULL
)
4366 Py_INCREF(socket_gaierror
);
4367 PyModule_AddObject(m
, "gaierror", socket_gaierror
);
4368 socket_timeout
= PyErr_NewException("socket.timeout",
4369 socket_error
, NULL
);
4370 if (socket_timeout
== NULL
)
4372 Py_INCREF(socket_timeout
);
4373 PyModule_AddObject(m
, "timeout", socket_timeout
);
4374 Py_INCREF((PyObject
*)&sock_type
);
4375 if (PyModule_AddObject(m
, "SocketType",
4376 (PyObject
*)&sock_type
) != 0)
4378 Py_INCREF((PyObject
*)&sock_type
);
4379 if (PyModule_AddObject(m
, "socket",
4380 (PyObject
*)&sock_type
) != 0)
4386 has_ipv6
= Py_False
;
4388 Py_INCREF(has_ipv6
);
4389 PyModule_AddObject(m
, "has_ipv6", has_ipv6
);
4392 if (PyModule_AddObject(m
, PySocket_CAPI_NAME
,
4393 PyCObject_FromVoidPtr((void *)&PySocketModuleAPI
, NULL
)
4397 /* Address families (we only support AF_INET and AF_UNIX) */
4399 PyModule_AddIntConstant(m
, "AF_UNSPEC", AF_UNSPEC
);
4401 PyModule_AddIntConstant(m
, "AF_INET", AF_INET
);
4403 PyModule_AddIntConstant(m
, "AF_INET6", AF_INET6
);
4404 #endif /* AF_INET6 */
4405 #if defined(AF_UNIX)
4406 PyModule_AddIntConstant(m
, "AF_UNIX", AF_UNIX
);
4407 #endif /* AF_UNIX */
4409 /* Amateur Radio AX.25 */
4410 PyModule_AddIntConstant(m
, "AF_AX25", AF_AX25
);
4413 PyModule_AddIntConstant(m
, "AF_IPX", AF_IPX
); /* Novell IPX */
4417 PyModule_AddIntConstant(m
, "AF_APPLETALK", AF_APPLETALK
);
4420 /* Amateur radio NetROM */
4421 PyModule_AddIntConstant(m
, "AF_NETROM", AF_NETROM
);
4424 /* Multiprotocol bridge */
4425 PyModule_AddIntConstant(m
, "AF_BRIDGE", AF_BRIDGE
);
4429 PyModule_AddIntConstant(m
, "AF_ATMPVC", AF_ATMPVC
);
4432 /* Reserved for Werner's ATM */
4433 PyModule_AddIntConstant(m
, "AF_AAL5", AF_AAL5
);
4436 /* Reserved for X.25 project */
4437 PyModule_AddIntConstant(m
, "AF_X25", AF_X25
);
4440 PyModule_AddIntConstant(m
, "AF_INET6", AF_INET6
); /* IP version 6 */
4443 /* Amateur Radio X.25 PLP */
4444 PyModule_AddIntConstant(m
, "AF_ROSE", AF_ROSE
);
4447 /* Reserved for DECnet project */
4448 PyModule_AddIntConstant(m
, "AF_DECnet", AF_DECnet
);
4451 /* Reserved for 802.2LLC project */
4452 PyModule_AddIntConstant(m
, "AF_NETBEUI", AF_NETBEUI
);
4455 /* Security callback pseudo AF */
4456 PyModule_AddIntConstant(m
, "AF_SECURITY", AF_SECURITY
);
4459 /* PF_KEY key management API */
4460 PyModule_AddIntConstant(m
, "AF_KEY", AF_KEY
);
4464 PyModule_AddIntConstant(m
, "AF_NETLINK", AF_NETLINK
);
4465 PyModule_AddIntConstant(m
, "NETLINK_ROUTE", NETLINK_ROUTE
);
4467 PyModule_AddIntConstant(m
, "NETLINK_SKIP", NETLINK_SKIP
);
4470 PyModule_AddIntConstant(m
, "NETLINK_W1", NETLINK_W1
);
4472 PyModule_AddIntConstant(m
, "NETLINK_USERSOCK", NETLINK_USERSOCK
);
4473 PyModule_AddIntConstant(m
, "NETLINK_FIREWALL", NETLINK_FIREWALL
);
4474 #ifdef NETLINK_TCPDIAG
4475 PyModule_AddIntConstant(m
, "NETLINK_TCPDIAG", NETLINK_TCPDIAG
);
4477 #ifdef NETLINK_NFLOG
4478 PyModule_AddIntConstant(m
, "NETLINK_NFLOG", NETLINK_NFLOG
);
4481 PyModule_AddIntConstant(m
, "NETLINK_XFRM", NETLINK_XFRM
);
4484 PyModule_AddIntConstant(m
, "NETLINK_ARPD", NETLINK_ARPD
);
4486 #ifdef NETLINK_ROUTE6
4487 PyModule_AddIntConstant(m
, "NETLINK_ROUTE6", NETLINK_ROUTE6
);
4489 PyModule_AddIntConstant(m
, "NETLINK_IP6_FW", NETLINK_IP6_FW
);
4490 #ifdef NETLINK_DNRTMSG
4491 PyModule_AddIntConstant(m
, "NETLINK_DNRTMSG", NETLINK_DNRTMSG
);
4493 #ifdef NETLINK_TAPBASE
4494 PyModule_AddIntConstant(m
, "NETLINK_TAPBASE", NETLINK_TAPBASE
);
4496 #endif /* AF_NETLINK */
4498 /* Alias to emulate 4.4BSD */
4499 PyModule_AddIntConstant(m
, "AF_ROUTE", AF_ROUTE
);
4503 PyModule_AddIntConstant(m
, "AF_ASH", AF_ASH
);
4507 PyModule_AddIntConstant(m
, "AF_ECONET", AF_ECONET
);
4511 PyModule_AddIntConstant(m
, "AF_ATMSVC", AF_ATMSVC
);
4514 /* Linux SNA Project (nutters!) */
4515 PyModule_AddIntConstant(m
, "AF_SNA", AF_SNA
);
4519 PyModule_AddIntConstant(m
, "AF_IRDA", AF_IRDA
);
4523 PyModule_AddIntConstant(m
, "AF_PPPOX", AF_PPPOX
);
4526 /* Wanpipe API Sockets */
4527 PyModule_AddIntConstant(m
, "AF_WANPIPE", AF_WANPIPE
);
4531 PyModule_AddIntConstant(m
, "AF_LLC", AF_LLC
);
4534 #ifdef USE_BLUETOOTH
4535 PyModule_AddIntConstant(m
, "AF_BLUETOOTH", AF_BLUETOOTH
);
4536 PyModule_AddIntConstant(m
, "BTPROTO_L2CAP", BTPROTO_L2CAP
);
4537 PyModule_AddIntConstant(m
, "BTPROTO_HCI", BTPROTO_HCI
);
4538 PyModule_AddIntConstant(m
, "SOL_HCI", SOL_HCI
);
4539 PyModule_AddIntConstant(m
, "HCI_FILTER", HCI_FILTER
);
4540 #if !defined(__FreeBSD__)
4541 PyModule_AddIntConstant(m
, "HCI_TIME_STAMP", HCI_TIME_STAMP
);
4542 PyModule_AddIntConstant(m
, "HCI_DATA_DIR", HCI_DATA_DIR
);
4543 PyModule_AddIntConstant(m
, "BTPROTO_SCO", BTPROTO_SCO
);
4545 PyModule_AddIntConstant(m
, "BTPROTO_RFCOMM", BTPROTO_RFCOMM
);
4546 PyModule_AddStringConstant(m
, "BDADDR_ANY", "00:00:00:00:00:00");
4547 PyModule_AddStringConstant(m
, "BDADDR_LOCAL", "00:00:00:FF:FF:FF");
4550 #ifdef HAVE_NETPACKET_PACKET_H
4551 PyModule_AddIntConstant(m
, "AF_PACKET", AF_PACKET
);
4552 PyModule_AddIntConstant(m
, "PF_PACKET", PF_PACKET
);
4553 PyModule_AddIntConstant(m
, "PACKET_HOST", PACKET_HOST
);
4554 PyModule_AddIntConstant(m
, "PACKET_BROADCAST", PACKET_BROADCAST
);
4555 PyModule_AddIntConstant(m
, "PACKET_MULTICAST", PACKET_MULTICAST
);
4556 PyModule_AddIntConstant(m
, "PACKET_OTHERHOST", PACKET_OTHERHOST
);
4557 PyModule_AddIntConstant(m
, "PACKET_OUTGOING", PACKET_OUTGOING
);
4558 PyModule_AddIntConstant(m
, "PACKET_LOOPBACK", PACKET_LOOPBACK
);
4559 PyModule_AddIntConstant(m
, "PACKET_FASTROUTE", PACKET_FASTROUTE
);
4562 #ifdef HAVE_LINUX_TIPC_H
4563 PyModule_AddIntConstant(m
, "AF_TIPC", AF_TIPC
);
4566 PyModule_AddIntConstant(m
, "TIPC_ADDR_NAMESEQ", TIPC_ADDR_NAMESEQ
);
4567 PyModule_AddIntConstant(m
, "TIPC_ADDR_NAME", TIPC_ADDR_NAME
);
4568 PyModule_AddIntConstant(m
, "TIPC_ADDR_ID", TIPC_ADDR_ID
);
4570 PyModule_AddIntConstant(m
, "TIPC_ZONE_SCOPE", TIPC_ZONE_SCOPE
);
4571 PyModule_AddIntConstant(m
, "TIPC_CLUSTER_SCOPE", TIPC_CLUSTER_SCOPE
);
4572 PyModule_AddIntConstant(m
, "TIPC_NODE_SCOPE", TIPC_NODE_SCOPE
);
4574 /* for setsockopt() */
4575 PyModule_AddIntConstant(m
, "SOL_TIPC", SOL_TIPC
);
4576 PyModule_AddIntConstant(m
, "TIPC_IMPORTANCE", TIPC_IMPORTANCE
);
4577 PyModule_AddIntConstant(m
, "TIPC_SRC_DROPPABLE", TIPC_SRC_DROPPABLE
);
4578 PyModule_AddIntConstant(m
, "TIPC_DEST_DROPPABLE",
4579 TIPC_DEST_DROPPABLE
);
4580 PyModule_AddIntConstant(m
, "TIPC_CONN_TIMEOUT", TIPC_CONN_TIMEOUT
);
4582 PyModule_AddIntConstant(m
, "TIPC_LOW_IMPORTANCE",
4583 TIPC_LOW_IMPORTANCE
);
4584 PyModule_AddIntConstant(m
, "TIPC_MEDIUM_IMPORTANCE",
4585 TIPC_MEDIUM_IMPORTANCE
);
4586 PyModule_AddIntConstant(m
, "TIPC_HIGH_IMPORTANCE",
4587 TIPC_HIGH_IMPORTANCE
);
4588 PyModule_AddIntConstant(m
, "TIPC_CRITICAL_IMPORTANCE",
4589 TIPC_CRITICAL_IMPORTANCE
);
4591 /* for subscriptions */
4592 PyModule_AddIntConstant(m
, "TIPC_SUB_PORTS", TIPC_SUB_PORTS
);
4593 PyModule_AddIntConstant(m
, "TIPC_SUB_SERVICE", TIPC_SUB_SERVICE
);
4594 PyModule_AddIntConstant(m
, "TIPC_SUB_CANCEL", TIPC_SUB_CANCEL
);
4595 PyModule_AddIntConstant(m
, "TIPC_WAIT_FOREVER", TIPC_WAIT_FOREVER
);
4596 PyModule_AddIntConstant(m
, "TIPC_PUBLISHED", TIPC_PUBLISHED
);
4597 PyModule_AddIntConstant(m
, "TIPC_WITHDRAWN", TIPC_WITHDRAWN
);
4598 PyModule_AddIntConstant(m
, "TIPC_SUBSCR_TIMEOUT", TIPC_SUBSCR_TIMEOUT
);
4599 PyModule_AddIntConstant(m
, "TIPC_CFG_SRV", TIPC_CFG_SRV
);
4600 PyModule_AddIntConstant(m
, "TIPC_TOP_SRV", TIPC_TOP_SRV
);
4604 PyModule_AddIntConstant(m
, "SOCK_STREAM", SOCK_STREAM
);
4605 PyModule_AddIntConstant(m
, "SOCK_DGRAM", SOCK_DGRAM
);
4607 /* We have incomplete socket support. */
4608 PyModule_AddIntConstant(m
, "SOCK_RAW", SOCK_RAW
);
4609 PyModule_AddIntConstant(m
, "SOCK_SEQPACKET", SOCK_SEQPACKET
);
4610 #if defined(SOCK_RDM)
4611 PyModule_AddIntConstant(m
, "SOCK_RDM", SOCK_RDM
);
4616 PyModule_AddIntConstant(m
, "SO_DEBUG", SO_DEBUG
);
4618 #ifdef SO_ACCEPTCONN
4619 PyModule_AddIntConstant(m
, "SO_ACCEPTCONN", SO_ACCEPTCONN
);
4622 PyModule_AddIntConstant(m
, "SO_REUSEADDR", SO_REUSEADDR
);
4624 #ifdef SO_EXCLUSIVEADDRUSE
4625 PyModule_AddIntConstant(m
, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE
);
4629 PyModule_AddIntConstant(m
, "SO_KEEPALIVE", SO_KEEPALIVE
);
4632 PyModule_AddIntConstant(m
, "SO_DONTROUTE", SO_DONTROUTE
);
4635 PyModule_AddIntConstant(m
, "SO_BROADCAST", SO_BROADCAST
);
4637 #ifdef SO_USELOOPBACK
4638 PyModule_AddIntConstant(m
, "SO_USELOOPBACK", SO_USELOOPBACK
);
4641 PyModule_AddIntConstant(m
, "SO_LINGER", SO_LINGER
);
4644 PyModule_AddIntConstant(m
, "SO_OOBINLINE", SO_OOBINLINE
);
4647 PyModule_AddIntConstant(m
, "SO_REUSEPORT", SO_REUSEPORT
);
4650 PyModule_AddIntConstant(m
, "SO_SNDBUF", SO_SNDBUF
);
4653 PyModule_AddIntConstant(m
, "SO_RCVBUF", SO_RCVBUF
);
4656 PyModule_AddIntConstant(m
, "SO_SNDLOWAT", SO_SNDLOWAT
);
4659 PyModule_AddIntConstant(m
, "SO_RCVLOWAT", SO_RCVLOWAT
);
4662 PyModule_AddIntConstant(m
, "SO_SNDTIMEO", SO_SNDTIMEO
);
4665 PyModule_AddIntConstant(m
, "SO_RCVTIMEO", SO_RCVTIMEO
);
4668 PyModule_AddIntConstant(m
, "SO_ERROR", SO_ERROR
);
4671 PyModule_AddIntConstant(m
, "SO_TYPE", SO_TYPE
);
4674 /* Maximum number of connections for "listen" */
4676 PyModule_AddIntConstant(m
, "SOMAXCONN", SOMAXCONN
);
4678 PyModule_AddIntConstant(m
, "SOMAXCONN", 5); /* Common value */
4681 /* Flags for send, recv */
4683 PyModule_AddIntConstant(m
, "MSG_OOB", MSG_OOB
);
4686 PyModule_AddIntConstant(m
, "MSG_PEEK", MSG_PEEK
);
4688 #ifdef MSG_DONTROUTE
4689 PyModule_AddIntConstant(m
, "MSG_DONTROUTE", MSG_DONTROUTE
);
4692 PyModule_AddIntConstant(m
, "MSG_DONTWAIT", MSG_DONTWAIT
);
4695 PyModule_AddIntConstant(m
, "MSG_EOR", MSG_EOR
);
4698 PyModule_AddIntConstant(m
, "MSG_TRUNC", MSG_TRUNC
);
4701 PyModule_AddIntConstant(m
, "MSG_CTRUNC", MSG_CTRUNC
);
4704 PyModule_AddIntConstant(m
, "MSG_WAITALL", MSG_WAITALL
);
4707 PyModule_AddIntConstant(m
, "MSG_BTAG", MSG_BTAG
);
4710 PyModule_AddIntConstant(m
, "MSG_ETAG", MSG_ETAG
);
4713 /* Protocol level and numbers, usable for [gs]etsockopt */
4715 PyModule_AddIntConstant(m
, "SOL_SOCKET", SOL_SOCKET
);
4718 PyModule_AddIntConstant(m
, "SOL_IP", SOL_IP
);
4720 PyModule_AddIntConstant(m
, "SOL_IP", 0);
4723 PyModule_AddIntConstant(m
, "SOL_IPX", SOL_IPX
);
4726 PyModule_AddIntConstant(m
, "SOL_AX25", SOL_AX25
);
4729 PyModule_AddIntConstant(m
, "SOL_ATALK", SOL_ATALK
);
4732 PyModule_AddIntConstant(m
, "SOL_NETROM", SOL_NETROM
);
4735 PyModule_AddIntConstant(m
, "SOL_ROSE", SOL_ROSE
);
4738 PyModule_AddIntConstant(m
, "SOL_TCP", SOL_TCP
);
4740 PyModule_AddIntConstant(m
, "SOL_TCP", 6);
4743 PyModule_AddIntConstant(m
, "SOL_UDP", SOL_UDP
);
4745 PyModule_AddIntConstant(m
, "SOL_UDP", 17);
4748 PyModule_AddIntConstant(m
, "IPPROTO_IP", IPPROTO_IP
);
4750 PyModule_AddIntConstant(m
, "IPPROTO_IP", 0);
4752 #ifdef IPPROTO_HOPOPTS
4753 PyModule_AddIntConstant(m
, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS
);
4756 PyModule_AddIntConstant(m
, "IPPROTO_ICMP", IPPROTO_ICMP
);
4758 PyModule_AddIntConstant(m
, "IPPROTO_ICMP", 1);
4761 PyModule_AddIntConstant(m
, "IPPROTO_IGMP", IPPROTO_IGMP
);
4764 PyModule_AddIntConstant(m
, "IPPROTO_GGP", IPPROTO_GGP
);
4767 PyModule_AddIntConstant(m
, "IPPROTO_IPV4", IPPROTO_IPV4
);
4770 PyModule_AddIntConstant(m
, "IPPROTO_IPV6", IPPROTO_IPV6
);
4773 PyModule_AddIntConstant(m
, "IPPROTO_IPIP", IPPROTO_IPIP
);
4776 PyModule_AddIntConstant(m
, "IPPROTO_TCP", IPPROTO_TCP
);
4778 PyModule_AddIntConstant(m
, "IPPROTO_TCP", 6);
4781 PyModule_AddIntConstant(m
, "IPPROTO_EGP", IPPROTO_EGP
);
4784 PyModule_AddIntConstant(m
, "IPPROTO_PUP", IPPROTO_PUP
);
4787 PyModule_AddIntConstant(m
, "IPPROTO_UDP", IPPROTO_UDP
);
4789 PyModule_AddIntConstant(m
, "IPPROTO_UDP", 17);
4792 PyModule_AddIntConstant(m
, "IPPROTO_IDP", IPPROTO_IDP
);
4794 #ifdef IPPROTO_HELLO
4795 PyModule_AddIntConstant(m
, "IPPROTO_HELLO", IPPROTO_HELLO
);
4798 PyModule_AddIntConstant(m
, "IPPROTO_ND", IPPROTO_ND
);
4801 PyModule_AddIntConstant(m
, "IPPROTO_TP", IPPROTO_TP
);
4804 PyModule_AddIntConstant(m
, "IPPROTO_IPV6", IPPROTO_IPV6
);
4806 #ifdef IPPROTO_ROUTING
4807 PyModule_AddIntConstant(m
, "IPPROTO_ROUTING", IPPROTO_ROUTING
);
4809 #ifdef IPPROTO_FRAGMENT
4810 PyModule_AddIntConstant(m
, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT
);
4813 PyModule_AddIntConstant(m
, "IPPROTO_RSVP", IPPROTO_RSVP
);
4816 PyModule_AddIntConstant(m
, "IPPROTO_GRE", IPPROTO_GRE
);
4819 PyModule_AddIntConstant(m
, "IPPROTO_ESP", IPPROTO_ESP
);
4822 PyModule_AddIntConstant(m
, "IPPROTO_AH", IPPROTO_AH
);
4824 #ifdef IPPROTO_MOBILE
4825 PyModule_AddIntConstant(m
, "IPPROTO_MOBILE", IPPROTO_MOBILE
);
4827 #ifdef IPPROTO_ICMPV6
4828 PyModule_AddIntConstant(m
, "IPPROTO_ICMPV6", IPPROTO_ICMPV6
);
4831 PyModule_AddIntConstant(m
, "IPPROTO_NONE", IPPROTO_NONE
);
4833 #ifdef IPPROTO_DSTOPTS
4834 PyModule_AddIntConstant(m
, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS
);
4837 PyModule_AddIntConstant(m
, "IPPROTO_XTP", IPPROTO_XTP
);
4840 PyModule_AddIntConstant(m
, "IPPROTO_EON", IPPROTO_EON
);
4843 PyModule_AddIntConstant(m
, "IPPROTO_PIM", IPPROTO_PIM
);
4845 #ifdef IPPROTO_IPCOMP
4846 PyModule_AddIntConstant(m
, "IPPROTO_IPCOMP", IPPROTO_IPCOMP
);
4849 PyModule_AddIntConstant(m
, "IPPROTO_VRRP", IPPROTO_VRRP
);
4852 PyModule_AddIntConstant(m
, "IPPROTO_BIP", IPPROTO_BIP
);
4856 PyModule_AddIntConstant(m
, "IPPROTO_RAW", IPPROTO_RAW
);
4858 PyModule_AddIntConstant(m
, "IPPROTO_RAW", 255);
4861 PyModule_AddIntConstant(m
, "IPPROTO_MAX", IPPROTO_MAX
);
4864 /* Some port configuration */
4865 #ifdef IPPORT_RESERVED
4866 PyModule_AddIntConstant(m
, "IPPORT_RESERVED", IPPORT_RESERVED
);
4868 PyModule_AddIntConstant(m
, "IPPORT_RESERVED", 1024);
4870 #ifdef IPPORT_USERRESERVED
4871 PyModule_AddIntConstant(m
, "IPPORT_USERRESERVED", IPPORT_USERRESERVED
);
4873 PyModule_AddIntConstant(m
, "IPPORT_USERRESERVED", 5000);
4876 /* Some reserved IP v.4 addresses */
4878 PyModule_AddIntConstant(m
, "INADDR_ANY", INADDR_ANY
);
4880 PyModule_AddIntConstant(m
, "INADDR_ANY", 0x00000000);
4882 #ifdef INADDR_BROADCAST
4883 PyModule_AddIntConstant(m
, "INADDR_BROADCAST", INADDR_BROADCAST
);
4885 PyModule_AddIntConstant(m
, "INADDR_BROADCAST", 0xffffffff);
4887 #ifdef INADDR_LOOPBACK
4888 PyModule_AddIntConstant(m
, "INADDR_LOOPBACK", INADDR_LOOPBACK
);
4890 PyModule_AddIntConstant(m
, "INADDR_LOOPBACK", 0x7F000001);
4892 #ifdef INADDR_UNSPEC_GROUP
4893 PyModule_AddIntConstant(m
, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP
);
4895 PyModule_AddIntConstant(m
, "INADDR_UNSPEC_GROUP", 0xe0000000);
4897 #ifdef INADDR_ALLHOSTS_GROUP
4898 PyModule_AddIntConstant(m
, "INADDR_ALLHOSTS_GROUP",
4899 INADDR_ALLHOSTS_GROUP
);
4901 PyModule_AddIntConstant(m
, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
4903 #ifdef INADDR_MAX_LOCAL_GROUP
4904 PyModule_AddIntConstant(m
, "INADDR_MAX_LOCAL_GROUP",
4905 INADDR_MAX_LOCAL_GROUP
);
4907 PyModule_AddIntConstant(m
, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
4910 PyModule_AddIntConstant(m
, "INADDR_NONE", INADDR_NONE
);
4912 PyModule_AddIntConstant(m
, "INADDR_NONE", 0xffffffff);
4915 /* IPv4 [gs]etsockopt options */
4917 PyModule_AddIntConstant(m
, "IP_OPTIONS", IP_OPTIONS
);
4920 PyModule_AddIntConstant(m
, "IP_HDRINCL", IP_HDRINCL
);
4923 PyModule_AddIntConstant(m
, "IP_TOS", IP_TOS
);
4926 PyModule_AddIntConstant(m
, "IP_TTL", IP_TTL
);
4929 PyModule_AddIntConstant(m
, "IP_RECVOPTS", IP_RECVOPTS
);
4931 #ifdef IP_RECVRETOPTS
4932 PyModule_AddIntConstant(m
, "IP_RECVRETOPTS", IP_RECVRETOPTS
);
4934 #ifdef IP_RECVDSTADDR
4935 PyModule_AddIntConstant(m
, "IP_RECVDSTADDR", IP_RECVDSTADDR
);
4938 PyModule_AddIntConstant(m
, "IP_RETOPTS", IP_RETOPTS
);
4940 #ifdef IP_MULTICAST_IF
4941 PyModule_AddIntConstant(m
, "IP_MULTICAST_IF", IP_MULTICAST_IF
);
4943 #ifdef IP_MULTICAST_TTL
4944 PyModule_AddIntConstant(m
, "IP_MULTICAST_TTL", IP_MULTICAST_TTL
);
4946 #ifdef IP_MULTICAST_LOOP
4947 PyModule_AddIntConstant(m
, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP
);
4949 #ifdef IP_ADD_MEMBERSHIP
4950 PyModule_AddIntConstant(m
, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP
);
4952 #ifdef IP_DROP_MEMBERSHIP
4953 PyModule_AddIntConstant(m
, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP
);
4955 #ifdef IP_DEFAULT_MULTICAST_TTL
4956 PyModule_AddIntConstant(m
, "IP_DEFAULT_MULTICAST_TTL",
4957 IP_DEFAULT_MULTICAST_TTL
);
4959 #ifdef IP_DEFAULT_MULTICAST_LOOP
4960 PyModule_AddIntConstant(m
, "IP_DEFAULT_MULTICAST_LOOP",
4961 IP_DEFAULT_MULTICAST_LOOP
);
4963 #ifdef IP_MAX_MEMBERSHIPS
4964 PyModule_AddIntConstant(m
, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS
);
4967 /* IPv6 [gs]etsockopt options, defined in RFC2553 */
4968 #ifdef IPV6_JOIN_GROUP
4969 PyModule_AddIntConstant(m
, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP
);
4971 #ifdef IPV6_LEAVE_GROUP
4972 PyModule_AddIntConstant(m
, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP
);
4974 #ifdef IPV6_MULTICAST_HOPS
4975 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS
);
4977 #ifdef IPV6_MULTICAST_IF
4978 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF
);
4980 #ifdef IPV6_MULTICAST_LOOP
4981 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP
);
4983 #ifdef IPV6_UNICAST_HOPS
4984 PyModule_AddIntConstant(m
, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS
);
4986 /* Additional IPV6 socket options, defined in RFC 3493 */
4988 PyModule_AddIntConstant(m
, "IPV6_V6ONLY", IPV6_V6ONLY
);
4990 /* Advanced IPV6 socket options, from RFC 3542 */
4991 #ifdef IPV6_CHECKSUM
4992 PyModule_AddIntConstant(m
, "IPV6_CHECKSUM", IPV6_CHECKSUM
);
4994 #ifdef IPV6_DONTFRAG
4995 PyModule_AddIntConstant(m
, "IPV6_DONTFRAG", IPV6_DONTFRAG
);
4998 PyModule_AddIntConstant(m
, "IPV6_DSTOPTS", IPV6_DSTOPTS
);
5000 #ifdef IPV6_HOPLIMIT
5001 PyModule_AddIntConstant(m
, "IPV6_HOPLIMIT", IPV6_HOPLIMIT
);
5004 PyModule_AddIntConstant(m
, "IPV6_HOPOPTS", IPV6_HOPOPTS
);
5007 PyModule_AddIntConstant(m
, "IPV6_NEXTHOP", IPV6_NEXTHOP
);
5010 PyModule_AddIntConstant(m
, "IPV6_PATHMTU", IPV6_PATHMTU
);
5013 PyModule_AddIntConstant(m
, "IPV6_PKTINFO", IPV6_PKTINFO
);
5015 #ifdef IPV6_RECVDSTOPTS
5016 PyModule_AddIntConstant(m
, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS
);
5018 #ifdef IPV6_RECVHOPLIMIT
5019 PyModule_AddIntConstant(m
, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT
);
5021 #ifdef IPV6_RECVHOPOPTS
5022 PyModule_AddIntConstant(m
, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS
);
5024 #ifdef IPV6_RECVPKTINFO
5025 PyModule_AddIntConstant(m
, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO
);
5027 #ifdef IPV6_RECVRTHDR
5028 PyModule_AddIntConstant(m
, "IPV6_RECVRTHDR", IPV6_RECVRTHDR
);
5030 #ifdef IPV6_RECVTCLASS
5031 PyModule_AddIntConstant(m
, "IPV6_RECVTCLASS", IPV6_RECVTCLASS
);
5034 PyModule_AddIntConstant(m
, "IPV6_RTHDR", IPV6_RTHDR
);
5036 #ifdef IPV6_RTHDRDSTOPTS
5037 PyModule_AddIntConstant(m
, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS
);
5039 #ifdef IPV6_RTHDR_TYPE_0
5040 PyModule_AddIntConstant(m
, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0
);
5042 #ifdef IPV6_RECVPATHMTU
5043 PyModule_AddIntConstant(m
, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU
);
5046 PyModule_AddIntConstant(m
, "IPV6_TCLASS", IPV6_TCLASS
);
5048 #ifdef IPV6_USE_MIN_MTU
5049 PyModule_AddIntConstant(m
, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU
);
5054 PyModule_AddIntConstant(m
, "TCP_NODELAY", TCP_NODELAY
);
5057 PyModule_AddIntConstant(m
, "TCP_MAXSEG", TCP_MAXSEG
);
5060 PyModule_AddIntConstant(m
, "TCP_CORK", TCP_CORK
);
5063 PyModule_AddIntConstant(m
, "TCP_KEEPIDLE", TCP_KEEPIDLE
);
5065 #ifdef TCP_KEEPINTVL
5066 PyModule_AddIntConstant(m
, "TCP_KEEPINTVL", TCP_KEEPINTVL
);
5069 PyModule_AddIntConstant(m
, "TCP_KEEPCNT", TCP_KEEPCNT
);
5072 PyModule_AddIntConstant(m
, "TCP_SYNCNT", TCP_SYNCNT
);
5075 PyModule_AddIntConstant(m
, "TCP_LINGER2", TCP_LINGER2
);
5077 #ifdef TCP_DEFER_ACCEPT
5078 PyModule_AddIntConstant(m
, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT
);
5080 #ifdef TCP_WINDOW_CLAMP
5081 PyModule_AddIntConstant(m
, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP
);
5084 PyModule_AddIntConstant(m
, "TCP_INFO", TCP_INFO
);
5087 PyModule_AddIntConstant(m
, "TCP_QUICKACK", TCP_QUICKACK
);
5093 PyModule_AddIntConstant(m
, "IPX_TYPE", IPX_TYPE
);
5096 /* get{addr,name}info parameters */
5097 #ifdef EAI_ADDRFAMILY
5098 PyModule_AddIntConstant(m
, "EAI_ADDRFAMILY", EAI_ADDRFAMILY
);
5101 PyModule_AddIntConstant(m
, "EAI_AGAIN", EAI_AGAIN
);
5104 PyModule_AddIntConstant(m
, "EAI_BADFLAGS", EAI_BADFLAGS
);
5107 PyModule_AddIntConstant(m
, "EAI_FAIL", EAI_FAIL
);
5110 PyModule_AddIntConstant(m
, "EAI_FAMILY", EAI_FAMILY
);
5113 PyModule_AddIntConstant(m
, "EAI_MEMORY", EAI_MEMORY
);
5116 PyModule_AddIntConstant(m
, "EAI_NODATA", EAI_NODATA
);
5119 PyModule_AddIntConstant(m
, "EAI_NONAME", EAI_NONAME
);
5122 PyModule_AddIntConstant(m
, "EAI_OVERFLOW", EAI_OVERFLOW
);
5125 PyModule_AddIntConstant(m
, "EAI_SERVICE", EAI_SERVICE
);
5128 PyModule_AddIntConstant(m
, "EAI_SOCKTYPE", EAI_SOCKTYPE
);
5131 PyModule_AddIntConstant(m
, "EAI_SYSTEM", EAI_SYSTEM
);
5134 PyModule_AddIntConstant(m
, "EAI_BADHINTS", EAI_BADHINTS
);
5137 PyModule_AddIntConstant(m
, "EAI_PROTOCOL", EAI_PROTOCOL
);
5140 PyModule_AddIntConstant(m
, "EAI_MAX", EAI_MAX
);
5143 PyModule_AddIntConstant(m
, "AI_PASSIVE", AI_PASSIVE
);
5146 PyModule_AddIntConstant(m
, "AI_CANONNAME", AI_CANONNAME
);
5148 #ifdef AI_NUMERICHOST
5149 PyModule_AddIntConstant(m
, "AI_NUMERICHOST", AI_NUMERICHOST
);
5151 #ifdef AI_NUMERICSERV
5152 PyModule_AddIntConstant(m
, "AI_NUMERICSERV", AI_NUMERICSERV
);
5155 PyModule_AddIntConstant(m
, "AI_MASK", AI_MASK
);
5158 PyModule_AddIntConstant(m
, "AI_ALL", AI_ALL
);
5160 #ifdef AI_V4MAPPED_CFG
5161 PyModule_AddIntConstant(m
, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG
);
5163 #ifdef AI_ADDRCONFIG
5164 PyModule_AddIntConstant(m
, "AI_ADDRCONFIG", AI_ADDRCONFIG
);
5167 PyModule_AddIntConstant(m
, "AI_V4MAPPED", AI_V4MAPPED
);
5170 PyModule_AddIntConstant(m
, "AI_DEFAULT", AI_DEFAULT
);
5173 PyModule_AddIntConstant(m
, "NI_MAXHOST", NI_MAXHOST
);
5176 PyModule_AddIntConstant(m
, "NI_MAXSERV", NI_MAXSERV
);
5179 PyModule_AddIntConstant(m
, "NI_NOFQDN", NI_NOFQDN
);
5181 #ifdef NI_NUMERICHOST
5182 PyModule_AddIntConstant(m
, "NI_NUMERICHOST", NI_NUMERICHOST
);
5185 PyModule_AddIntConstant(m
, "NI_NAMEREQD", NI_NAMEREQD
);
5187 #ifdef NI_NUMERICSERV
5188 PyModule_AddIntConstant(m
, "NI_NUMERICSERV", NI_NUMERICSERV
);
5191 PyModule_AddIntConstant(m
, "NI_DGRAM", NI_DGRAM
);
5194 /* shutdown() parameters */
5196 PyModule_AddIntConstant(m
, "SHUT_RD", SHUT_RD
);
5197 #elif defined(SD_RECEIVE)
5198 PyModule_AddIntConstant(m
, "SHUT_RD", SD_RECEIVE
);
5200 PyModule_AddIntConstant(m
, "SHUT_RD", 0);
5203 PyModule_AddIntConstant(m
, "SHUT_WR", SHUT_WR
);
5204 #elif defined(SD_SEND)
5205 PyModule_AddIntConstant(m
, "SHUT_WR", SD_SEND
);
5207 PyModule_AddIntConstant(m
, "SHUT_WR", 1);
5210 PyModule_AddIntConstant(m
, "SHUT_RDWR", SHUT_RDWR
);
5211 #elif defined(SD_BOTH)
5212 PyModule_AddIntConstant(m
, "SHUT_RDWR", SD_BOTH
);
5214 PyModule_AddIntConstant(m
, "SHUT_RDWR", 2);
5218 tmp
= PyLong_FromUnsignedLong(SIO_RCVALL
);
5221 PyModule_AddObject(m
, "SIO_RCVALL", tmp
);
5222 PyModule_AddIntConstant(m
, "RCVALL_OFF", RCVALL_OFF
);
5223 PyModule_AddIntConstant(m
, "RCVALL_ON", RCVALL_ON
);
5224 PyModule_AddIntConstant(m
, "RCVALL_SOCKETLEVELONLY", RCVALL_SOCKETLEVELONLY
);
5225 PyModule_AddIntConstant(m
, "RCVALL_IPLEVEL", RCVALL_IPLEVEL
);
5226 PyModule_AddIntConstant(m
, "RCVALL_MAX", RCVALL_MAX
);
5227 #endif /* _MSTCPIP_ */
5229 /* Initialize gethostbyname lock */
5230 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
5231 netdb_lock
= PyThread_allocate_lock();
5236 #ifndef HAVE_INET_PTON
5237 #if !defined(NTDDI_VERSION) || (NTDDI_VERSION < NTDDI_LONGHORN)
5239 /* Simplistic emulation code for inet_pton that only works for IPv4 */
5240 /* These are not exposed because they do not set errno properly */
5243 inet_pton(int af
, const char *src
, void *dst
)
5245 if (af
== AF_INET
) {
5247 packed_addr
= inet_addr(src
);
5248 if (packed_addr
== INADDR_NONE
)
5250 memcpy(dst
, &packed_addr
, 4);
5253 /* Should set errno to EAFNOSUPPORT */
5258 inet_ntop(int af
, const void *src
, char *dst
, socklen_t size
)
5260 if (af
== AF_INET
) {
5261 struct in_addr packed_addr
;
5263 /* Should set errno to ENOSPC. */
5265 memcpy(&packed_addr
, src
, sizeof(packed_addr
));
5266 return strncpy(dst
, inet_ntoa(packed_addr
), size
);
5268 /* Should set errno to EAFNOSUPPORT */