5 This module provides an interface to Berkeley socket IPC.
9 - Only AF_INET, AF_INET6 and AF_UNIX address families are supported in a
10 portable manner, though AF_PACKET and AF_NETLINK are supported under Linux.
11 - No read/write operations (use sendall/recv or makefile instead).
12 - Additional restrictions apply on some non-Unix platforms (compensated
17 - socket.error: exception raised for socket specific errors
18 - socket.gaierror: exception raised for getaddrinfo/getnameinfo errors,
19 a subclass of socket.error
20 - socket.herror: exception raised for gethostby* errors,
21 a subclass of socket.error
22 - socket.fromfd(fd, family, type[, proto]) --> new socket object (created
23 from an existing file descriptor)
24 - socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')
25 - socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])
26 - socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com')
27 - socket.getprotobyname(protocolname) --> protocol number
28 - socket.getservbyname(servicename[, protocolname]) --> port number
29 - socket.getservbyport(portnumber[, protocolname]) --> service name
30 - socket.socket([family[, type [, proto]]]) --> new socket object
31 - socket.socketpair([family[, type [, proto]]]) --> (socket, socket)
32 - socket.ntohs(16 bit value) --> new int object
33 - socket.ntohl(32 bit value) --> new int object
34 - socket.htons(16 bit value) --> new int object
35 - socket.htonl(32 bit value) --> new int object
36 - socket.getaddrinfo(host, port [, family, socktype, proto, flags])
37 --> List of (family, socktype, proto, canonname, sockaddr)
38 - socket.getnameinfo(sockaddr, flags) --> (host, port)
39 - socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
40 - socket.has_ipv6: boolean value indicating if IPv6 is supported
41 - socket.inet_aton(IP address) -> 32-bit packed IP representation
42 - socket.inet_ntoa(packed IP) -> IP address string
43 - socket.getdefaulttimeout() -> None | float
44 - socket.setdefaulttimeout(None | float)
45 - an Internet socket address is a pair (hostname, port)
46 where hostname can be anything recognized by gethostbyname()
47 (including the dd.dd.dd.dd notation) and port is in host byte order
48 - where a hostname is returned, the dd.dd.dd.dd notation is used
49 - a UNIX domain socket address is a string specifying the pathname
50 - an AF_PACKET socket address is a tuple containing a string
51 specifying the ethernet interface and an integer specifying
52 the Ethernet protocol number to be received. For example:
53 ("eth0",0x1234). Optional 3rd,4th,5th elements in the tuple
54 specify packet-type and ha-type/addr.
56 Local naming conventions:
58 - names starting with sock_ are socket object methods
59 - names starting with socket_ are module-level functions
60 - names starting with PySocket are exported through socketmodule.h
66 * inet_aton is not available on OSX 10.3, yet we want to use a binary
67 * that was build on 10.4 or later to work on that release, weak linking
68 * comes to the rescue.
70 # pragma weak inet_aton
74 #include "structmember.h"
77 #define MAX(x, y) ((x) < (y) ? (y) : (x))
79 /* Socket object documentation */
80 PyDoc_STRVAR(sock_doc
,
81 "socket([family[, type[, proto]]]) -> socket object\n\
83 Open a socket of the given type. The family argument specifies the\n\
84 address family; it defaults to AF_INET. The type argument specifies\n\
85 whether this is a stream (SOCK_STREAM, this is the default)\n\
86 or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0,\n\
87 specifying the default protocol. Keyword arguments are accepted.\n\
89 A socket object represents one endpoint of a network connection.\n\
91 Methods of socket objects (keyword arguments not allowed):\n\
93 accept() -- accept a connection, returning new socket and client address\n\
94 bind(addr) -- bind the socket to a local address\n\
95 close() -- close the socket\n\
96 connect(addr) -- connect the socket to a remote address\n\
97 connect_ex(addr) -- connect, return an error code instead of an exception\n\
98 dup() -- return a new socket object identical to the current one [*]\n\
99 fileno() -- return underlying file descriptor\n\
100 getpeername() -- return remote address [*]\n\
101 getsockname() -- return local address\n\
102 getsockopt(level, optname[, buflen]) -- get socket options\n\
103 gettimeout() -- return timeout or None\n\
104 listen(n) -- start listening for incoming connections\n\
105 makefile([mode, [bufsize]]) -- return a file object for the socket [*]\n\
106 recv(buflen[, flags]) -- receive data\n\
107 recv_into(buffer[, nbytes[, flags]]) -- receive data (into a buffer)\n\
108 recvfrom(buflen[, flags]) -- receive data and sender\'s address\n\
109 recvfrom_into(buffer[, nbytes, [, flags])\n\
110 -- receive data and sender\'s address (into a buffer)\n\
111 sendall(data[, flags]) -- send all data\n\
112 send(data[, flags]) -- send data, may not send all of it\n\
113 sendto(data[, flags], addr) -- send data to a given address\n\
114 setblocking(0 | 1) -- set or clear the blocking I/O flag\n\
115 setsockopt(level, optname, value) -- set socket options\n\
116 settimeout(None | float) -- set or clear the timeout\n\
117 shutdown(how) -- shut down traffic in one or both directions\n\
119 [*] not available on all platforms!");
121 /* XXX This is a terrible mess of platform-dependent preprocessor hacks.
122 I hope some day someone can clean this up please... */
124 /* Hacks for gethostbyname_r(). On some non-Linux platforms, the configure
125 script doesn't get this right, so we hardcode some platform checks below.
126 On the other hand, not all Linux versions agree, so there the settings
127 computed by the configure script are needed! */
130 # undef HAVE_GETHOSTBYNAME_R_3_ARG
131 # undef HAVE_GETHOSTBYNAME_R_5_ARG
132 # undef HAVE_GETHOSTBYNAME_R_6_ARG
136 # undef HAVE_GETHOSTBYNAME_R
139 #ifdef HAVE_GETHOSTBYNAME_R
140 # if defined(_AIX) || defined(__osf__)
141 # define HAVE_GETHOSTBYNAME_R_3_ARG
142 # elif defined(__sun) || defined(__sgi)
143 # define HAVE_GETHOSTBYNAME_R_5_ARG
144 # elif defined(linux)
145 /* Rely on the configure script */
147 # undef HAVE_GETHOSTBYNAME_R
151 #if !defined(HAVE_GETHOSTBYNAME_R) && defined(WITH_THREAD) && \
153 # define USE_GETHOSTBYNAME_LOCK
156 /* To use __FreeBSD_version */
157 #ifdef HAVE_SYS_PARAM_H
158 #include <sys/param.h>
160 /* On systems on which getaddrinfo() is believed to not be thread-safe,
161 (this includes the getaddrinfo emulation) protect access with a lock. */
162 #if defined(WITH_THREAD) && (defined(__APPLE__) || \
163 (defined(__FreeBSD__) && __FreeBSD_version+0 < 503000) || \
164 defined(__OpenBSD__) || defined(__NetBSD__) || \
165 defined(__VMS) || !defined(HAVE_GETADDRINFO))
166 #define USE_GETADDRINFO_LOCK
169 #ifdef USE_GETADDRINFO_LOCK
170 #define ACQUIRE_GETADDRINFO_LOCK PyThread_acquire_lock(netdb_lock, 1);
171 #define RELEASE_GETADDRINFO_LOCK PyThread_release_lock(netdb_lock);
173 #define ACQUIRE_GETADDRINFO_LOCK
174 #define RELEASE_GETADDRINFO_LOCK
177 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
178 # include "pythread.h"
181 #if defined(PYCC_VACPP)
184 # include <sys/ioctl.h>
193 #if defined(PYOS_OS2)
195 # define INCL_DOSERRORS
196 # define INCL_NOPMAPI
200 #if defined(__sgi) && _COMPILER_VERSION>700 && !_SGIAPI
201 /* make sure that the reentrant (gethostbyaddr_r etc)
202 functions are declared correctly if compiling with
203 MIPSPro 7.x in ANSI C mode (default) */
205 /* XXX Using _SGIAPI is the wrong thing,
206 but I don't know what the right thing is. */
207 #undef _SGIAPI /* to avoid warning */
211 #include <sys/socket.h>
212 #include <sys/types.h>
213 #include <netinet/in.h>
215 #define HAVE_GETADDRINFO 1
216 #define HAVE_GETNAMEINFO 1
219 #define HAVE_INET_PTON
223 /* Irix 6.5 fails to define this variable at all. This is needed
224 for both GCC and SGI's compiler. I'd say that the SGI headers
225 are just busted. Same thing for Solaris. */
226 #if (defined(__sgi) || defined(sun)) && !defined(INET_ADDRSTRLEN)
227 #define INET_ADDRSTRLEN 16
230 /* Generic includes */
231 #ifdef HAVE_SYS_TYPES_H
232 #include <sys/types.h>
235 /* Generic socket object definitions and includes */
236 #define PySocket_BUILDING_SOCKET
237 #include "socketmodule.h"
239 /* Addressing includes */
243 /* Non-MS WINDOWS includes */
246 /* Headers needed for inet_ntoa() and inet_addr() */
248 # include <net/netdb.h>
249 # elif defined(PYOS_OS2) && defined(PYCC_VACPP)
251 typedef size_t socklen_t
;
253 # include <arpa/inet.h>
259 # include <sys/ioctl.h>
260 # include <socklib.h>
262 int h_errno
; /* not used */
263 # define INET_ADDRSTRLEN 16
268 /* MS_WINDOWS includes */
278 # define offsetof(type, member) ((size_t)(&((type *)0)->member))
282 # define O_NONBLOCK O_NDELAY
285 /* include Python's addrinfo.h unless it causes trouble */
286 #if defined(__sgi) && _COMPILER_VERSION>700 && defined(_SS_ALIGNSIZE)
287 /* Do not include addinfo.h on some newer IRIX versions.
288 * _SS_ALIGNSIZE is defined in sys/socket.h by 6.5.21,
289 * for example, but not by 6.5.10.
291 #elif defined(_MSC_VER) && _MSC_VER>1201
292 /* Do not include addrinfo.h for MSVC7 or greater. 'addrinfo' and
293 * EAI_* constants are defined in (the already included) ws2tcpip.h.
296 # include "addrinfo.h"
299 #ifndef HAVE_INET_PTON
300 int inet_pton(int af
, const char *src
, void *dst
);
301 const char *inet_ntop(int af
, const void *src
, char *dst
, socklen_t size
);
305 /* On OS X, getaddrinfo returns no error indication of lookup
306 failure, so we must use the emulation instead of the libinfo
307 implementation. Unfortunately, performing an autoconf test
308 for this bug would require DNS access for the machine performing
309 the configuration, which is not acceptable. Therefore, we
310 determine the bug just by checking for __APPLE__. If this bug
311 gets ever fixed, perhaps checking for sys/version.h would be
312 appropriate, which is 10/0 on the system with the bug. */
313 #ifndef HAVE_GETNAMEINFO
314 /* This bug seems to be fixed in Jaguar. Ths easiest way I could
315 Find to check for Jaguar is that it has getnameinfo(), which
316 older releases don't have */
317 #undef HAVE_GETADDRINFO
320 #ifdef HAVE_INET_ATON
321 #define USE_INET_ATON_WEAKLINK
326 /* I know this is a bad practice, but it is the easiest... */
327 #if !defined(HAVE_GETADDRINFO)
328 /* avoid clashes with the C library definition of the symbol. */
329 #define getaddrinfo fake_getaddrinfo
330 #define gai_strerror fake_gai_strerror
331 #define freeaddrinfo fake_freeaddrinfo
332 #include "getaddrinfo.c"
334 #if !defined(HAVE_GETNAMEINFO)
335 #define getnameinfo fake_getnameinfo
336 #include "getnameinfo.c"
339 #if defined(MS_WINDOWS) || defined(__BEOS__)
340 /* BeOS suffers from the same socket dichotomy as Win32... - [cjh] */
341 /* seem to be a few differences in the API */
342 #define SOCKETCLOSE closesocket
343 #define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */
347 #define EAFNOSUPPORT WSAEAFNOSUPPORT
348 #define snprintf _snprintf
351 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
352 #define SOCKETCLOSE soclose
353 #define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
357 #define SOCKETCLOSE close
360 #if defined(HAVE_BLUETOOTH_H) || defined(HAVE_BLUETOOTH_BLUETOOTH_H)
361 #define USE_BLUETOOTH 1
362 #if defined(__FreeBSD__)
363 #define BTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP
364 #define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM
365 #define sockaddr_l2 sockaddr_l2cap
366 #define sockaddr_rc sockaddr_rfcomm
367 #define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb)
368 #define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)
369 #elif defined(__NetBSD__)
370 #define sockaddr_l2 sockaddr_bt
371 #define sockaddr_rc sockaddr_bt
372 #define sockaddr_sco sockaddr_bt
373 #define _BT_L2_MEMB(sa, memb) ((sa)->bt_##memb)
374 #define _BT_RC_MEMB(sa, memb) ((sa)->bt_##memb)
375 #define _BT_SCO_MEMB(sa, memb) ((sa)->bt_##memb)
377 #define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb)
378 #define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb)
379 #define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)
384 /* TCP/IP Services for VMS uses a maximum send/recv buffer length */
385 #define SEGMENT_SIZE (32 * 1024 -1)
388 #define SAS2SA(x) ((struct sockaddr *)(x))
391 * Constants for getnameinfo()
393 #if !defined(NI_MAXHOST)
394 #define NI_MAXHOST 1025
396 #if !defined(NI_MAXSERV)
397 #define NI_MAXSERV 32
400 /* XXX There's a problem here: *static* functions are not supposed to have
401 a Py prefix (or use CapitalizedWords). Later... */
403 /* Global variable holding the exception type for errors detected
404 by this module (but not argument type or memory errors, etc.). */
405 static PyObject
*socket_error
;
406 static PyObject
*socket_herror
;
407 static PyObject
*socket_gaierror
;
408 static PyObject
*socket_timeout
;
411 /* Global variable which is !=0 if Python is running in a RISC OS taskwindow */
412 static int taskwindow
;
415 /* A forward reference to the socket type object.
416 The sock_type variable contains pointers to various functions,
417 some of which call new_sockobject(), which uses sock_type, so
418 there has to be a circular reference. */
419 static PyTypeObject sock_type
;
421 #if defined(HAVE_POLL_H)
423 #elif defined(HAVE_SYS_POLL_H)
424 #include <sys/poll.h>
427 #ifdef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
428 /* Platform can select file descriptors beyond FD_SETSIZE */
429 #define IS_SELECTABLE(s) 1
430 #elif defined(HAVE_POLL)
431 /* Instead of select(), we'll use poll() since poll() works on any fd. */
432 #define IS_SELECTABLE(s) 1
433 /* Can we call select() with this socket without a buffer overrun? */
435 /* POSIX says selecting file descriptors beyond FD_SETSIZE
436 has undefined behaviour. If there's no timeout left, we don't have to
437 call select, so it's a safe, little white lie. */
438 #define IS_SELECTABLE(s) ((s)->sock_fd < FD_SETSIZE || s->sock_timeout <= 0.0)
444 PyErr_SetString(socket_error
, "unable to select on socket");
448 /* Convenience function to raise an error according to errno
449 and return a NULL pointer from a function. */
455 int err_no
= WSAGetLastError();
460 {WSAEINTR
, "Interrupted system call"},
461 {WSAEBADF
, "Bad file descriptor"},
462 {WSAEACCES
, "Permission denied"},
463 {WSAEFAULT
, "Bad address"},
464 {WSAEINVAL
, "Invalid argument"},
465 {WSAEMFILE
, "Too many open files"},
467 "The socket operation could not complete "
469 {WSAEINPROGRESS
, "Operation now in progress"},
470 {WSAEALREADY
, "Operation already in progress"},
471 {WSAENOTSOCK
, "Socket operation on non-socket"},
472 {WSAEDESTADDRREQ
, "Destination address required"},
473 {WSAEMSGSIZE
, "Message too long"},
474 {WSAEPROTOTYPE
, "Protocol wrong type for socket"},
475 {WSAENOPROTOOPT
, "Protocol not available"},
476 {WSAEPROTONOSUPPORT
, "Protocol not supported"},
477 {WSAESOCKTNOSUPPORT
, "Socket type not supported"},
478 {WSAEOPNOTSUPP
, "Operation not supported"},
479 {WSAEPFNOSUPPORT
, "Protocol family not supported"},
480 {WSAEAFNOSUPPORT
, "Address family not supported"},
481 {WSAEADDRINUSE
, "Address already in use"},
482 {WSAEADDRNOTAVAIL
, "Can't assign requested address"},
483 {WSAENETDOWN
, "Network is down"},
484 {WSAENETUNREACH
, "Network is unreachable"},
485 {WSAENETRESET
, "Network dropped connection on reset"},
486 {WSAECONNABORTED
, "Software caused connection abort"},
487 {WSAECONNRESET
, "Connection reset by peer"},
488 {WSAENOBUFS
, "No buffer space available"},
489 {WSAEISCONN
, "Socket is already connected"},
490 {WSAENOTCONN
, "Socket is not connected"},
491 {WSAESHUTDOWN
, "Can't send after socket shutdown"},
492 {WSAETOOMANYREFS
, "Too many references: can't splice"},
493 {WSAETIMEDOUT
, "Operation timed out"},
494 {WSAECONNREFUSED
, "Connection refused"},
495 {WSAELOOP
, "Too many levels of symbolic links"},
496 {WSAENAMETOOLONG
, "File name too long"},
497 {WSAEHOSTDOWN
, "Host is down"},
498 {WSAEHOSTUNREACH
, "No route to host"},
499 {WSAENOTEMPTY
, "Directory not empty"},
500 {WSAEPROCLIM
, "Too many processes"},
501 {WSAEUSERS
, "Too many users"},
502 {WSAEDQUOT
, "Disc quota exceeded"},
503 {WSAESTALE
, "Stale NFS file handle"},
504 {WSAEREMOTE
, "Too many levels of remote in path"},
505 {WSASYSNOTREADY
, "Network subsystem is unvailable"},
506 {WSAVERNOTSUPPORTED
, "WinSock version is not supported"},
508 "Successful WSAStartup() not yet performed"},
509 {WSAEDISCON
, "Graceful shutdown in progress"},
510 /* Resolver errors */
511 {WSAHOST_NOT_FOUND
, "No such host is known"},
512 {WSATRY_AGAIN
, "Host not found, or server failed"},
513 {WSANO_RECOVERY
, "Unexpected server error encountered"},
514 {WSANO_DATA
, "Valid name without requested data"},
515 {WSANO_ADDRESS
, "No address, look for MX record"},
520 const char *msg
= "winsock error";
522 for (msgp
= msgs
; msgp
->msg
; msgp
++) {
523 if (err_no
== msgp
->no
) {
529 v
= Py_BuildValue("(is)", err_no
, msg
);
531 PyErr_SetObject(socket_error
, v
);
539 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
540 if (sock_errno() != NO_ERROR
) {
544 int myerrorcode
= sock_errno();
546 /* Retrieve socket-related error message from MPTN.MSG file */
547 rc
= DosGetMessage(NULL
, 0, outbuf
, sizeof(outbuf
),
548 myerrorcode
- SOCBASEERR
+ 26,
551 if (rc
== NO_ERROR
) {
554 /* OS/2 doesn't guarantee a terminator */
555 outbuf
[msglen
] = '\0';
556 if (strlen(outbuf
) > 0) {
557 /* If non-empty msg, trim CRLF */
558 char *lastc
= &outbuf
[ strlen(outbuf
)-1 ];
559 while (lastc
> outbuf
&&
560 isspace(Py_CHARMASK(*lastc
))) {
561 /* Trim trailing whitespace (CRLF) */
565 v
= Py_BuildValue("(is)", myerrorcode
, outbuf
);
567 PyErr_SetObject(socket_error
, v
);
576 if (_inet_error
.errnum
!= NULL
) {
578 v
= Py_BuildValue("(is)", errno
, _inet_err());
580 PyErr_SetObject(socket_error
, v
);
587 return PyErr_SetFromErrno(socket_error
);
592 set_herror(int h_error
)
596 #ifdef HAVE_HSTRERROR
597 v
= Py_BuildValue("(is)", h_error
, (char *)hstrerror(h_error
));
599 v
= Py_BuildValue("(is)", h_error
, "host not found");
602 PyErr_SetObject(socket_herror
, v
);
611 set_gaierror(int error
)
616 /* EAI_SYSTEM is not available on Windows XP. */
617 if (error
== EAI_SYSTEM
)
621 #ifdef HAVE_GAI_STRERROR
622 v
= Py_BuildValue("(is)", error
, gai_strerror(error
));
624 v
= Py_BuildValue("(is)", error
, "getaddrinfo failed");
627 PyErr_SetObject(socket_gaierror
, v
);
635 /* Function to send in segments */
637 sendsegmented(int sock_fd
, char *buf
, int len
, int flags
)
642 while (remaining
> 0) {
643 unsigned int segment
;
645 segment
= (remaining
>= SEGMENT_SIZE
? SEGMENT_SIZE
: remaining
);
646 n
= send(sock_fd
, buf
, segment
, flags
);
650 remaining
-= segment
;
658 /* Function to perform the setting of socket blocking mode
659 internally. block = (1 | 0). */
661 internal_setblocking(PySocketSockObject
*s
, int block
)
669 Py_BEGIN_ALLOW_THREADS
672 setsockopt(s
->sock_fd
, SOL_SOCKET
, SO_NONBLOCK
,
673 (void *)(&block
), sizeof(int));
677 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
679 ioctl(s
->sock_fd
, FIONBIO
, (caddr_t
)&block
, sizeof(block
));
682 ioctl(s
->sock_fd
, FIONBIO
, (unsigned int *)&block
);
683 #else /* !PYOS_OS2 && !__VMS */
684 delay_flag
= fcntl(s
->sock_fd
, F_GETFL
, 0);
686 delay_flag
&= (~O_NONBLOCK
);
688 delay_flag
|= O_NONBLOCK
;
689 fcntl(s
->sock_fd
, F_SETFL
, delay_flag
);
690 #endif /* !PYOS_OS2 */
691 #else /* MS_WINDOWS */
693 ioctlsocket(s
->sock_fd
, FIONBIO
, (u_long
*)&block
);
694 #endif /* MS_WINDOWS */
697 socketioctl(s
->sock_fd
, FIONBIO
, (u_long
*)&block
);
699 #endif /* __BEOS__ */
702 /* Since these don't return anything */
706 /* Do a select()/poll() on the socket, if necessary (sock_timeout > 0).
707 The argument writing indicates the direction.
708 This does not raise an exception; we'll let our caller do that
709 after they've reacquired the interpreter lock.
710 Returns 1 on timeout, -1 on error, 0 otherwise. */
712 internal_select(PySocketSockObject
*s
, int writing
)
716 /* Nothing to do unless we're in timeout mode (not non-blocking) */
717 if (s
->sock_timeout
<= 0.0)
720 /* Guard against closed socket */
724 /* Prefer poll, if available, since you can poll() any fd
725 * which can't be done with select(). */
728 struct pollfd pollfd
;
731 pollfd
.fd
= s
->sock_fd
;
732 pollfd
.events
= writing
? POLLOUT
: POLLIN
;
734 /* s->sock_timeout is in seconds, timeout in ms */
735 timeout
= (int)(s
->sock_timeout
* 1000 + 0.5);
736 n
= poll(&pollfd
, 1, timeout
);
740 /* Construct the arguments to select */
743 tv
.tv_sec
= (int)s
->sock_timeout
;
744 tv
.tv_usec
= (int)((s
->sock_timeout
- tv
.tv_sec
) * 1e6
);
746 FD_SET(s
->sock_fd
, &fds
);
748 /* See if the socket is ready */
750 n
= select(s
->sock_fd
+1, NULL
, &fds
, NULL
, &tv
);
752 n
= select(s
->sock_fd
+1, &fds
, NULL
, NULL
, &tv
);
763 /* Initialize a new socket object. */
765 static double defaulttimeout
= -1.0; /* Default timeout for new sockets */
768 init_sockobject(PySocketSockObject
*s
,
769 SOCKET_T fd
, int family
, int type
, int proto
)
775 s
->sock_family
= family
;
777 s
->sock_proto
= proto
;
778 s
->sock_timeout
= defaulttimeout
;
780 s
->errorhandler
= &set_error
;
782 if (defaulttimeout
>= 0.0)
783 internal_setblocking(s
, 0);
787 socketioctl(s
->sock_fd
, 0x80046679, (u_long
*)&block
);
792 /* Create a new socket object.
793 This just creates the object and initializes it.
794 If the creation fails, return NULL and set an exception (implicit
797 static PySocketSockObject
*
798 new_sockobject(SOCKET_T fd
, int family
, int type
, int proto
)
800 PySocketSockObject
*s
;
801 s
= (PySocketSockObject
*)
802 PyType_GenericNew(&sock_type
, NULL
, NULL
);
804 init_sockobject(s
, fd
, family
, type
, proto
);
809 /* Lock to allow python interpreter to continue, but only allow one
810 thread to be in gethostbyname or getaddrinfo */
811 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
812 PyThread_type_lock netdb_lock
;
816 /* Convert a string specifying a host name or one of a few symbolic
817 names to a numeric IP address. This usually calls gethostbyname()
818 to do the work; the names "" and "<broadcast>" are special.
819 Return the length (IPv4 should be 4 bytes), or negative if
820 an error occurred; then an exception is raised. */
823 setipaddr(char *name
, struct sockaddr
*addr_ret
, size_t addr_ret_size
, int af
)
825 struct addrinfo hints
, *res
;
830 memset((void *) addr_ret
, '\0', sizeof(*addr_ret
));
831 if (name
[0] == '\0') {
833 memset(&hints
, 0, sizeof(hints
));
834 hints
.ai_family
= af
;
835 hints
.ai_socktype
= SOCK_DGRAM
; /*dummy*/
836 hints
.ai_flags
= AI_PASSIVE
;
837 Py_BEGIN_ALLOW_THREADS
838 ACQUIRE_GETADDRINFO_LOCK
839 error
= getaddrinfo(NULL
, "0", &hints
, &res
);
841 /* We assume that those thread-unsafe getaddrinfo() versions
842 *are* safe regarding their return value, ie. that a
843 subsequent call to getaddrinfo() does not destroy the
844 outcome of the first call. */
845 RELEASE_GETADDRINFO_LOCK
850 switch (res
->ai_family
) {
861 PyErr_SetString(socket_error
,
862 "unsupported address family");
867 PyErr_SetString(socket_error
,
868 "wildcard resolved to multiple address");
871 if (res
->ai_addrlen
< addr_ret_size
)
872 addr_ret_size
= res
->ai_addrlen
;
873 memcpy(addr_ret
, res
->ai_addr
, addr_ret_size
);
877 if (name
[0] == '<' && strcmp(name
, "<broadcast>") == 0) {
878 struct sockaddr_in
*sin
;
879 if (af
!= AF_INET
&& af
!= AF_UNSPEC
) {
880 PyErr_SetString(socket_error
,
881 "address family mismatched");
884 sin
= (struct sockaddr_in
*)addr_ret
;
885 memset((void *) sin
, '\0', sizeof(*sin
));
886 sin
->sin_family
= AF_INET
;
887 #ifdef HAVE_SOCKADDR_SA_LEN
888 sin
->sin_len
= sizeof(*sin
);
890 sin
->sin_addr
.s_addr
= INADDR_BROADCAST
;
891 return sizeof(sin
->sin_addr
);
893 if (sscanf(name
, "%d.%d.%d.%d%c", &d1
, &d2
, &d3
, &d4
, &ch
) == 4 &&
894 0 <= d1
&& d1
<= 255 && 0 <= d2
&& d2
<= 255 &&
895 0 <= d3
&& d3
<= 255 && 0 <= d4
&& d4
<= 255) {
896 struct sockaddr_in
*sin
;
897 sin
= (struct sockaddr_in
*)addr_ret
;
898 sin
->sin_addr
.s_addr
= htonl(
899 ((long) d1
<< 24) | ((long) d2
<< 16) |
900 ((long) d3
<< 8) | ((long) d4
<< 0));
901 sin
->sin_family
= AF_INET
;
902 #ifdef HAVE_SOCKADDR_SA_LEN
903 sin
->sin_len
= sizeof(*sin
);
907 memset(&hints
, 0, sizeof(hints
));
908 hints
.ai_family
= af
;
909 Py_BEGIN_ALLOW_THREADS
910 ACQUIRE_GETADDRINFO_LOCK
911 error
= getaddrinfo(name
, NULL
, &hints
, &res
);
912 #if defined(__digital__) && defined(__unix__)
913 if (error
== EAI_NONAME
&& af
== AF_UNSPEC
) {
914 /* On Tru64 V5.1, numeric-to-addr conversion fails
915 if no address family is given. Assume IPv4 for now.*/
916 hints
.ai_family
= AF_INET
;
917 error
= getaddrinfo(name
, NULL
, &hints
, &res
);
921 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
926 if (res
->ai_addrlen
< addr_ret_size
)
927 addr_ret_size
= res
->ai_addrlen
;
928 memcpy((char *) addr_ret
, res
->ai_addr
, addr_ret_size
);
930 switch (addr_ret
->sa_family
) {
938 PyErr_SetString(socket_error
, "unknown address family");
944 /* Create a string object representing an IP address.
945 This is always a string of the form 'dd.dd.dd.dd' (with variable
949 makeipaddr(struct sockaddr
*addr
, int addrlen
)
951 char buf
[NI_MAXHOST
];
954 error
= getnameinfo(addr
, addrlen
, buf
, sizeof(buf
), NULL
, 0,
960 return PyString_FromString(buf
);
965 /* Convert a string representation of a Bluetooth address into a numeric
966 address. Returns the length (6), or raises an exception and returns -1 if
967 an error occurred. */
970 setbdaddr(char *name
, bdaddr_t
*bdaddr
)
972 unsigned int b0
, b1
, b2
, b3
, b4
, b5
;
976 n
= sscanf(name
, "%X:%X:%X:%X:%X:%X%c",
977 &b5
, &b4
, &b3
, &b2
, &b1
, &b0
, &ch
);
978 if (n
== 6 && (b0
| b1
| b2
| b3
| b4
| b5
) < 256) {
987 PyErr_SetString(socket_error
, "bad bluetooth address");
992 /* Create a string representation of the Bluetooth address. This is always a
993 string of the form 'XX:XX:XX:XX:XX:XX' where XX is a two digit hexadecimal
994 value (zero padded if necessary). */
997 makebdaddr(bdaddr_t
*bdaddr
)
999 char buf
[(6 * 2) + 5 + 1];
1001 sprintf(buf
, "%02X:%02X:%02X:%02X:%02X:%02X",
1002 bdaddr
->b
[5], bdaddr
->b
[4], bdaddr
->b
[3],
1003 bdaddr
->b
[2], bdaddr
->b
[1], bdaddr
->b
[0]);
1004 return PyString_FromString(buf
);
1009 /* Create an object representing the given socket address,
1010 suitable for passing it back to bind(), connect() etc.
1011 The family field of the sockaddr structure is inspected
1012 to determine what kind of address it really is. */
1016 makesockaddr(int sockfd
, struct sockaddr
*addr
, int addrlen
, int proto
)
1019 /* No address -- may be recvfrom() from known socket */
1025 /* XXX: BeOS version of accept() doesn't set family correctly */
1026 addr
->sa_family
= AF_INET
;
1029 switch (addr
->sa_family
) {
1033 struct sockaddr_in
*a
;
1034 PyObject
*addrobj
= makeipaddr(addr
, sizeof(*a
));
1035 PyObject
*ret
= NULL
;
1037 a
= (struct sockaddr_in
*)addr
;
1038 ret
= Py_BuildValue("Oi", addrobj
, ntohs(a
->sin_port
));
1044 #if defined(AF_UNIX)
1047 struct sockaddr_un
*a
= (struct sockaddr_un
*) addr
;
1049 if (a
->sun_path
[0] == 0) { /* Linux abstract namespace */
1050 addrlen
-= (sizeof(*a
) - sizeof(a
->sun_path
));
1051 return PyString_FromStringAndSize(a
->sun_path
,
1057 /* regular NULL-terminated string */
1058 return PyString_FromString(a
->sun_path
);
1061 #endif /* AF_UNIX */
1063 #if defined(AF_NETLINK)
1066 struct sockaddr_nl
*a
= (struct sockaddr_nl
*) addr
;
1067 return Py_BuildValue("II", a
->nl_pid
, a
->nl_groups
);
1069 #endif /* AF_NETLINK */
1074 struct sockaddr_in6
*a
;
1075 PyObject
*addrobj
= makeipaddr(addr
, sizeof(*a
));
1076 PyObject
*ret
= NULL
;
1078 a
= (struct sockaddr_in6
*)addr
;
1079 ret
= Py_BuildValue("Oiii",
1081 ntohs(a
->sin6_port
),
1090 #ifdef USE_BLUETOOTH
1096 struct sockaddr_l2
*a
= (struct sockaddr_l2
*) addr
;
1097 PyObject
*addrobj
= makebdaddr(&_BT_L2_MEMB(a
, bdaddr
));
1098 PyObject
*ret
= NULL
;
1100 ret
= Py_BuildValue("Oi",
1102 _BT_L2_MEMB(a
, psm
));
1108 case BTPROTO_RFCOMM
:
1110 struct sockaddr_rc
*a
= (struct sockaddr_rc
*) addr
;
1111 PyObject
*addrobj
= makebdaddr(&_BT_RC_MEMB(a
, bdaddr
));
1112 PyObject
*ret
= NULL
;
1114 ret
= Py_BuildValue("Oi",
1116 _BT_RC_MEMB(a
, channel
));
1122 #if !defined(__FreeBSD__)
1125 struct sockaddr_sco
*a
= (struct sockaddr_sco
*) addr
;
1126 return makebdaddr(&_BT_SCO_MEMB(a
, bdaddr
));
1133 #ifdef HAVE_NETPACKET_PACKET_H
1136 struct sockaddr_ll
*a
= (struct sockaddr_ll
*)addr
;
1139 /* need to look up interface name give index */
1140 if (a
->sll_ifindex
) {
1141 ifr
.ifr_ifindex
= a
->sll_ifindex
;
1142 if (ioctl(sockfd
, SIOCGIFNAME
, &ifr
) == 0)
1143 ifname
= ifr
.ifr_name
;
1145 return Py_BuildValue("shbhs#",
1147 ntohs(a
->sll_protocol
),
1155 /* More cases here... */
1158 /* If we don't know the address family, don't raise an
1159 exception -- return it as a tuple. */
1160 return Py_BuildValue("is#",
1163 sizeof(addr
->sa_data
));
1169 /* Parse a socket address argument according to the socket object's
1170 address family. Return 1 if the address was in the proper format,
1171 0 of not. The address is returned through addr_ret, its length
1175 getsockaddrarg(PySocketSockObject
*s
, PyObject
*args
,
1176 struct sockaddr
*addr_ret
, int *len_ret
)
1178 switch (s
->sock_family
) {
1180 #if defined(AF_UNIX)
1183 struct sockaddr_un
* addr
;
1186 if (!PyArg_Parse(args
, "t#", &path
, &len
))
1189 addr
= (struct sockaddr_un
*)addr_ret
;
1191 if (len
> 0 && path
[0] == 0) {
1192 /* Linux abstract namespace extension */
1193 if (len
> sizeof addr
->sun_path
) {
1194 PyErr_SetString(socket_error
,
1195 "AF_UNIX path too long");
1202 /* regular NULL-terminated string */
1203 if (len
>= sizeof addr
->sun_path
) {
1204 PyErr_SetString(socket_error
,
1205 "AF_UNIX path too long");
1208 addr
->sun_path
[len
] = 0;
1210 addr
->sun_family
= s
->sock_family
;
1211 memcpy(addr
->sun_path
, path
, len
);
1212 #if defined(PYOS_OS2)
1213 *len_ret
= sizeof(*addr
);
1215 *len_ret
= len
+ sizeof(*addr
) - sizeof(addr
->sun_path
);
1219 #endif /* AF_UNIX */
1221 #if defined(AF_NETLINK)
1224 struct sockaddr_nl
* addr
;
1226 addr
= (struct sockaddr_nl
*)addr_ret
;
1227 if (!PyTuple_Check(args
)) {
1231 "AF_NETLINK address must be tuple, not %.500s",
1232 args
->ob_type
->tp_name
);
1235 if (!PyArg_ParseTuple(args
, "II:getsockaddrarg", &pid
, &groups
))
1237 addr
->nl_family
= AF_NETLINK
;
1239 addr
->nl_groups
= groups
;
1240 *len_ret
= sizeof(*addr
);
1247 struct sockaddr_in
* addr
;
1250 if (!PyTuple_Check(args
)) {
1254 "AF_INET address must be tuple, not %.500s",
1255 args
->ob_type
->tp_name
);
1258 if (!PyArg_ParseTuple(args
, "eti:getsockaddrarg",
1259 "idna", &host
, &port
))
1261 addr
=(struct sockaddr_in
*)addr_ret
;
1262 result
= setipaddr(host
, (struct sockaddr
*)addr
,
1263 sizeof(*addr
), AF_INET
);
1267 addr
->sin_family
= AF_INET
;
1268 addr
->sin_port
= htons((short)port
);
1269 *len_ret
= sizeof *addr
;
1276 struct sockaddr_in6
* addr
;
1278 int port
, flowinfo
, scope_id
, result
;
1279 flowinfo
= scope_id
= 0;
1280 if (!PyTuple_Check(args
)) {
1284 "AF_INET6 address must be tuple, not %.500s",
1285 args
->ob_type
->tp_name
);
1288 if (!PyArg_ParseTuple(args
, "eti|ii",
1289 "idna", &host
, &port
, &flowinfo
,
1293 addr
= (struct sockaddr_in6
*)addr_ret
;
1294 result
= setipaddr(host
, (struct sockaddr
*)addr
,
1295 sizeof(*addr
), AF_INET6
);
1299 addr
->sin6_family
= s
->sock_family
;
1300 addr
->sin6_port
= htons((short)port
);
1301 addr
->sin6_flowinfo
= flowinfo
;
1302 addr
->sin6_scope_id
= scope_id
;
1303 *len_ret
= sizeof *addr
;
1308 #ifdef USE_BLUETOOTH
1311 switch (s
->sock_proto
) {
1314 struct sockaddr_l2
*addr
;
1317 addr
= (struct sockaddr_l2
*)addr_ret
;
1318 _BT_L2_MEMB(addr
, family
) = AF_BLUETOOTH
;
1319 if (!PyArg_ParseTuple(args
, "si", &straddr
,
1320 &_BT_L2_MEMB(addr
, psm
))) {
1321 PyErr_SetString(socket_error
, "getsockaddrarg: "
1325 if (setbdaddr(straddr
, &_BT_L2_MEMB(addr
, bdaddr
)) < 0)
1328 *len_ret
= sizeof *addr
;
1331 case BTPROTO_RFCOMM
:
1333 struct sockaddr_rc
*addr
;
1336 addr
= (struct sockaddr_rc
*)addr_ret
;
1337 _BT_RC_MEMB(addr
, family
) = AF_BLUETOOTH
;
1338 if (!PyArg_ParseTuple(args
, "si", &straddr
,
1339 &_BT_RC_MEMB(addr
, channel
))) {
1340 PyErr_SetString(socket_error
, "getsockaddrarg: "
1344 if (setbdaddr(straddr
, &_BT_RC_MEMB(addr
, bdaddr
)) < 0)
1347 *len_ret
= sizeof *addr
;
1350 #if !defined(__FreeBSD__)
1353 struct sockaddr_sco
*addr
;
1356 addr
= (struct sockaddr_sco
*)addr_ret
;
1357 _BT_SCO_MEMB(addr
, family
) = AF_BLUETOOTH
;
1358 straddr
= PyString_AsString(args
);
1359 if (straddr
== NULL
) {
1360 PyErr_SetString(socket_error
, "getsockaddrarg: "
1364 if (setbdaddr(straddr
, &_BT_SCO_MEMB(addr
, bdaddr
)) < 0)
1367 *len_ret
= sizeof *addr
;
1372 PyErr_SetString(socket_error
, "getsockaddrarg: unknown Bluetooth protocol");
1378 #ifdef HAVE_NETPACKET_PACKET_H
1381 struct sockaddr_ll
* addr
;
1383 char *interfaceName
;
1388 unsigned int halen
= 0;
1390 if (!PyTuple_Check(args
)) {
1394 "AF_PACKET address must be tuple, not %.500s",
1395 args
->ob_type
->tp_name
);
1398 if (!PyArg_ParseTuple(args
, "si|iis#", &interfaceName
,
1399 &protoNumber
, &pkttype
, &hatype
,
1402 strncpy(ifr
.ifr_name
, interfaceName
, sizeof(ifr
.ifr_name
));
1403 ifr
.ifr_name
[(sizeof(ifr
.ifr_name
))-1] = '\0';
1404 if (ioctl(s
->sock_fd
, SIOCGIFINDEX
, &ifr
) < 0) {
1409 PyErr_SetString(PyExc_ValueError
,
1410 "Hardware address must be 8 bytes or less");
1413 addr
= (struct sockaddr_ll
*)addr_ret
;
1414 addr
->sll_family
= AF_PACKET
;
1415 addr
->sll_protocol
= htons((short)protoNumber
);
1416 addr
->sll_ifindex
= ifr
.ifr_ifindex
;
1417 addr
->sll_pkttype
= pkttype
;
1418 addr
->sll_hatype
= hatype
;
1420 memcpy(&addr
->sll_addr
, haddr
, halen
);
1422 addr
->sll_halen
= halen
;
1423 *len_ret
= sizeof *addr
;
1428 /* More cases here... */
1431 PyErr_SetString(socket_error
, "getsockaddrarg: bad family");
1438 /* Get the address length according to the socket object's address family.
1439 Return 1 if the family is known, 0 otherwise. The length is returned
1443 getsockaddrlen(PySocketSockObject
*s
, socklen_t
*len_ret
)
1445 switch (s
->sock_family
) {
1447 #if defined(AF_UNIX)
1450 *len_ret
= sizeof (struct sockaddr_un
);
1453 #endif /* AF_UNIX */
1454 #if defined(AF_NETLINK)
1457 *len_ret
= sizeof (struct sockaddr_nl
);
1464 *len_ret
= sizeof (struct sockaddr_in
);
1471 *len_ret
= sizeof (struct sockaddr_in6
);
1476 #ifdef USE_BLUETOOTH
1479 switch(s
->sock_proto
)
1483 *len_ret
= sizeof (struct sockaddr_l2
);
1485 case BTPROTO_RFCOMM
:
1486 *len_ret
= sizeof (struct sockaddr_rc
);
1488 #if !defined(__FreeBSD__)
1490 *len_ret
= sizeof (struct sockaddr_sco
);
1494 PyErr_SetString(socket_error
, "getsockaddrlen: "
1495 "unknown BT protocol");
1502 #ifdef HAVE_NETPACKET_PACKET_H
1505 *len_ret
= sizeof (struct sockaddr_ll
);
1510 /* More cases here... */
1513 PyErr_SetString(socket_error
, "getsockaddrlen: bad family");
1520 /* s.accept() method */
1523 sock_accept(PySocketSockObject
*s
)
1525 sock_addr_t addrbuf
;
1528 PyObject
*sock
= NULL
;
1529 PyObject
*addr
= NULL
;
1530 PyObject
*res
= NULL
;
1533 if (!getsockaddrlen(s
, &addrlen
))
1535 memset(&addrbuf
, 0, addrlen
);
1538 newfd
= INVALID_SOCKET
;
1543 if (!IS_SELECTABLE(s
))
1544 return select_error();
1546 Py_BEGIN_ALLOW_THREADS
1547 timeout
= internal_select(s
, 0);
1549 newfd
= accept(s
->sock_fd
, SAS2SA(&addrbuf
), &addrlen
);
1550 Py_END_ALLOW_THREADS
1553 PyErr_SetString(socket_timeout
, "timed out");
1558 if (newfd
== INVALID_SOCKET
)
1562 return s
->errorhandler();
1564 /* Create the new object with unspecified family,
1565 to avoid calls to bind() etc. on it. */
1566 sock
= (PyObject
*) new_sockobject(newfd
,
1575 addr
= makesockaddr(s
->sock_fd
, SAS2SA(&addrbuf
),
1576 addrlen
, s
->sock_proto
);
1580 res
= PyTuple_Pack(2, sock
, addr
);
1588 PyDoc_STRVAR(accept_doc
,
1589 "accept() -> (socket object, address info)\n\
1591 Wait for an incoming connection. Return a new socket representing the\n\
1592 connection, and the address of the client. For IP sockets, the address\n\
1593 info is a pair (hostaddr, port).");
1595 /* s.setblocking(flag) method. Argument:
1596 False -- non-blocking mode; same as settimeout(0)
1597 True -- blocking mode; same as settimeout(None)
1601 sock_setblocking(PySocketSockObject
*s
, PyObject
*arg
)
1605 block
= PyInt_AsLong(arg
);
1606 if (block
== -1 && PyErr_Occurred())
1609 s
->sock_timeout
= block
? -1.0 : 0.0;
1610 internal_setblocking(s
, block
);
1616 PyDoc_STRVAR(setblocking_doc
,
1617 "setblocking(flag)\n\
1619 Set the socket to blocking (flag is true) or non-blocking (false).\n\
1620 setblocking(True) is equivalent to settimeout(None);\n\
1621 setblocking(False) is equivalent to settimeout(0.0).");
1623 /* s.settimeout(timeout) method. Argument:
1624 None -- no timeout, blocking mode; same as setblocking(True)
1625 0.0 -- non-blocking mode; same as setblocking(False)
1626 > 0 -- timeout mode; operations time out after timeout seconds
1627 < 0 -- illegal; raises an exception
1630 sock_settimeout(PySocketSockObject
*s
, PyObject
*arg
)
1637 timeout
= PyFloat_AsDouble(arg
);
1638 if (timeout
< 0.0) {
1639 if (!PyErr_Occurred())
1640 PyErr_SetString(PyExc_ValueError
,
1641 "Timeout value out of range");
1646 s
->sock_timeout
= timeout
;
1647 internal_setblocking(s
, timeout
< 0.0);
1653 PyDoc_STRVAR(settimeout_doc
,
1654 "settimeout(timeout)\n\
1656 Set a timeout on socket operations. 'timeout' can be a float,\n\
1657 giving in seconds, or None. Setting a timeout of None disables\n\
1658 the timeout feature and is equivalent to setblocking(1).\n\
1659 Setting a timeout of zero is the same as setblocking(0).");
1661 /* s.gettimeout() method.
1662 Returns the timeout associated with a socket. */
1664 sock_gettimeout(PySocketSockObject
*s
)
1666 if (s
->sock_timeout
< 0.0) {
1671 return PyFloat_FromDouble(s
->sock_timeout
);
1674 PyDoc_STRVAR(gettimeout_doc
,
1675 "gettimeout() -> timeout\n\
1677 Returns the timeout in floating seconds associated with socket \n\
1678 operations. A timeout of None indicates that timeouts on socket \n\
1679 operations are disabled.");
1682 /* s.sleeptaskw(1 | 0) method */
1685 sock_sleeptaskw(PySocketSockObject
*s
,PyObject
*arg
)
1688 block
= PyInt_AsLong(arg
);
1689 if (block
== -1 && PyErr_Occurred())
1691 Py_BEGIN_ALLOW_THREADS
1692 socketioctl(s
->sock_fd
, 0x80046679, (u_long
*)&block
);
1693 Py_END_ALLOW_THREADS
1698 PyDoc_STRVAR(sleeptaskw_doc
,
1699 "sleeptaskw(flag)\n\
1701 Allow sleeps in taskwindows.");
1705 /* s.setsockopt() method.
1706 With an integer third argument, sets an integer option.
1707 With a string third argument, sets an option from a buffer;
1708 use optional built-in module 'struct' to encode the string. */
1711 sock_setsockopt(PySocketSockObject
*s
, PyObject
*args
)
1720 if (PyArg_ParseTuple(args
, "iii:setsockopt",
1721 &level
, &optname
, &flag
)) {
1722 buf
= (char *) &flag
;
1723 buflen
= sizeof flag
;
1727 if (!PyArg_ParseTuple(args
, "iis#:setsockopt",
1728 &level
, &optname
, &buf
, &buflen
))
1731 res
= setsockopt(s
->sock_fd
, level
, optname
, (void *)buf
, buflen
);
1733 return s
->errorhandler();
1738 PyDoc_STRVAR(setsockopt_doc
,
1739 "setsockopt(level, option, value)\n\
1741 Set a socket option. See the Unix manual for level and option.\n\
1742 The value argument can either be an integer or a string.");
1745 /* s.getsockopt() method.
1746 With two arguments, retrieves an integer option.
1747 With a third integer argument, retrieves a string buffer of that size;
1748 use optional built-in module 'struct' to decode the string. */
1751 sock_getsockopt(PySocketSockObject
*s
, PyObject
*args
)
1757 socklen_t buflen
= 0;
1760 /* We have incomplete socket support. */
1761 PyErr_SetString(socket_error
, "getsockopt not supported");
1765 if (!PyArg_ParseTuple(args
, "ii|i:getsockopt",
1766 &level
, &optname
, &buflen
))
1771 socklen_t flagsize
= sizeof flag
;
1772 res
= getsockopt(s
->sock_fd
, level
, optname
,
1773 (void *)&flag
, &flagsize
);
1775 return s
->errorhandler();
1776 return PyInt_FromLong(flag
);
1779 /* socklen_t is unsigned so no negative test is needed,
1780 test buflen == 0 is previously done */
1781 if (buflen
> 1024) {
1783 if (buflen
<= 0 || buflen
> 1024) {
1785 PyErr_SetString(socket_error
,
1786 "getsockopt buflen out of range");
1789 buf
= PyString_FromStringAndSize((char *)NULL
, buflen
);
1792 res
= getsockopt(s
->sock_fd
, level
, optname
,
1793 (void *)PyString_AS_STRING(buf
), &buflen
);
1796 return s
->errorhandler();
1798 _PyString_Resize(&buf
, buflen
);
1800 #endif /* __BEOS__ */
1803 PyDoc_STRVAR(getsockopt_doc
,
1804 "getsockopt(level, option[, buffersize]) -> value\n\
1806 Get a socket option. See the Unix manual for level and option.\n\
1807 If a nonzero buffersize argument is given, the return value is a\n\
1808 string of that length; otherwise it is an integer.");
1811 /* s.bind(sockaddr) method */
1814 sock_bind(PySocketSockObject
*s
, PyObject
*addro
)
1816 sock_addr_t addrbuf
;
1820 if (!getsockaddrarg(s
, addro
, SAS2SA(&addrbuf
), &addrlen
))
1822 Py_BEGIN_ALLOW_THREADS
1823 res
= bind(s
->sock_fd
, SAS2SA(&addrbuf
), addrlen
);
1824 Py_END_ALLOW_THREADS
1826 return s
->errorhandler();
1831 PyDoc_STRVAR(bind_doc
,
1834 Bind the socket to a local address. For IP sockets, the address is a\n\
1835 pair (host, port); the host must refer to the local host. For raw packet\n\
1836 sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");
1839 /* s.close() method.
1840 Set the file descriptor to -1 so operations tried subsequently
1841 will surely fail. */
1844 sock_close(PySocketSockObject
*s
)
1848 if ((fd
= s
->sock_fd
) != -1) {
1850 Py_BEGIN_ALLOW_THREADS
1851 (void) SOCKETCLOSE(fd
);
1852 Py_END_ALLOW_THREADS
1858 PyDoc_STRVAR(close_doc
,
1861 Close the socket. It cannot be used after this call.");
1864 internal_connect(PySocketSockObject
*s
, struct sockaddr
*addr
, int addrlen
,
1870 res
= connect(s
->sock_fd
, addr
, addrlen
);
1874 if (s
->sock_timeout
> 0.0) {
1875 if (res
< 0 && WSAGetLastError() == WSAEWOULDBLOCK
&&
1877 /* This is a mess. Best solution: trust select */
1881 tv
.tv_sec
= (int)s
->sock_timeout
;
1882 tv
.tv_usec
= (int)((s
->sock_timeout
- tv
.tv_sec
) * 1e6
);
1884 FD_SET(s
->sock_fd
, &fds
);
1886 FD_SET(s
->sock_fd
, &fds_exc
);
1887 res
= select(s
->sock_fd
+1, NULL
, &fds
, &fds_exc
, &tv
);
1889 res
= WSAEWOULDBLOCK
;
1891 } else if (res
> 0) {
1892 if (FD_ISSET(s
->sock_fd
, &fds
))
1893 /* The socket is in the writeable set - this
1897 /* As per MS docs, we need to call getsockopt()
1898 to get the underlying error */
1899 int res_size
= sizeof res
;
1900 /* It must be in the exception set */
1901 assert(FD_ISSET(s
->sock_fd
, &fds_exc
));
1902 if (0 == getsockopt(s
->sock_fd
, SOL_SOCKET
, SO_ERROR
,
1903 (char *)&res
, &res_size
))
1904 /* getsockopt also clears WSAGetLastError,
1905 so reset it back. */
1906 WSASetLastError(res
);
1908 res
= WSAGetLastError();
1911 /* else if (res < 0) an error occurred */
1916 res
= WSAGetLastError();
1920 if (s
->sock_timeout
> 0.0) {
1921 if (res
< 0 && errno
== EINPROGRESS
&& IS_SELECTABLE(s
)) {
1922 timeout
= internal_select(s
, 1);
1924 res
= connect(s
->sock_fd
, addr
, addrlen
);
1925 if (res
< 0 && errno
== EISCONN
)
1928 else if (timeout
== -1)
1929 res
= errno
; /* had error */
1931 res
= EWOULDBLOCK
; /* timed out */
1939 *timeoutp
= timeout
;
1944 /* s.connect(sockaddr) method */
1947 sock_connect(PySocketSockObject
*s
, PyObject
*addro
)
1949 sock_addr_t addrbuf
;
1954 if (!getsockaddrarg(s
, addro
, SAS2SA(&addrbuf
), &addrlen
))
1957 Py_BEGIN_ALLOW_THREADS
1958 res
= internal_connect(s
, SAS2SA(&addrbuf
), addrlen
, &timeout
);
1959 Py_END_ALLOW_THREADS
1962 PyErr_SetString(socket_timeout
, "timed out");
1966 return s
->errorhandler();
1971 PyDoc_STRVAR(connect_doc
,
1972 "connect(address)\n\
1974 Connect the socket to a remote address. For IP sockets, the address\n\
1975 is a pair (host, port).");
1978 /* s.connect_ex(sockaddr) method */
1981 sock_connect_ex(PySocketSockObject
*s
, PyObject
*addro
)
1983 sock_addr_t addrbuf
;
1988 if (!getsockaddrarg(s
, addro
, SAS2SA(&addrbuf
), &addrlen
))
1991 Py_BEGIN_ALLOW_THREADS
1992 res
= internal_connect(s
, SAS2SA(&addrbuf
), addrlen
, &timeout
);
1993 Py_END_ALLOW_THREADS
1995 /* Signals are not errors (though they may raise exceptions). Adapted
1996 from PyErr_SetFromErrnoWithFilenameObject(). */
1998 if (res
== EINTR
&& PyErr_CheckSignals())
2002 return PyInt_FromLong((long) res
);
2005 PyDoc_STRVAR(connect_ex_doc
,
2006 "connect_ex(address) -> errno\n\
2008 This is like connect(address), but returns an error code (the errno value)\n\
2009 instead of raising an exception when an error occurs.");
2012 /* s.fileno() method */
2015 sock_fileno(PySocketSockObject
*s
)
2017 #if SIZEOF_SOCKET_T <= SIZEOF_LONG
2018 return PyInt_FromLong((long) s
->sock_fd
);
2020 return PyLong_FromLongLong((PY_LONG_LONG
)s
->sock_fd
);
2024 PyDoc_STRVAR(fileno_doc
,
2025 "fileno() -> integer\n\
2027 Return the integer file descriptor of the socket.");
2031 /* s.dup() method */
2034 sock_dup(PySocketSockObject
*s
)
2039 newfd
= dup(s
->sock_fd
);
2041 return s
->errorhandler();
2042 sock
= (PyObject
*) new_sockobject(newfd
,
2051 PyDoc_STRVAR(dup_doc
,
2052 "dup() -> socket object\n\
2054 Return a new socket object connected to the same system resource.");
2059 /* s.getsockname() method */
2062 sock_getsockname(PySocketSockObject
*s
)
2064 sock_addr_t addrbuf
;
2068 if (!getsockaddrlen(s
, &addrlen
))
2070 memset(&addrbuf
, 0, addrlen
);
2071 Py_BEGIN_ALLOW_THREADS
2072 res
= getsockname(s
->sock_fd
, SAS2SA(&addrbuf
), &addrlen
);
2073 Py_END_ALLOW_THREADS
2075 return s
->errorhandler();
2076 return makesockaddr(s
->sock_fd
, SAS2SA(&addrbuf
), addrlen
,
2080 PyDoc_STRVAR(getsockname_doc
,
2081 "getsockname() -> address info\n\
2083 Return the address of the local endpoint. For IP sockets, the address\n\
2084 info is a pair (hostaddr, port).");
2087 #ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
2088 /* s.getpeername() method */
2091 sock_getpeername(PySocketSockObject
*s
)
2093 sock_addr_t addrbuf
;
2097 if (!getsockaddrlen(s
, &addrlen
))
2099 memset(&addrbuf
, 0, addrlen
);
2100 Py_BEGIN_ALLOW_THREADS
2101 res
= getpeername(s
->sock_fd
, SAS2SA(&addrbuf
), &addrlen
);
2102 Py_END_ALLOW_THREADS
2104 return s
->errorhandler();
2105 return makesockaddr(s
->sock_fd
, SAS2SA(&addrbuf
), addrlen
,
2109 PyDoc_STRVAR(getpeername_doc
,
2110 "getpeername() -> address info\n\
2112 Return the address of the remote endpoint. For IP sockets, the address\n\
2113 info is a pair (hostaddr, port).");
2115 #endif /* HAVE_GETPEERNAME */
2118 /* s.listen(n) method */
2121 sock_listen(PySocketSockObject
*s
, PyObject
*arg
)
2126 backlog
= PyInt_AsLong(arg
);
2127 if (backlog
== -1 && PyErr_Occurred())
2129 Py_BEGIN_ALLOW_THREADS
2132 res
= listen(s
->sock_fd
, backlog
);
2133 Py_END_ALLOW_THREADS
2135 return s
->errorhandler();
2140 PyDoc_STRVAR(listen_doc
,
2143 Enable a server to accept connections. The backlog argument must be at\n\
2144 least 1; it specifies the number of unaccepted connection that the system\n\
2145 will allow before refusing new connections.");
2149 /* s.makefile(mode) method.
2150 Create a new open file object referring to a dupped version of
2151 the socket's file descriptor. (The dup() call is necessary so
2152 that the open file and socket objects may be closed independent
2154 The mode argument specifies 'r' or 'w' passed to fdopen(). */
2157 sock_makefile(PySocketSockObject
*s
, PyObject
*args
)
2159 extern int fclose(FILE *);
2174 if (!PyArg_ParseTuple(args
, "|si:makefile", &mode
, &bufsize
))
2177 if (strcmp(mode
,"rb") == 0) {
2181 if (strcmp(mode
,"wb") == 0) {
2187 if (((fd
= _open_osfhandle(s
->sock_fd
, _O_BINARY
)) < 0) ||
2188 ((fd
= dup(fd
)) < 0) || ((fp
= fdopen(fd
, mode
)) == NULL
))
2190 if ((fd
= dup(s
->sock_fd
)) < 0 || (fp
= fdopen(fd
, mode
)) == NULL
)
2195 return s
->errorhandler();
2197 f
= PyFile_FromFile(fp
, "<socket>", mode
, fclose
);
2199 PyFile_SetBufSize(f
, bufsize
);
2203 PyDoc_STRVAR(makefile_doc
,
2204 "makefile([mode[, buffersize]]) -> file object\n\
2206 Return a regular file object corresponding to the socket.\n\
2207 The mode and buffersize arguments are as for the built-in open() function.");
2212 * This is the guts of the recv() and recv_into() methods, which reads into a
2213 * char buffer. If you have any inc/dec ref to do to the objects that contain
2214 * the buffer, do it in the caller. This function returns the number of bytes
2215 * succesfully read. If there was an error, it returns -1. Note that it is
2216 * also possible that we return a number of bytes smaller than the request
2220 sock_recv_guts(PySocketSockObject
*s
, char* cbuf
, int len
, int flags
)
2222 ssize_t outlen
= -1;
2229 if (!IS_SELECTABLE(s
)) {
2235 Py_BEGIN_ALLOW_THREADS
2236 timeout
= internal_select(s
, 0);
2238 outlen
= recv(s
->sock_fd
, cbuf
, len
, flags
);
2239 Py_END_ALLOW_THREADS
2242 PyErr_SetString(socket_timeout
, "timed out");
2246 /* Note: the call to errorhandler() ALWAYS indirectly returned
2247 NULL, so ignore its return value */
2254 while (remaining
!= 0) {
2255 unsigned int segment
;
2258 segment
= remaining
/SEGMENT_SIZE
;
2260 segment
= SEGMENT_SIZE
;
2263 segment
= remaining
;
2266 Py_BEGIN_ALLOW_THREADS
2267 timeout
= internal_select(s
, 0);
2269 nread
= recv(s
->sock_fd
, read_buf
, segment
, flags
);
2270 Py_END_ALLOW_THREADS
2273 PyErr_SetString(socket_timeout
, "timed out");
2280 if (nread
!= remaining
) {
2285 remaining
-= segment
;
2286 read_buf
+= segment
;
2288 outlen
= read_buf
- cbuf
;
2295 /* s.recv(nbytes [,flags]) method */
2298 sock_recv(PySocketSockObject
*s
, PyObject
*args
)
2300 int recvlen
, flags
= 0;
2304 if (!PyArg_ParseTuple(args
, "i|i:recv", &recvlen
, &flags
))
2308 PyErr_SetString(PyExc_ValueError
,
2309 "negative buffersize in recv");
2313 /* Allocate a new string. */
2314 buf
= PyString_FromStringAndSize((char *) 0, recvlen
);
2319 outlen
= sock_recv_guts(s
, PyString_AS_STRING(buf
), recvlen
, flags
);
2321 /* An error occurred, release the string and return an
2326 if (outlen
!= recvlen
) {
2327 /* We did not read as many bytes as we anticipated, resize the
2328 string if possible and be succesful. */
2329 if (_PyString_Resize(&buf
, outlen
) < 0)
2330 /* Oopsy, not so succesful after all. */
2337 PyDoc_STRVAR(recv_doc
,
2338 "recv(buffersize[, flags]) -> data\n\
2340 Receive up to buffersize bytes from the socket. For the optional flags\n\
2341 argument, see the Unix manual. When no data is available, block until\n\
2342 at least one byte is available or until the remote end is closed. When\n\
2343 the remote end is closed and all data is read, return the empty string.");
2346 /* s.recv_into(buffer, [nbytes [,flags]]) method */
2349 sock_recv_into(PySocketSockObject
*s
, PyObject
*args
, PyObject
*kwds
)
2351 static char *kwlist
[] = {"buffer", "nbytes", "flags", 0};
2353 int recvlen
= 0, flags
= 0;
2358 /* Get the buffer's memory */
2359 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "w#|ii:recv", kwlist
,
2360 &buf
, &buflen
, &recvlen
, &flags
))
2362 assert(buf
!= 0 && buflen
> 0);
2365 PyErr_SetString(PyExc_ValueError
,
2366 "negative buffersize in recv");
2370 /* If nbytes was not specified, use the buffer's length */
2374 /* Check if the buffer is large enough */
2375 if (buflen
< recvlen
) {
2376 PyErr_SetString(PyExc_ValueError
,
2377 "buffer too small for requested bytes");
2382 readlen
= sock_recv_guts(s
, buf
, recvlen
, flags
);
2384 /* Return an error. */
2388 /* Return the number of bytes read. Note that we do not do anything
2389 special here in the case that readlen < recvlen. */
2390 return PyInt_FromSsize_t(readlen
);
2393 PyDoc_STRVAR(recv_into_doc
,
2394 "recv_into(buffer, [nbytes[, flags]]) -> nbytes_read\n\
2396 A version of recv() that stores its data into a buffer rather than creating \n\
2397 a new string. Receive up to buffersize bytes from the socket. If buffersize \n\
2398 is not specified (or 0), receive up to the size available in the given buffer.\n\
2400 See recv() for documentation about the flags.");
2404 * This is the guts of the recv() and recv_into() methods, which reads into a
2405 * char buffer. If you have any inc/def ref to do to the objects that contain
2406 * the buffer, do it in the caller. This function returns the number of bytes
2407 * succesfully read. If there was an error, it returns -1. Note that it is
2408 * also possible that we return a number of bytes smaller than the request
2411 * 'addr' is a return value for the address object. Note that you must decref
2415 sock_recvfrom_guts(PySocketSockObject
*s
, char* cbuf
, int len
, int flags
,
2418 sock_addr_t addrbuf
;
2425 if (!getsockaddrlen(s
, &addrlen
))
2428 if (!IS_SELECTABLE(s
)) {
2433 Py_BEGIN_ALLOW_THREADS
2434 memset(&addrbuf
, 0, addrlen
);
2435 timeout
= internal_select(s
, 0);
2438 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
2439 n
= recvfrom(s
->sock_fd
, cbuf
, len
, flags
,
2440 SAS2SA(&addrbuf
), &addrlen
);
2442 n
= recvfrom(s
->sock_fd
, cbuf
, len
, flags
,
2443 (void *) &addrbuf
, &addrlen
);
2446 n
= recvfrom(s
->sock_fd
, cbuf
, len
, flags
,
2447 SAS2SA(&addrbuf
), &addrlen
);
2450 Py_END_ALLOW_THREADS
2453 PyErr_SetString(socket_timeout
, "timed out");
2461 if (!(*addr
= makesockaddr(s
->sock_fd
, SAS2SA(&addrbuf
),
2462 addrlen
, s
->sock_proto
)))
2468 /* s.recvfrom(nbytes [,flags]) method */
2471 sock_recvfrom(PySocketSockObject
*s
, PyObject
*args
)
2473 PyObject
*buf
= NULL
;
2474 PyObject
*addr
= NULL
;
2475 PyObject
*ret
= NULL
;
2476 int recvlen
, flags
= 0;
2479 if (!PyArg_ParseTuple(args
, "i|i:recvfrom", &recvlen
, &flags
))
2482 buf
= PyString_FromStringAndSize((char *) 0, recvlen
);
2486 outlen
= sock_recvfrom_guts(s
, PyString_AS_STRING(buf
),
2487 recvlen
, flags
, &addr
);
2492 if (outlen
!= recvlen
) {
2493 /* We did not read as many bytes as we anticipated, resize the
2494 string if possible and be succesful. */
2495 if (_PyString_Resize(&buf
, outlen
) < 0)
2496 /* Oopsy, not so succesful after all. */
2500 ret
= PyTuple_Pack(2, buf
, addr
);
2508 PyDoc_STRVAR(recvfrom_doc
,
2509 "recvfrom(buffersize[, flags]) -> (data, address info)\n\
2511 Like recv(buffersize, flags) but also return the sender's address info.");
2514 /* s.recvfrom_into(buffer[, nbytes [,flags]]) method */
2517 sock_recvfrom_into(PySocketSockObject
*s
, PyObject
*args
, PyObject
* kwds
)
2519 static char *kwlist
[] = {"buffer", "nbytes", "flags", 0};
2521 int recvlen
= 0, flags
= 0;
2526 PyObject
*addr
= NULL
;
2528 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "w#|ii:recvfrom", kwlist
,
2529 &buf
, &buflen
, &recvlen
, &flags
))
2531 assert(buf
!= 0 && buflen
> 0);
2534 PyErr_SetString(PyExc_ValueError
,
2535 "negative buffersize in recv");
2539 /* If nbytes was not specified, use the buffer's length */
2543 readlen
= sock_recvfrom_guts(s
, buf
, recvlen
, flags
, &addr
);
2545 /* Return an error */
2550 /* Return the number of bytes read and the address. Note that we do
2551 not do anything special here in the case that readlen < recvlen. */
2552 return Py_BuildValue("lN", readlen
, addr
);
2555 PyDoc_STRVAR(recvfrom_into_doc
,
2556 "recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)\n\
2558 Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.");
2561 /* s.send(data [,flags]) method */
2564 sock_send(PySocketSockObject
*s
, PyObject
*args
)
2567 int len
, n
= -1, flags
= 0, timeout
;
2569 if (!PyArg_ParseTuple(args
, "s#|i:send", &buf
, &len
, &flags
))
2572 if (!IS_SELECTABLE(s
))
2573 return select_error();
2575 Py_BEGIN_ALLOW_THREADS
2576 timeout
= internal_select(s
, 1);
2579 n
= sendsegmented(s
->sock_fd
, buf
, len
, flags
);
2581 n
= send(s
->sock_fd
, buf
, len
, flags
);
2583 Py_END_ALLOW_THREADS
2586 PyErr_SetString(socket_timeout
, "timed out");
2590 return s
->errorhandler();
2591 return PyInt_FromLong((long)n
);
2594 PyDoc_STRVAR(send_doc
,
2595 "send(data[, flags]) -> count\n\
2597 Send a data string to the socket. For the optional flags\n\
2598 argument, see the Unix manual. Return the number of bytes\n\
2599 sent; this may be less than len(data) if the network is busy.");
2602 /* s.sendall(data [,flags]) method */
2605 sock_sendall(PySocketSockObject
*s
, PyObject
*args
)
2608 int len
, n
= -1, flags
= 0, timeout
;
2610 if (!PyArg_ParseTuple(args
, "s#|i:sendall", &buf
, &len
, &flags
))
2613 if (!IS_SELECTABLE(s
))
2614 return select_error();
2616 Py_BEGIN_ALLOW_THREADS
2618 timeout
= internal_select(s
, 1);
2623 n
= sendsegmented(s
->sock_fd
, buf
, len
, flags
);
2625 n
= send(s
->sock_fd
, buf
, len
, flags
);
2632 Py_END_ALLOW_THREADS
2635 PyErr_SetString(socket_timeout
, "timed out");
2639 return s
->errorhandler();
2645 PyDoc_STRVAR(sendall_doc
,
2646 "sendall(data[, flags])\n\
2648 Send a data string to the socket. For the optional flags\n\
2649 argument, see the Unix manual. This calls send() repeatedly\n\
2650 until all data is sent. If an error occurs, it's impossible\n\
2651 to tell how much data has been sent.");
2654 /* s.sendto(data, [flags,] sockaddr) method */
2657 sock_sendto(PySocketSockObject
*s
, PyObject
*args
)
2661 sock_addr_t addrbuf
;
2662 int addrlen
, len
, n
= -1, flags
, timeout
;
2665 if (!PyArg_ParseTuple(args
, "s#O:sendto", &buf
, &len
, &addro
)) {
2667 if (!PyArg_ParseTuple(args
, "s#iO:sendto",
2668 &buf
, &len
, &flags
, &addro
))
2672 if (!IS_SELECTABLE(s
))
2673 return select_error();
2675 if (!getsockaddrarg(s
, addro
, SAS2SA(&addrbuf
), &addrlen
))
2678 Py_BEGIN_ALLOW_THREADS
2679 timeout
= internal_select(s
, 1);
2681 n
= sendto(s
->sock_fd
, buf
, len
, flags
, SAS2SA(&addrbuf
), addrlen
);
2682 Py_END_ALLOW_THREADS
2685 PyErr_SetString(socket_timeout
, "timed out");
2689 return s
->errorhandler();
2690 return PyInt_FromLong((long)n
);
2693 PyDoc_STRVAR(sendto_doc
,
2694 "sendto(data[, flags], address) -> count\n\
2696 Like send(data, flags) but allows specifying the destination address.\n\
2697 For IP sockets, the address is a pair (hostaddr, port).");
2700 /* s.shutdown(how) method */
2703 sock_shutdown(PySocketSockObject
*s
, PyObject
*arg
)
2708 how
= PyInt_AsLong(arg
);
2709 if (how
== -1 && PyErr_Occurred())
2711 Py_BEGIN_ALLOW_THREADS
2712 res
= shutdown(s
->sock_fd
, how
);
2713 Py_END_ALLOW_THREADS
2715 return s
->errorhandler();
2720 PyDoc_STRVAR(shutdown_doc
,
2723 Shut down the reading side of the socket (flag == SHUT_RD), the writing side\n\
2724 of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).");
2727 /* List of methods for socket objects */
2729 static PyMethodDef sock_methods
[] = {
2730 {"accept", (PyCFunction
)sock_accept
, METH_NOARGS
,
2732 {"bind", (PyCFunction
)sock_bind
, METH_O
,
2734 {"close", (PyCFunction
)sock_close
, METH_NOARGS
,
2736 {"connect", (PyCFunction
)sock_connect
, METH_O
,
2738 {"connect_ex", (PyCFunction
)sock_connect_ex
, METH_O
,
2741 {"dup", (PyCFunction
)sock_dup
, METH_NOARGS
,
2744 {"fileno", (PyCFunction
)sock_fileno
, METH_NOARGS
,
2746 #ifdef HAVE_GETPEERNAME
2747 {"getpeername", (PyCFunction
)sock_getpeername
,
2748 METH_NOARGS
, getpeername_doc
},
2750 {"getsockname", (PyCFunction
)sock_getsockname
,
2751 METH_NOARGS
, getsockname_doc
},
2752 {"getsockopt", (PyCFunction
)sock_getsockopt
, METH_VARARGS
,
2754 {"listen", (PyCFunction
)sock_listen
, METH_O
,
2757 {"makefile", (PyCFunction
)sock_makefile
, METH_VARARGS
,
2760 {"recv", (PyCFunction
)sock_recv
, METH_VARARGS
,
2762 {"recv_into", (PyCFunction
)sock_recv_into
, METH_VARARGS
| METH_KEYWORDS
,
2764 {"recvfrom", (PyCFunction
)sock_recvfrom
, METH_VARARGS
,
2766 {"recvfrom_into", (PyCFunction
)sock_recvfrom_into
, METH_VARARGS
| METH_KEYWORDS
,
2768 {"send", (PyCFunction
)sock_send
, METH_VARARGS
,
2770 {"sendall", (PyCFunction
)sock_sendall
, METH_VARARGS
,
2772 {"sendto", (PyCFunction
)sock_sendto
, METH_VARARGS
,
2774 {"setblocking", (PyCFunction
)sock_setblocking
, METH_O
,
2776 {"settimeout", (PyCFunction
)sock_settimeout
, METH_O
,
2778 {"gettimeout", (PyCFunction
)sock_gettimeout
, METH_NOARGS
,
2780 {"setsockopt", (PyCFunction
)sock_setsockopt
, METH_VARARGS
,
2782 {"shutdown", (PyCFunction
)sock_shutdown
, METH_O
,
2785 {"sleeptaskw", (PyCFunction
)sock_sleeptaskw
, METH_O
,
2788 {NULL
, NULL
} /* sentinel */
2791 /* SockObject members */
2792 static PyMemberDef sock_memberlist
[] = {
2793 {"family", T_INT
, offsetof(PySocketSockObject
, sock_family
), READONLY
, "the socket family"},
2794 {"type", T_INT
, offsetof(PySocketSockObject
, sock_type
), READONLY
, "the socket type"},
2795 {"proto", T_INT
, offsetof(PySocketSockObject
, sock_proto
), READONLY
, "the socket protocol"},
2796 {"timeout", T_DOUBLE
, offsetof(PySocketSockObject
, sock_timeout
), READONLY
, "the socket timeout"},
2800 /* Deallocate a socket object in response to the last Py_DECREF().
2801 First close the file description. */
2804 sock_dealloc(PySocketSockObject
*s
)
2806 if (s
->sock_fd
!= -1)
2807 (void) SOCKETCLOSE(s
->sock_fd
);
2808 s
->ob_type
->tp_free((PyObject
*)s
);
2813 sock_repr(PySocketSockObject
*s
)
2816 #if SIZEOF_SOCKET_T > SIZEOF_LONG
2817 if (s
->sock_fd
> LONG_MAX
) {
2818 /* this can occur on Win64, and actually there is a special
2819 ugly printf formatter for decimal pointer length integer
2820 printing, only bother if necessary*/
2821 PyErr_SetString(PyExc_OverflowError
,
2822 "no printf formatter to display "
2823 "the socket descriptor in decimal");
2829 "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
2830 (long)s
->sock_fd
, s
->sock_family
,
2833 return PyString_FromString(buf
);
2837 /* Create a new, uninitialized socket object. */
2840 sock_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
2844 new = type
->tp_alloc(type
, 0);
2846 ((PySocketSockObject
*)new)->sock_fd
= -1;
2847 ((PySocketSockObject
*)new)->sock_timeout
= -1.0;
2848 ((PySocketSockObject
*)new)->errorhandler
= &set_error
;
2854 /* Initialize a new socket object. */
2858 sock_initobj(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
2860 PySocketSockObject
*s
= (PySocketSockObject
*)self
;
2862 int family
= AF_INET
, type
= SOCK_STREAM
, proto
= 0;
2863 static char *keywords
[] = {"family", "type", "proto", 0};
2865 if (!PyArg_ParseTupleAndKeywords(args
, kwds
,
2866 "|iii:socket", keywords
,
2867 &family
, &type
, &proto
))
2870 Py_BEGIN_ALLOW_THREADS
2871 fd
= socket(family
, type
, proto
);
2872 Py_END_ALLOW_THREADS
2875 if (fd
== INVALID_SOCKET
)
2883 init_sockobject(s
, fd
, family
, type
, proto
);
2890 /* Type object for socket objects. */
2892 static PyTypeObject sock_type
= {
2893 PyObject_HEAD_INIT(0) /* Must fill in type value later */
2895 "_socket.socket", /* tp_name */
2896 sizeof(PySocketSockObject
), /* tp_basicsize */
2897 0, /* tp_itemsize */
2898 (destructor
)sock_dealloc
, /* tp_dealloc */
2903 (reprfunc
)sock_repr
, /* tp_repr */
2904 0, /* tp_as_number */
2905 0, /* tp_as_sequence */
2906 0, /* tp_as_mapping */
2910 PyObject_GenericGetAttr
, /* tp_getattro */
2911 0, /* tp_setattro */
2912 0, /* tp_as_buffer */
2913 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
2914 sock_doc
, /* tp_doc */
2915 0, /* tp_traverse */
2917 0, /* tp_richcompare */
2918 0, /* tp_weaklistoffset */
2920 0, /* tp_iternext */
2921 sock_methods
, /* tp_methods */
2922 sock_memberlist
, /* tp_members */
2926 0, /* tp_descr_get */
2927 0, /* tp_descr_set */
2928 0, /* tp_dictoffset */
2929 sock_initobj
, /* tp_init */
2930 PyType_GenericAlloc
, /* tp_alloc */
2931 sock_new
, /* tp_new */
2932 PyObject_Del
, /* tp_free */
2936 /* Python interface to gethostname(). */
2940 socket_gethostname(PyObject
*self
, PyObject
*unused
)
2944 Py_BEGIN_ALLOW_THREADS
2945 res
= gethostname(buf
, (int) sizeof buf
- 1);
2946 Py_END_ALLOW_THREADS
2949 buf
[sizeof buf
- 1] = '\0';
2950 return PyString_FromString(buf
);
2953 PyDoc_STRVAR(gethostname_doc
,
2954 "gethostname() -> string\n\
2956 Return the current host name.");
2959 /* Python interface to gethostbyname(name). */
2963 socket_gethostbyname(PyObject
*self
, PyObject
*args
)
2966 sock_addr_t addrbuf
;
2968 if (!PyArg_ParseTuple(args
, "s:gethostbyname", &name
))
2970 if (setipaddr(name
, SAS2SA(&addrbuf
), sizeof(addrbuf
), AF_INET
) < 0)
2972 return makeipaddr(SAS2SA(&addrbuf
), sizeof(struct sockaddr_in
));
2975 PyDoc_STRVAR(gethostbyname_doc
,
2976 "gethostbyname(host) -> address\n\
2978 Return the IP address (a string of the form '255.255.255.255') for a host.");
2981 /* Convenience function common to gethostbyname_ex and gethostbyaddr */
2984 gethost_common(struct hostent
*h
, struct sockaddr
*addr
, int alen
, int af
)
2987 PyObject
*rtn_tuple
= (PyObject
*)NULL
;
2988 PyObject
*name_list
= (PyObject
*)NULL
;
2989 PyObject
*addr_list
= (PyObject
*)NULL
;
2993 /* Let's get real error message to return */
2995 set_herror(h_errno
);
2997 PyErr_SetString(socket_error
, "host not found");
3002 if (h
->h_addrtype
!= af
) {
3003 #ifdef HAVE_STRERROR
3004 /* Let's get real error message to return */
3005 PyErr_SetString(socket_error
,
3006 (char *)strerror(EAFNOSUPPORT
));
3010 "Address family not supported by protocol family");
3018 if (alen
< sizeof(struct sockaddr_in
))
3024 if (alen
< sizeof(struct sockaddr_in6
))
3031 if ((name_list
= PyList_New(0)) == NULL
)
3034 if ((addr_list
= PyList_New(0)) == NULL
)
3037 /* SF #1511317: h_aliases can be NULL */
3039 for (pch
= h
->h_aliases
; *pch
!= NULL
; pch
++) {
3041 tmp
= PyString_FromString(*pch
);
3045 status
= PyList_Append(name_list
, tmp
);
3053 for (pch
= h
->h_addr_list
; *pch
!= NULL
; pch
++) {
3060 struct sockaddr_in sin
;
3061 memset(&sin
, 0, sizeof(sin
));
3062 sin
.sin_family
= af
;
3063 #ifdef HAVE_SOCKADDR_SA_LEN
3064 sin
.sin_len
= sizeof(sin
);
3066 memcpy(&sin
.sin_addr
, *pch
, sizeof(sin
.sin_addr
));
3067 tmp
= makeipaddr((struct sockaddr
*)&sin
, sizeof(sin
));
3069 if (pch
== h
->h_addr_list
&& alen
>= sizeof(sin
))
3070 memcpy((char *) addr
, &sin
, sizeof(sin
));
3077 struct sockaddr_in6 sin6
;
3078 memset(&sin6
, 0, sizeof(sin6
));
3079 sin6
.sin6_family
= af
;
3080 #ifdef HAVE_SOCKADDR_SA_LEN
3081 sin6
.sin6_len
= sizeof(sin6
);
3083 memcpy(&sin6
.sin6_addr
, *pch
, sizeof(sin6
.sin6_addr
));
3084 tmp
= makeipaddr((struct sockaddr
*)&sin6
,
3087 if (pch
== h
->h_addr_list
&& alen
>= sizeof(sin6
))
3088 memcpy((char *) addr
, &sin6
, sizeof(sin6
));
3093 default: /* can't happen */
3094 PyErr_SetString(socket_error
,
3095 "unsupported address family");
3102 status
= PyList_Append(addr_list
, tmp
);
3109 rtn_tuple
= Py_BuildValue("sOO", h
->h_name
, name_list
, addr_list
);
3112 Py_XDECREF(name_list
);
3113 Py_XDECREF(addr_list
);
3118 /* Python interface to gethostbyname_ex(name). */
3122 socket_gethostbyname_ex(PyObject
*self
, PyObject
*args
)
3127 struct sockaddr_storage addr
;
3129 struct sockaddr_in addr
;
3131 struct sockaddr
*sa
;
3133 #ifdef HAVE_GETHOSTBYNAME_R
3134 struct hostent hp_allocated
;
3135 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
3136 struct hostent_data data
;
3139 int buf_len
= (sizeof buf
) - 1;
3142 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3145 #endif /* HAVE_GETHOSTBYNAME_R */
3147 if (!PyArg_ParseTuple(args
, "s:gethostbyname_ex", &name
))
3149 if (setipaddr(name
, (struct sockaddr
*)&addr
, sizeof(addr
), AF_INET
) < 0)
3151 Py_BEGIN_ALLOW_THREADS
3152 #ifdef HAVE_GETHOSTBYNAME_R
3153 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3154 result
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
,
3156 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
3157 h
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
, &errnop
);
3158 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
3159 memset((void *) &data
, '\0', sizeof(data
));
3160 result
= gethostbyname_r(name
, &hp_allocated
, &data
);
3161 h
= (result
!= 0) ? NULL
: &hp_allocated
;
3163 #else /* not HAVE_GETHOSTBYNAME_R */
3164 #ifdef USE_GETHOSTBYNAME_LOCK
3165 PyThread_acquire_lock(netdb_lock
, 1);
3167 h
= gethostbyname(name
);
3168 #endif /* HAVE_GETHOSTBYNAME_R */
3169 Py_END_ALLOW_THREADS
3170 /* Some C libraries would require addr.__ss_family instead of
3172 Therefore, we cast the sockaddr_storage into sockaddr to
3173 access sa_family. */
3174 sa
= (struct sockaddr
*)&addr
;
3175 ret
= gethost_common(h
, (struct sockaddr
*)&addr
, sizeof(addr
),
3177 #ifdef USE_GETHOSTBYNAME_LOCK
3178 PyThread_release_lock(netdb_lock
);
3183 PyDoc_STRVAR(ghbn_ex_doc
,
3184 "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
3186 Return the true host name, a list of aliases, and a list of IP addresses,\n\
3187 for a host. The host argument is a string giving a host name or IP number.");
3190 /* Python interface to gethostbyaddr(IP). */
3194 socket_gethostbyaddr(PyObject
*self
, PyObject
*args
)
3197 struct sockaddr_storage addr
;
3199 struct sockaddr_in addr
;
3201 struct sockaddr
*sa
= (struct sockaddr
*)&addr
;
3205 #ifdef HAVE_GETHOSTBYNAME_R
3206 struct hostent hp_allocated
;
3207 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
3208 struct hostent_data data
;
3211 int buf_len
= (sizeof buf
) - 1;
3214 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3217 #endif /* HAVE_GETHOSTBYNAME_R */
3222 if (!PyArg_ParseTuple(args
, "s:gethostbyaddr", &ip_num
))
3225 if (setipaddr(ip_num
, sa
, sizeof(addr
), af
) < 0)
3232 ap
= (char *)&((struct sockaddr_in
*)sa
)->sin_addr
;
3233 al
= sizeof(((struct sockaddr_in
*)sa
)->sin_addr
);
3237 ap
= (char *)&((struct sockaddr_in6
*)sa
)->sin6_addr
;
3238 al
= sizeof(((struct sockaddr_in6
*)sa
)->sin6_addr
);
3242 PyErr_SetString(socket_error
, "unsupported address family");
3245 Py_BEGIN_ALLOW_THREADS
3246 #ifdef HAVE_GETHOSTBYNAME_R
3247 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3248 result
= gethostbyaddr_r(ap
, al
, af
,
3249 &hp_allocated
, buf
, buf_len
,
3251 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
3252 h
= gethostbyaddr_r(ap
, al
, af
,
3253 &hp_allocated
, buf
, buf_len
, &errnop
);
3254 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
3255 memset((void *) &data
, '\0', sizeof(data
));
3256 result
= gethostbyaddr_r(ap
, al
, af
, &hp_allocated
, &data
);
3257 h
= (result
!= 0) ? NULL
: &hp_allocated
;
3259 #else /* not HAVE_GETHOSTBYNAME_R */
3260 #ifdef USE_GETHOSTBYNAME_LOCK
3261 PyThread_acquire_lock(netdb_lock
, 1);
3263 h
= gethostbyaddr(ap
, al
, af
);
3264 #endif /* HAVE_GETHOSTBYNAME_R */
3265 Py_END_ALLOW_THREADS
3266 ret
= gethost_common(h
, (struct sockaddr
*)&addr
, sizeof(addr
), af
);
3267 #ifdef USE_GETHOSTBYNAME_LOCK
3268 PyThread_release_lock(netdb_lock
);
3273 PyDoc_STRVAR(gethostbyaddr_doc
,
3274 "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
3276 Return the true host name, a list of aliases, and a list of IP addresses,\n\
3277 for a host. The host argument is a string giving a host name or IP number.");
3280 /* Python interface to getservbyname(name).
3281 This only returns the port number, since the other info is already
3282 known or not useful (like the list of aliases). */
3286 socket_getservbyname(PyObject
*self
, PyObject
*args
)
3288 char *name
, *proto
=NULL
;
3290 if (!PyArg_ParseTuple(args
, "s|s:getservbyname", &name
, &proto
))
3292 Py_BEGIN_ALLOW_THREADS
3293 sp
= getservbyname(name
, proto
);
3294 Py_END_ALLOW_THREADS
3296 PyErr_SetString(socket_error
, "service/proto not found");
3299 return PyInt_FromLong((long) ntohs(sp
->s_port
));
3302 PyDoc_STRVAR(getservbyname_doc
,
3303 "getservbyname(servicename[, protocolname]) -> integer\n\
3305 Return a port number from a service name and protocol name.\n\
3306 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3307 otherwise any protocol will match.");
3310 /* Python interface to getservbyport(port).
3311 This only returns the service name, since the other info is already
3312 known or not useful (like the list of aliases). */
3316 socket_getservbyport(PyObject
*self
, PyObject
*args
)
3318 unsigned short port
;
3321 if (!PyArg_ParseTuple(args
, "H|s:getservbyport", &port
, &proto
))
3323 Py_BEGIN_ALLOW_THREADS
3324 sp
= getservbyport(htons(port
), proto
);
3325 Py_END_ALLOW_THREADS
3327 PyErr_SetString(socket_error
, "port/proto not found");
3330 return PyString_FromString(sp
->s_name
);
3333 PyDoc_STRVAR(getservbyport_doc
,
3334 "getservbyport(port[, protocolname]) -> string\n\
3336 Return the service name from a port number and protocol name.\n\
3337 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3338 otherwise any protocol will match.");
3340 /* Python interface to getprotobyname(name).
3341 This only returns the protocol number, since the other info is
3342 already known or not useful (like the list of aliases). */
3346 socket_getprotobyname(PyObject
*self
, PyObject
*args
)
3349 struct protoent
*sp
;
3351 /* Not available in BeOS yet. - [cjh] */
3352 PyErr_SetString(socket_error
, "getprotobyname not supported");
3355 if (!PyArg_ParseTuple(args
, "s:getprotobyname", &name
))
3357 Py_BEGIN_ALLOW_THREADS
3358 sp
= getprotobyname(name
);
3359 Py_END_ALLOW_THREADS
3361 PyErr_SetString(socket_error
, "protocol not found");
3364 return PyInt_FromLong((long) sp
->p_proto
);
3368 PyDoc_STRVAR(getprotobyname_doc
,
3369 "getprotobyname(name) -> integer\n\
3371 Return the protocol number for the named protocol. (Rarely used.)");
3374 #ifdef HAVE_SOCKETPAIR
3375 /* Create a pair of sockets using the socketpair() function.
3376 Arguments as for socket() except the default family is AF_UNIX if
3377 defined on the platform; otherwise, the default is AF_INET. */
3381 socket_socketpair(PyObject
*self
, PyObject
*args
)
3383 PySocketSockObject
*s0
= NULL
, *s1
= NULL
;
3385 int family
, type
= SOCK_STREAM
, proto
= 0;
3386 PyObject
*res
= NULL
;
3388 #if defined(AF_UNIX)
3393 if (!PyArg_ParseTuple(args
, "|iii:socketpair",
3394 &family
, &type
, &proto
))
3396 /* Create a pair of socket fds */
3397 if (socketpair(family
, type
, proto
, sv
) < 0)
3399 s0
= new_sockobject(sv
[0], family
, type
, proto
);
3402 s1
= new_sockobject(sv
[1], family
, type
, proto
);
3405 res
= PyTuple_Pack(2, s0
, s1
);
3419 PyDoc_STRVAR(socketpair_doc
,
3420 "socketpair([family[, type[, proto]]]) -> (socket object, socket object)\n\
3422 Create a pair of socket objects from the sockets returned by the platform\n\
3423 socketpair() function.\n\
3424 The arguments are the same as for socket() except the default family is\n\
3425 AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");
3427 #endif /* HAVE_SOCKETPAIR */
3431 /* Create a socket object from a numeric file description.
3432 Useful e.g. if stdin is a socket.
3433 Additional arguments as for socket(). */
3437 socket_fromfd(PyObject
*self
, PyObject
*args
)
3439 PySocketSockObject
*s
;
3441 int family
, type
, proto
= 0;
3442 if (!PyArg_ParseTuple(args
, "iii|i:fromfd",
3443 &fd
, &family
, &type
, &proto
))
3445 /* Dup the fd so it and the socket can be closed independently */
3449 s
= new_sockobject(fd
, family
, type
, proto
);
3450 return (PyObject
*) s
;
3453 PyDoc_STRVAR(fromfd_doc
,
3454 "fromfd(fd, family, type[, proto]) -> socket object\n\
3456 Create a socket object from a duplicate of the given\n\
3458 The remaining arguments are the same as for socket().");
3464 socket_ntohs(PyObject
*self
, PyObject
*args
)
3468 if (!PyArg_ParseTuple(args
, "i:ntohs", &x1
)) {
3472 PyErr_SetString(PyExc_OverflowError
,
3473 "can't convert negative number to unsigned long");
3476 x2
= (unsigned int)ntohs((unsigned short)x1
);
3477 return PyInt_FromLong(x2
);
3480 PyDoc_STRVAR(ntohs_doc
,
3481 "ntohs(integer) -> integer\n\
3483 Convert a 16-bit integer from network to host byte order.");
3487 socket_ntohl(PyObject
*self
, PyObject
*arg
)
3491 if (PyInt_Check(arg
)) {
3492 x
= PyInt_AS_LONG(arg
);
3493 if (x
== (unsigned long) -1 && PyErr_Occurred())
3496 PyErr_SetString(PyExc_OverflowError
,
3497 "can't convert negative number to unsigned long");
3501 else if (PyLong_Check(arg
)) {
3502 x
= PyLong_AsUnsignedLong(arg
);
3503 if (x
== (unsigned long) -1 && PyErr_Occurred())
3508 /* only want the trailing 32 bits */
3509 y
= x
& 0xFFFFFFFFUL
;
3511 return PyErr_Format(PyExc_OverflowError
,
3512 "long int larger than 32 bits");
3518 return PyErr_Format(PyExc_TypeError
,
3519 "expected int/long, %s found",
3520 arg
->ob_type
->tp_name
);
3521 if (x
== (unsigned long) -1 && PyErr_Occurred())
3523 return PyLong_FromUnsignedLong(ntohl(x
));
3526 PyDoc_STRVAR(ntohl_doc
,
3527 "ntohl(integer) -> integer\n\
3529 Convert a 32-bit integer from network to host byte order.");
3533 socket_htons(PyObject
*self
, PyObject
*args
)
3537 if (!PyArg_ParseTuple(args
, "i:htons", &x1
)) {
3541 PyErr_SetString(PyExc_OverflowError
,
3542 "can't convert negative number to unsigned long");
3545 x2
= (unsigned int)htons((unsigned short)x1
);
3546 return PyInt_FromLong(x2
);
3549 PyDoc_STRVAR(htons_doc
,
3550 "htons(integer) -> integer\n\
3552 Convert a 16-bit integer from host to network byte order.");
3556 socket_htonl(PyObject
*self
, PyObject
*arg
)
3560 if (PyInt_Check(arg
)) {
3561 x
= PyInt_AS_LONG(arg
);
3562 if (x
== (unsigned long) -1 && PyErr_Occurred())
3565 PyErr_SetString(PyExc_OverflowError
,
3566 "can't convert negative number to unsigned long");
3570 else if (PyLong_Check(arg
)) {
3571 x
= PyLong_AsUnsignedLong(arg
);
3572 if (x
== (unsigned long) -1 && PyErr_Occurred())
3577 /* only want the trailing 32 bits */
3578 y
= x
& 0xFFFFFFFFUL
;
3580 return PyErr_Format(PyExc_OverflowError
,
3581 "long int larger than 32 bits");
3587 return PyErr_Format(PyExc_TypeError
,
3588 "expected int/long, %s found",
3589 arg
->ob_type
->tp_name
);
3590 return PyLong_FromUnsignedLong(htonl((unsigned long)x
));
3593 PyDoc_STRVAR(htonl_doc
,
3594 "htonl(integer) -> integer\n\
3596 Convert a 32-bit integer from host to network byte order.");
3598 /* socket.inet_aton() and socket.inet_ntoa() functions. */
3600 PyDoc_STRVAR(inet_aton_doc
,
3601 "inet_aton(string) -> packed 32-bit IP representation\n\
3603 Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
3604 binary format used in low-level network functions.");
3607 socket_inet_aton(PyObject
*self
, PyObject
*args
)
3610 #define INADDR_NONE (-1)
3612 #ifdef HAVE_INET_ATON
3616 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
3617 /* Have to use inet_addr() instead */
3618 unsigned long packed_addr
;
3622 if (!PyArg_ParseTuple(args
, "s:inet_aton", &ip_addr
))
3626 #ifdef HAVE_INET_ATON
3628 #ifdef USE_INET_ATON_WEAKLINK
3629 if (inet_aton
!= NULL
) {
3631 if (inet_aton(ip_addr
, &buf
))
3632 return PyString_FromStringAndSize((char *)(&buf
),
3635 PyErr_SetString(socket_error
,
3636 "illegal IP address string passed to inet_aton");
3639 #ifdef USE_INET_ATON_WEAKLINK
3645 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
3647 /* special-case this address as inet_addr might return INADDR_NONE
3649 if (strcmp(ip_addr
, "255.255.255.255") == 0) {
3650 packed_addr
= 0xFFFFFFFF;
3653 packed_addr
= inet_addr(ip_addr
);
3655 if (packed_addr
== INADDR_NONE
) { /* invalid address */
3656 PyErr_SetString(socket_error
,
3657 "illegal IP address string passed to inet_aton");
3661 return PyString_FromStringAndSize((char *) &packed_addr
,
3662 sizeof(packed_addr
));
3664 #ifdef USE_INET_ATON_WEAKLINK
3671 PyDoc_STRVAR(inet_ntoa_doc
,
3672 "inet_ntoa(packed_ip) -> ip_address_string\n\
3674 Convert an IP address from 32-bit packed binary format to string format");
3677 socket_inet_ntoa(PyObject
*self
, PyObject
*args
)
3681 struct in_addr packed_addr
;
3683 if (!PyArg_ParseTuple(args
, "s#:inet_ntoa", &packed_str
, &addr_len
)) {
3687 if (addr_len
!= sizeof(packed_addr
)) {
3688 PyErr_SetString(socket_error
,
3689 "packed IP wrong length for inet_ntoa");
3693 memcpy(&packed_addr
, packed_str
, addr_len
);
3695 return PyString_FromString(inet_ntoa(packed_addr
));
3698 #ifdef HAVE_INET_PTON
3700 PyDoc_STRVAR(inet_pton_doc
,
3701 "inet_pton(af, ip) -> packed IP address string\n\
3703 Convert an IP address from string format to a packed string suitable\n\
3704 for use with low-level network functions.");
3707 socket_inet_pton(PyObject
*self
, PyObject
*args
)
3713 char packed
[MAX(sizeof(struct in_addr
), sizeof(struct in6_addr
))];
3715 char packed
[sizeof(struct in_addr
)];
3717 if (!PyArg_ParseTuple(args
, "is:inet_pton", &af
, &ip
)) {
3721 #if !defined(ENABLE_IPV6) && defined(AF_INET6)
3722 if(af
== AF_INET6
) {
3723 PyErr_SetString(socket_error
,
3724 "can't use AF_INET6, IPv6 is disabled");
3729 retval
= inet_pton(af
, ip
, packed
);
3731 PyErr_SetFromErrno(socket_error
);
3733 } else if (retval
== 0) {
3734 PyErr_SetString(socket_error
,
3735 "illegal IP address string passed to inet_pton");
3737 } else if (af
== AF_INET
) {
3738 return PyString_FromStringAndSize(packed
,
3739 sizeof(struct in_addr
));
3741 } else if (af
== AF_INET6
) {
3742 return PyString_FromStringAndSize(packed
,
3743 sizeof(struct in6_addr
));
3746 PyErr_SetString(socket_error
, "unknown address family");
3751 PyDoc_STRVAR(inet_ntop_doc
,
3752 "inet_ntop(af, packed_ip) -> string formatted IP address\n\
3754 Convert a packed IP address of the given family to string format.");
3757 socket_inet_ntop(PyObject
*self
, PyObject
*args
)
3764 char ip
[MAX(INET_ADDRSTRLEN
, INET6_ADDRSTRLEN
) + 1];
3766 char ip
[INET_ADDRSTRLEN
+ 1];
3769 /* Guarantee NUL-termination for PyString_FromString() below */
3770 memset((void *) &ip
[0], '\0', sizeof(ip
));
3772 if (!PyArg_ParseTuple(args
, "is#:inet_ntop", &af
, &packed
, &len
)) {
3776 if (af
== AF_INET
) {
3777 if (len
!= sizeof(struct in_addr
)) {
3778 PyErr_SetString(PyExc_ValueError
,
3779 "invalid length of packed IP address string");
3783 } else if (af
== AF_INET6
) {
3784 if (len
!= sizeof(struct in6_addr
)) {
3785 PyErr_SetString(PyExc_ValueError
,
3786 "invalid length of packed IP address string");
3791 PyErr_Format(PyExc_ValueError
,
3792 "unknown address family %d", af
);
3796 retval
= inet_ntop(af
, packed
, ip
, sizeof(ip
));
3798 PyErr_SetFromErrno(socket_error
);
3801 return PyString_FromString(retval
);
3805 PyErr_SetString(PyExc_RuntimeError
, "invalid handling of inet_ntop");
3809 #endif /* HAVE_INET_PTON */
3811 /* Python interface to getaddrinfo(host, port). */
3815 socket_getaddrinfo(PyObject
*self
, PyObject
*args
)
3817 struct addrinfo hints
, *res
;
3818 struct addrinfo
*res0
= NULL
;
3819 PyObject
*hobj
= NULL
;
3820 PyObject
*pobj
= (PyObject
*)NULL
;
3823 int family
, socktype
, protocol
, flags
;
3825 PyObject
*all
= (PyObject
*)NULL
;
3826 PyObject
*single
= (PyObject
*)NULL
;
3827 PyObject
*idna
= NULL
;
3829 family
= socktype
= protocol
= flags
= 0;
3831 if (!PyArg_ParseTuple(args
, "OO|iiii:getaddrinfo",
3832 &hobj
, &pobj
, &family
, &socktype
,
3833 &protocol
, &flags
)) {
3836 if (hobj
== Py_None
) {
3838 } else if (PyUnicode_Check(hobj
)) {
3839 idna
= PyObject_CallMethod(hobj
, "encode", "s", "idna");
3842 hptr
= PyString_AsString(idna
);
3843 } else if (PyString_Check(hobj
)) {
3844 hptr
= PyString_AsString(hobj
);
3846 PyErr_SetString(PyExc_TypeError
,
3847 "getaddrinfo() argument 1 must be string or None");
3850 if (PyInt_Check(pobj
)) {
3851 PyOS_snprintf(pbuf
, sizeof(pbuf
), "%ld", PyInt_AsLong(pobj
));
3853 } else if (PyString_Check(pobj
)) {
3854 pptr
= PyString_AsString(pobj
);
3855 } else if (pobj
== Py_None
) {
3856 pptr
= (char *)NULL
;
3858 PyErr_SetString(socket_error
, "Int or String expected");
3861 memset(&hints
, 0, sizeof(hints
));
3862 hints
.ai_family
= family
;
3863 hints
.ai_socktype
= socktype
;
3864 hints
.ai_protocol
= protocol
;
3865 hints
.ai_flags
= flags
;
3866 Py_BEGIN_ALLOW_THREADS
3867 ACQUIRE_GETADDRINFO_LOCK
3868 error
= getaddrinfo(hptr
, pptr
, &hints
, &res0
);
3869 Py_END_ALLOW_THREADS
3870 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
3872 set_gaierror(error
);
3876 if ((all
= PyList_New(0)) == NULL
)
3878 for (res
= res0
; res
; res
= res
->ai_next
) {
3880 makesockaddr(-1, res
->ai_addr
, res
->ai_addrlen
, protocol
);
3883 single
= Py_BuildValue("iiisO", res
->ai_family
,
3884 res
->ai_socktype
, res
->ai_protocol
,
3885 res
->ai_canonname
? res
->ai_canonname
: "",
3891 if (PyList_Append(all
, single
))
3905 return (PyObject
*)NULL
;
3908 PyDoc_STRVAR(getaddrinfo_doc
,
3909 "getaddrinfo(host, port [, family, socktype, proto, flags])\n\
3910 -> list of (family, socktype, proto, canonname, sockaddr)\n\
3912 Resolve host and port into addrinfo struct.");
3914 /* Python interface to getnameinfo(sa, flags). */
3918 socket_getnameinfo(PyObject
*self
, PyObject
*args
)
3920 PyObject
*sa
= (PyObject
*)NULL
;
3923 int port
, flowinfo
, scope_id
;
3924 char hbuf
[NI_MAXHOST
], pbuf
[NI_MAXSERV
];
3925 struct addrinfo hints
, *res
= NULL
;
3927 PyObject
*ret
= (PyObject
*)NULL
;
3929 flags
= flowinfo
= scope_id
= 0;
3930 if (!PyArg_ParseTuple(args
, "Oi:getnameinfo", &sa
, &flags
))
3932 if (!PyArg_ParseTuple(sa
, "si|ii",
3933 &hostp
, &port
, &flowinfo
, &scope_id
))
3935 PyOS_snprintf(pbuf
, sizeof(pbuf
), "%d", port
);
3936 memset(&hints
, 0, sizeof(hints
));
3937 hints
.ai_family
= AF_UNSPEC
;
3938 hints
.ai_socktype
= SOCK_DGRAM
; /* make numeric port happy */
3939 Py_BEGIN_ALLOW_THREADS
3940 ACQUIRE_GETADDRINFO_LOCK
3941 error
= getaddrinfo(hostp
, pbuf
, &hints
, &res
);
3942 Py_END_ALLOW_THREADS
3943 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
3945 set_gaierror(error
);
3949 PyErr_SetString(socket_error
,
3950 "sockaddr resolved to multiple addresses");
3953 switch (res
->ai_family
) {
3958 if (PyArg_ParseTuple(sa
, "si", &t1
, &t2
) == 0) {
3959 PyErr_SetString(socket_error
,
3960 "IPv4 sockaddr must be 2 tuple");
3968 struct sockaddr_in6
*sin6
;
3969 sin6
= (struct sockaddr_in6
*)res
->ai_addr
;
3970 sin6
->sin6_flowinfo
= flowinfo
;
3971 sin6
->sin6_scope_id
= scope_id
;
3976 error
= getnameinfo(res
->ai_addr
, res
->ai_addrlen
,
3977 hbuf
, sizeof(hbuf
), pbuf
, sizeof(pbuf
), flags
);
3979 set_gaierror(error
);
3982 ret
= Py_BuildValue("ss", hbuf
, pbuf
);
3990 PyDoc_STRVAR(getnameinfo_doc
,
3991 "getnameinfo(sockaddr, flags) --> (host, port)\n\
3993 Get host and port for a sockaddr.");
3996 /* Python API to getting and setting the default timeout value. */
3999 socket_getdefaulttimeout(PyObject
*self
)
4001 if (defaulttimeout
< 0.0) {
4006 return PyFloat_FromDouble(defaulttimeout
);
4009 PyDoc_STRVAR(getdefaulttimeout_doc
,
4010 "getdefaulttimeout() -> timeout\n\
4012 Returns the default timeout in floating seconds for new socket objects.\n\
4013 A value of None indicates that new socket objects have no timeout.\n\
4014 When the socket module is first imported, the default is None.");
4017 socket_setdefaulttimeout(PyObject
*self
, PyObject
*arg
)
4024 timeout
= PyFloat_AsDouble(arg
);
4025 if (timeout
< 0.0) {
4026 if (!PyErr_Occurred())
4027 PyErr_SetString(PyExc_ValueError
,
4028 "Timeout value out of range");
4033 defaulttimeout
= timeout
;
4039 PyDoc_STRVAR(setdefaulttimeout_doc
,
4040 "setdefaulttimeout(timeout)\n\
4042 Set the default timeout in floating seconds for new socket objects.\n\
4043 A value of None indicates that new socket objects have no timeout.\n\
4044 When the socket module is first imported, the default is None.");
4047 /* List of functions exported by this module. */
4049 static PyMethodDef socket_methods
[] = {
4050 {"gethostbyname", socket_gethostbyname
,
4051 METH_VARARGS
, gethostbyname_doc
},
4052 {"gethostbyname_ex", socket_gethostbyname_ex
,
4053 METH_VARARGS
, ghbn_ex_doc
},
4054 {"gethostbyaddr", socket_gethostbyaddr
,
4055 METH_VARARGS
, gethostbyaddr_doc
},
4056 {"gethostname", socket_gethostname
,
4057 METH_NOARGS
, gethostname_doc
},
4058 {"getservbyname", socket_getservbyname
,
4059 METH_VARARGS
, getservbyname_doc
},
4060 {"getservbyport", socket_getservbyport
,
4061 METH_VARARGS
, getservbyport_doc
},
4062 {"getprotobyname", socket_getprotobyname
,
4063 METH_VARARGS
, getprotobyname_doc
},
4065 {"fromfd", socket_fromfd
,
4066 METH_VARARGS
, fromfd_doc
},
4068 #ifdef HAVE_SOCKETPAIR
4069 {"socketpair", socket_socketpair
,
4070 METH_VARARGS
, socketpair_doc
},
4072 {"ntohs", socket_ntohs
,
4073 METH_VARARGS
, ntohs_doc
},
4074 {"ntohl", socket_ntohl
,
4076 {"htons", socket_htons
,
4077 METH_VARARGS
, htons_doc
},
4078 {"htonl", socket_htonl
,
4080 {"inet_aton", socket_inet_aton
,
4081 METH_VARARGS
, inet_aton_doc
},
4082 {"inet_ntoa", socket_inet_ntoa
,
4083 METH_VARARGS
, inet_ntoa_doc
},
4084 #ifdef HAVE_INET_PTON
4085 {"inet_pton", socket_inet_pton
,
4086 METH_VARARGS
, inet_pton_doc
},
4087 {"inet_ntop", socket_inet_ntop
,
4088 METH_VARARGS
, inet_ntop_doc
},
4090 {"getaddrinfo", socket_getaddrinfo
,
4091 METH_VARARGS
, getaddrinfo_doc
},
4092 {"getnameinfo", socket_getnameinfo
,
4093 METH_VARARGS
, getnameinfo_doc
},
4094 {"getdefaulttimeout", (PyCFunction
)socket_getdefaulttimeout
,
4095 METH_NOARGS
, getdefaulttimeout_doc
},
4096 {"setdefaulttimeout", socket_setdefaulttimeout
,
4097 METH_O
, setdefaulttimeout_doc
},
4098 {NULL
, NULL
} /* Sentinel */
4103 #define OS_INIT_DEFINED
4111 _kernel_swi(0x43380, &r
, &r
);
4112 taskwindow
= r
.r
[0];
4121 #define OS_INIT_DEFINED
4123 /* Additional initialization and cleanup for Windows */
4137 ret
= WSAStartup(0x0101, &WSAData
);
4139 case 0: /* No error */
4140 Py_AtExit(os_cleanup
);
4141 return 1; /* Success */
4142 case WSASYSNOTREADY
:
4143 PyErr_SetString(PyExc_ImportError
,
4144 "WSAStartup failed: network not ready");
4146 case WSAVERNOTSUPPORTED
:
4150 "WSAStartup failed: requested version not supported");
4153 PyOS_snprintf(buf
, sizeof(buf
),
4154 "WSAStartup failed: error code %d", ret
);
4155 PyErr_SetString(PyExc_ImportError
, buf
);
4158 return 0; /* Failure */
4161 #endif /* MS_WINDOWS */
4165 #define OS_INIT_DEFINED
4167 /* Additional initialization for OS/2 */
4174 int rc
= sock_init();
4177 return 1; /* Success */
4180 PyOS_snprintf(reason
, sizeof(reason
),
4181 "OS/2 TCP/IP Error# %d", sock_errno());
4182 PyErr_SetString(PyExc_ImportError
, reason
);
4184 return 0; /* Failure */
4186 /* No need to initialise sockets with GCC/EMX */
4187 return 1; /* Success */
4191 #endif /* PYOS_OS2 */
4194 #ifndef OS_INIT_DEFINED
4198 return 1; /* Success */
4203 /* C API table - always add new things to the end for binary
4206 PySocketModule_APIObject PySocketModuleAPI
=
4213 /* Initialize the _socket module.
4215 This module is actually called "_socket", and there's a wrapper
4216 "socket.py" which implements some additional functionality. On some
4217 platforms (e.g. Windows and OS/2), socket.py also implements a
4218 wrapper for the socket type that provides missing functionality such
4219 as makefile(), dup() and fromfd(). The import of "_socket" may fail
4220 with an ImportError exception if os-specific initialization fails.
4221 On Windows, this does WINSOCK initialization. When WINSOCK is
4222 initialized succesfully, a call to WSACleanup() is scheduled to be
4226 PyDoc_STRVAR(socket_doc
,
4227 "Implementation module for socket operations.\n\
4229 See the socket module for documentation.");
4234 PyObject
*m
, *has_ipv6
;
4239 sock_type
.ob_type
= &PyType_Type
;
4240 m
= Py_InitModule3(PySocket_MODULE_NAME
,
4246 socket_error
= PyErr_NewException("socket.error", NULL
, NULL
);
4247 if (socket_error
== NULL
)
4249 PySocketModuleAPI
.error
= socket_error
;
4250 Py_INCREF(socket_error
);
4251 PyModule_AddObject(m
, "error", socket_error
);
4252 socket_herror
= PyErr_NewException("socket.herror",
4253 socket_error
, NULL
);
4254 if (socket_herror
== NULL
)
4256 Py_INCREF(socket_herror
);
4257 PyModule_AddObject(m
, "herror", socket_herror
);
4258 socket_gaierror
= PyErr_NewException("socket.gaierror", socket_error
,
4260 if (socket_gaierror
== NULL
)
4262 Py_INCREF(socket_gaierror
);
4263 PyModule_AddObject(m
, "gaierror", socket_gaierror
);
4264 socket_timeout
= PyErr_NewException("socket.timeout",
4265 socket_error
, NULL
);
4266 if (socket_timeout
== NULL
)
4268 Py_INCREF(socket_timeout
);
4269 PyModule_AddObject(m
, "timeout", socket_timeout
);
4270 Py_INCREF((PyObject
*)&sock_type
);
4271 if (PyModule_AddObject(m
, "SocketType",
4272 (PyObject
*)&sock_type
) != 0)
4274 Py_INCREF((PyObject
*)&sock_type
);
4275 if (PyModule_AddObject(m
, "socket",
4276 (PyObject
*)&sock_type
) != 0)
4282 has_ipv6
= Py_False
;
4284 Py_INCREF(has_ipv6
);
4285 PyModule_AddObject(m
, "has_ipv6", has_ipv6
);
4288 if (PyModule_AddObject(m
, PySocket_CAPI_NAME
,
4289 PyCObject_FromVoidPtr((void *)&PySocketModuleAPI
, NULL
)
4293 /* Address families (we only support AF_INET and AF_UNIX) */
4295 PyModule_AddIntConstant(m
, "AF_UNSPEC", AF_UNSPEC
);
4297 PyModule_AddIntConstant(m
, "AF_INET", AF_INET
);
4299 PyModule_AddIntConstant(m
, "AF_INET6", AF_INET6
);
4300 #endif /* AF_INET6 */
4301 #if defined(AF_UNIX)
4302 PyModule_AddIntConstant(m
, "AF_UNIX", AF_UNIX
);
4303 #endif /* AF_UNIX */
4305 /* Amateur Radio AX.25 */
4306 PyModule_AddIntConstant(m
, "AF_AX25", AF_AX25
);
4309 PyModule_AddIntConstant(m
, "AF_IPX", AF_IPX
); /* Novell IPX */
4313 PyModule_AddIntConstant(m
, "AF_APPLETALK", AF_APPLETALK
);
4316 /* Amateur radio NetROM */
4317 PyModule_AddIntConstant(m
, "AF_NETROM", AF_NETROM
);
4320 /* Multiprotocol bridge */
4321 PyModule_AddIntConstant(m
, "AF_BRIDGE", AF_BRIDGE
);
4325 PyModule_AddIntConstant(m
, "AF_ATMPVC", AF_ATMPVC
);
4328 /* Reserved for Werner's ATM */
4329 PyModule_AddIntConstant(m
, "AF_AAL5", AF_AAL5
);
4332 /* Reserved for X.25 project */
4333 PyModule_AddIntConstant(m
, "AF_X25", AF_X25
);
4336 PyModule_AddIntConstant(m
, "AF_INET6", AF_INET6
); /* IP version 6 */
4339 /* Amateur Radio X.25 PLP */
4340 PyModule_AddIntConstant(m
, "AF_ROSE", AF_ROSE
);
4343 /* Reserved for DECnet project */
4344 PyModule_AddIntConstant(m
, "AF_DECnet", AF_DECnet
);
4347 /* Reserved for 802.2LLC project */
4348 PyModule_AddIntConstant(m
, "AF_NETBEUI", AF_NETBEUI
);
4351 /* Security callback pseudo AF */
4352 PyModule_AddIntConstant(m
, "AF_SECURITY", AF_SECURITY
);
4355 /* PF_KEY key management API */
4356 PyModule_AddIntConstant(m
, "AF_KEY", AF_KEY
);
4360 PyModule_AddIntConstant(m
, "AF_NETLINK", AF_NETLINK
);
4361 PyModule_AddIntConstant(m
, "NETLINK_ROUTE", NETLINK_ROUTE
);
4363 PyModule_AddIntConstant(m
, "NETLINK_SKIP", NETLINK_SKIP
);
4366 PyModule_AddIntConstant(m
, "NETLINK_W1", NETLINK_W1
);
4368 PyModule_AddIntConstant(m
, "NETLINK_USERSOCK", NETLINK_USERSOCK
);
4369 PyModule_AddIntConstant(m
, "NETLINK_FIREWALL", NETLINK_FIREWALL
);
4370 #ifdef NETLINK_TCPDIAG
4371 PyModule_AddIntConstant(m
, "NETLINK_TCPDIAG", NETLINK_TCPDIAG
);
4373 #ifdef NETLINK_NFLOG
4374 PyModule_AddIntConstant(m
, "NETLINK_NFLOG", NETLINK_NFLOG
);
4377 PyModule_AddIntConstant(m
, "NETLINK_XFRM", NETLINK_XFRM
);
4380 PyModule_AddIntConstant(m
, "NETLINK_ARPD", NETLINK_ARPD
);
4382 #ifdef NETLINK_ROUTE6
4383 PyModule_AddIntConstant(m
, "NETLINK_ROUTE6", NETLINK_ROUTE6
);
4385 PyModule_AddIntConstant(m
, "NETLINK_IP6_FW", NETLINK_IP6_FW
);
4386 PyModule_AddIntConstant(m
, "NETLINK_DNRTMSG", NETLINK_DNRTMSG
);
4387 #ifdef NETLINK_TAPBASE
4388 PyModule_AddIntConstant(m
, "NETLINK_TAPBASE", NETLINK_TAPBASE
);
4390 #endif /* AF_NETLINK */
4392 /* Alias to emulate 4.4BSD */
4393 PyModule_AddIntConstant(m
, "AF_ROUTE", AF_ROUTE
);
4397 PyModule_AddIntConstant(m
, "AF_ASH", AF_ASH
);
4401 PyModule_AddIntConstant(m
, "AF_ECONET", AF_ECONET
);
4405 PyModule_AddIntConstant(m
, "AF_ATMSVC", AF_ATMSVC
);
4408 /* Linux SNA Project (nutters!) */
4409 PyModule_AddIntConstant(m
, "AF_SNA", AF_SNA
);
4413 PyModule_AddIntConstant(m
, "AF_IRDA", AF_IRDA
);
4417 PyModule_AddIntConstant(m
, "AF_PPPOX", AF_PPPOX
);
4420 /* Wanpipe API Sockets */
4421 PyModule_AddIntConstant(m
, "AF_WANPIPE", AF_WANPIPE
);
4425 PyModule_AddIntConstant(m
, "AF_LLC", AF_LLC
);
4428 #ifdef USE_BLUETOOTH
4429 PyModule_AddIntConstant(m
, "AF_BLUETOOTH", AF_BLUETOOTH
);
4430 PyModule_AddIntConstant(m
, "BTPROTO_L2CAP", BTPROTO_L2CAP
);
4431 #if !defined(__FreeBSD__)
4432 PyModule_AddIntConstant(m
, "BTPROTO_SCO", BTPROTO_SCO
);
4434 PyModule_AddIntConstant(m
, "BTPROTO_RFCOMM", BTPROTO_RFCOMM
);
4435 PyModule_AddStringConstant(m
, "BDADDR_ANY", "00:00:00:00:00:00");
4436 PyModule_AddStringConstant(m
, "BDADDR_LOCAL", "00:00:00:FF:FF:FF");
4439 #ifdef HAVE_NETPACKET_PACKET_H
4440 PyModule_AddIntConstant(m
, "AF_PACKET", AF_PACKET
);
4441 PyModule_AddIntConstant(m
, "PF_PACKET", PF_PACKET
);
4442 PyModule_AddIntConstant(m
, "PACKET_HOST", PACKET_HOST
);
4443 PyModule_AddIntConstant(m
, "PACKET_BROADCAST", PACKET_BROADCAST
);
4444 PyModule_AddIntConstant(m
, "PACKET_MULTICAST", PACKET_MULTICAST
);
4445 PyModule_AddIntConstant(m
, "PACKET_OTHERHOST", PACKET_OTHERHOST
);
4446 PyModule_AddIntConstant(m
, "PACKET_OUTGOING", PACKET_OUTGOING
);
4447 PyModule_AddIntConstant(m
, "PACKET_LOOPBACK", PACKET_LOOPBACK
);
4448 PyModule_AddIntConstant(m
, "PACKET_FASTROUTE", PACKET_FASTROUTE
);
4452 PyModule_AddIntConstant(m
, "SOCK_STREAM", SOCK_STREAM
);
4453 PyModule_AddIntConstant(m
, "SOCK_DGRAM", SOCK_DGRAM
);
4455 /* We have incomplete socket support. */
4456 PyModule_AddIntConstant(m
, "SOCK_RAW", SOCK_RAW
);
4457 PyModule_AddIntConstant(m
, "SOCK_SEQPACKET", SOCK_SEQPACKET
);
4458 #if defined(SOCK_RDM)
4459 PyModule_AddIntConstant(m
, "SOCK_RDM", SOCK_RDM
);
4464 PyModule_AddIntConstant(m
, "SO_DEBUG", SO_DEBUG
);
4466 #ifdef SO_ACCEPTCONN
4467 PyModule_AddIntConstant(m
, "SO_ACCEPTCONN", SO_ACCEPTCONN
);
4470 PyModule_AddIntConstant(m
, "SO_REUSEADDR", SO_REUSEADDR
);
4472 #ifdef SO_EXCLUSIVEADDRUSE
4473 PyModule_AddIntConstant(m
, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE
);
4477 PyModule_AddIntConstant(m
, "SO_KEEPALIVE", SO_KEEPALIVE
);
4480 PyModule_AddIntConstant(m
, "SO_DONTROUTE", SO_DONTROUTE
);
4483 PyModule_AddIntConstant(m
, "SO_BROADCAST", SO_BROADCAST
);
4485 #ifdef SO_USELOOPBACK
4486 PyModule_AddIntConstant(m
, "SO_USELOOPBACK", SO_USELOOPBACK
);
4489 PyModule_AddIntConstant(m
, "SO_LINGER", SO_LINGER
);
4492 PyModule_AddIntConstant(m
, "SO_OOBINLINE", SO_OOBINLINE
);
4495 PyModule_AddIntConstant(m
, "SO_REUSEPORT", SO_REUSEPORT
);
4498 PyModule_AddIntConstant(m
, "SO_SNDBUF", SO_SNDBUF
);
4501 PyModule_AddIntConstant(m
, "SO_RCVBUF", SO_RCVBUF
);
4504 PyModule_AddIntConstant(m
, "SO_SNDLOWAT", SO_SNDLOWAT
);
4507 PyModule_AddIntConstant(m
, "SO_RCVLOWAT", SO_RCVLOWAT
);
4510 PyModule_AddIntConstant(m
, "SO_SNDTIMEO", SO_SNDTIMEO
);
4513 PyModule_AddIntConstant(m
, "SO_RCVTIMEO", SO_RCVTIMEO
);
4516 PyModule_AddIntConstant(m
, "SO_ERROR", SO_ERROR
);
4519 PyModule_AddIntConstant(m
, "SO_TYPE", SO_TYPE
);
4522 /* Maximum number of connections for "listen" */
4524 PyModule_AddIntConstant(m
, "SOMAXCONN", SOMAXCONN
);
4526 PyModule_AddIntConstant(m
, "SOMAXCONN", 5); /* Common value */
4529 /* Flags for send, recv */
4531 PyModule_AddIntConstant(m
, "MSG_OOB", MSG_OOB
);
4534 PyModule_AddIntConstant(m
, "MSG_PEEK", MSG_PEEK
);
4536 #ifdef MSG_DONTROUTE
4537 PyModule_AddIntConstant(m
, "MSG_DONTROUTE", MSG_DONTROUTE
);
4540 PyModule_AddIntConstant(m
, "MSG_DONTWAIT", MSG_DONTWAIT
);
4543 PyModule_AddIntConstant(m
, "MSG_EOR", MSG_EOR
);
4546 PyModule_AddIntConstant(m
, "MSG_TRUNC", MSG_TRUNC
);
4549 PyModule_AddIntConstant(m
, "MSG_CTRUNC", MSG_CTRUNC
);
4552 PyModule_AddIntConstant(m
, "MSG_WAITALL", MSG_WAITALL
);
4555 PyModule_AddIntConstant(m
, "MSG_BTAG", MSG_BTAG
);
4558 PyModule_AddIntConstant(m
, "MSG_ETAG", MSG_ETAG
);
4561 /* Protocol level and numbers, usable for [gs]etsockopt */
4563 PyModule_AddIntConstant(m
, "SOL_SOCKET", SOL_SOCKET
);
4566 PyModule_AddIntConstant(m
, "SOL_IP", SOL_IP
);
4568 PyModule_AddIntConstant(m
, "SOL_IP", 0);
4571 PyModule_AddIntConstant(m
, "SOL_IPX", SOL_IPX
);
4574 PyModule_AddIntConstant(m
, "SOL_AX25", SOL_AX25
);
4577 PyModule_AddIntConstant(m
, "SOL_ATALK", SOL_ATALK
);
4580 PyModule_AddIntConstant(m
, "SOL_NETROM", SOL_NETROM
);
4583 PyModule_AddIntConstant(m
, "SOL_ROSE", SOL_ROSE
);
4586 PyModule_AddIntConstant(m
, "SOL_TCP", SOL_TCP
);
4588 PyModule_AddIntConstant(m
, "SOL_TCP", 6);
4591 PyModule_AddIntConstant(m
, "SOL_UDP", SOL_UDP
);
4593 PyModule_AddIntConstant(m
, "SOL_UDP", 17);
4596 PyModule_AddIntConstant(m
, "IPPROTO_IP", IPPROTO_IP
);
4598 PyModule_AddIntConstant(m
, "IPPROTO_IP", 0);
4600 #ifdef IPPROTO_HOPOPTS
4601 PyModule_AddIntConstant(m
, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS
);
4604 PyModule_AddIntConstant(m
, "IPPROTO_ICMP", IPPROTO_ICMP
);
4606 PyModule_AddIntConstant(m
, "IPPROTO_ICMP", 1);
4609 PyModule_AddIntConstant(m
, "IPPROTO_IGMP", IPPROTO_IGMP
);
4612 PyModule_AddIntConstant(m
, "IPPROTO_GGP", IPPROTO_GGP
);
4615 PyModule_AddIntConstant(m
, "IPPROTO_IPV4", IPPROTO_IPV4
);
4618 PyModule_AddIntConstant(m
, "IPPROTO_IPV6", IPPROTO_IPV6
);
4621 PyModule_AddIntConstant(m
, "IPPROTO_IPIP", IPPROTO_IPIP
);
4624 PyModule_AddIntConstant(m
, "IPPROTO_TCP", IPPROTO_TCP
);
4626 PyModule_AddIntConstant(m
, "IPPROTO_TCP", 6);
4629 PyModule_AddIntConstant(m
, "IPPROTO_EGP", IPPROTO_EGP
);
4632 PyModule_AddIntConstant(m
, "IPPROTO_PUP", IPPROTO_PUP
);
4635 PyModule_AddIntConstant(m
, "IPPROTO_UDP", IPPROTO_UDP
);
4637 PyModule_AddIntConstant(m
, "IPPROTO_UDP", 17);
4640 PyModule_AddIntConstant(m
, "IPPROTO_IDP", IPPROTO_IDP
);
4642 #ifdef IPPROTO_HELLO
4643 PyModule_AddIntConstant(m
, "IPPROTO_HELLO", IPPROTO_HELLO
);
4646 PyModule_AddIntConstant(m
, "IPPROTO_ND", IPPROTO_ND
);
4649 PyModule_AddIntConstant(m
, "IPPROTO_TP", IPPROTO_TP
);
4652 PyModule_AddIntConstant(m
, "IPPROTO_IPV6", IPPROTO_IPV6
);
4654 #ifdef IPPROTO_ROUTING
4655 PyModule_AddIntConstant(m
, "IPPROTO_ROUTING", IPPROTO_ROUTING
);
4657 #ifdef IPPROTO_FRAGMENT
4658 PyModule_AddIntConstant(m
, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT
);
4661 PyModule_AddIntConstant(m
, "IPPROTO_RSVP", IPPROTO_RSVP
);
4664 PyModule_AddIntConstant(m
, "IPPROTO_GRE", IPPROTO_GRE
);
4667 PyModule_AddIntConstant(m
, "IPPROTO_ESP", IPPROTO_ESP
);
4670 PyModule_AddIntConstant(m
, "IPPROTO_AH", IPPROTO_AH
);
4672 #ifdef IPPROTO_MOBILE
4673 PyModule_AddIntConstant(m
, "IPPROTO_MOBILE", IPPROTO_MOBILE
);
4675 #ifdef IPPROTO_ICMPV6
4676 PyModule_AddIntConstant(m
, "IPPROTO_ICMPV6", IPPROTO_ICMPV6
);
4679 PyModule_AddIntConstant(m
, "IPPROTO_NONE", IPPROTO_NONE
);
4681 #ifdef IPPROTO_DSTOPTS
4682 PyModule_AddIntConstant(m
, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS
);
4685 PyModule_AddIntConstant(m
, "IPPROTO_XTP", IPPROTO_XTP
);
4688 PyModule_AddIntConstant(m
, "IPPROTO_EON", IPPROTO_EON
);
4691 PyModule_AddIntConstant(m
, "IPPROTO_PIM", IPPROTO_PIM
);
4693 #ifdef IPPROTO_IPCOMP
4694 PyModule_AddIntConstant(m
, "IPPROTO_IPCOMP", IPPROTO_IPCOMP
);
4697 PyModule_AddIntConstant(m
, "IPPROTO_VRRP", IPPROTO_VRRP
);
4700 PyModule_AddIntConstant(m
, "IPPROTO_BIP", IPPROTO_BIP
);
4704 PyModule_AddIntConstant(m
, "IPPROTO_RAW", IPPROTO_RAW
);
4706 PyModule_AddIntConstant(m
, "IPPROTO_RAW", 255);
4709 PyModule_AddIntConstant(m
, "IPPROTO_MAX", IPPROTO_MAX
);
4712 /* Some port configuration */
4713 #ifdef IPPORT_RESERVED
4714 PyModule_AddIntConstant(m
, "IPPORT_RESERVED", IPPORT_RESERVED
);
4716 PyModule_AddIntConstant(m
, "IPPORT_RESERVED", 1024);
4718 #ifdef IPPORT_USERRESERVED
4719 PyModule_AddIntConstant(m
, "IPPORT_USERRESERVED", IPPORT_USERRESERVED
);
4721 PyModule_AddIntConstant(m
, "IPPORT_USERRESERVED", 5000);
4724 /* Some reserved IP v.4 addresses */
4726 PyModule_AddIntConstant(m
, "INADDR_ANY", INADDR_ANY
);
4728 PyModule_AddIntConstant(m
, "INADDR_ANY", 0x00000000);
4730 #ifdef INADDR_BROADCAST
4731 PyModule_AddIntConstant(m
, "INADDR_BROADCAST", INADDR_BROADCAST
);
4733 PyModule_AddIntConstant(m
, "INADDR_BROADCAST", 0xffffffff);
4735 #ifdef INADDR_LOOPBACK
4736 PyModule_AddIntConstant(m
, "INADDR_LOOPBACK", INADDR_LOOPBACK
);
4738 PyModule_AddIntConstant(m
, "INADDR_LOOPBACK", 0x7F000001);
4740 #ifdef INADDR_UNSPEC_GROUP
4741 PyModule_AddIntConstant(m
, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP
);
4743 PyModule_AddIntConstant(m
, "INADDR_UNSPEC_GROUP", 0xe0000000);
4745 #ifdef INADDR_ALLHOSTS_GROUP
4746 PyModule_AddIntConstant(m
, "INADDR_ALLHOSTS_GROUP",
4747 INADDR_ALLHOSTS_GROUP
);
4749 PyModule_AddIntConstant(m
, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
4751 #ifdef INADDR_MAX_LOCAL_GROUP
4752 PyModule_AddIntConstant(m
, "INADDR_MAX_LOCAL_GROUP",
4753 INADDR_MAX_LOCAL_GROUP
);
4755 PyModule_AddIntConstant(m
, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
4758 PyModule_AddIntConstant(m
, "INADDR_NONE", INADDR_NONE
);
4760 PyModule_AddIntConstant(m
, "INADDR_NONE", 0xffffffff);
4763 /* IPv4 [gs]etsockopt options */
4765 PyModule_AddIntConstant(m
, "IP_OPTIONS", IP_OPTIONS
);
4768 PyModule_AddIntConstant(m
, "IP_HDRINCL", IP_HDRINCL
);
4771 PyModule_AddIntConstant(m
, "IP_TOS", IP_TOS
);
4774 PyModule_AddIntConstant(m
, "IP_TTL", IP_TTL
);
4777 PyModule_AddIntConstant(m
, "IP_RECVOPTS", IP_RECVOPTS
);
4779 #ifdef IP_RECVRETOPTS
4780 PyModule_AddIntConstant(m
, "IP_RECVRETOPTS", IP_RECVRETOPTS
);
4782 #ifdef IP_RECVDSTADDR
4783 PyModule_AddIntConstant(m
, "IP_RECVDSTADDR", IP_RECVDSTADDR
);
4786 PyModule_AddIntConstant(m
, "IP_RETOPTS", IP_RETOPTS
);
4788 #ifdef IP_MULTICAST_IF
4789 PyModule_AddIntConstant(m
, "IP_MULTICAST_IF", IP_MULTICAST_IF
);
4791 #ifdef IP_MULTICAST_TTL
4792 PyModule_AddIntConstant(m
, "IP_MULTICAST_TTL", IP_MULTICAST_TTL
);
4794 #ifdef IP_MULTICAST_LOOP
4795 PyModule_AddIntConstant(m
, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP
);
4797 #ifdef IP_ADD_MEMBERSHIP
4798 PyModule_AddIntConstant(m
, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP
);
4800 #ifdef IP_DROP_MEMBERSHIP
4801 PyModule_AddIntConstant(m
, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP
);
4803 #ifdef IP_DEFAULT_MULTICAST_TTL
4804 PyModule_AddIntConstant(m
, "IP_DEFAULT_MULTICAST_TTL",
4805 IP_DEFAULT_MULTICAST_TTL
);
4807 #ifdef IP_DEFAULT_MULTICAST_LOOP
4808 PyModule_AddIntConstant(m
, "IP_DEFAULT_MULTICAST_LOOP",
4809 IP_DEFAULT_MULTICAST_LOOP
);
4811 #ifdef IP_MAX_MEMBERSHIPS
4812 PyModule_AddIntConstant(m
, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS
);
4815 /* IPv6 [gs]etsockopt options, defined in RFC2553 */
4816 #ifdef IPV6_JOIN_GROUP
4817 PyModule_AddIntConstant(m
, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP
);
4819 #ifdef IPV6_LEAVE_GROUP
4820 PyModule_AddIntConstant(m
, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP
);
4822 #ifdef IPV6_MULTICAST_HOPS
4823 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS
);
4825 #ifdef IPV6_MULTICAST_IF
4826 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF
);
4828 #ifdef IPV6_MULTICAST_LOOP
4829 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP
);
4831 #ifdef IPV6_UNICAST_HOPS
4832 PyModule_AddIntConstant(m
, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS
);
4834 /* Additional IPV6 socket options, defined in RFC 3493 */
4836 PyModule_AddIntConstant(m
, "IPV6_V6ONLY", IPV6_V6ONLY
);
4838 /* Advanced IPV6 socket options, from RFC 3542 */
4839 #ifdef IPV6_CHECKSUM
4840 PyModule_AddIntConstant(m
, "IPV6_CHECKSUM", IPV6_CHECKSUM
);
4842 #ifdef IPV6_DONTFRAG
4843 PyModule_AddIntConstant(m
, "IPV6_DONTFRAG", IPV6_DONTFRAG
);
4846 PyModule_AddIntConstant(m
, "IPV6_DSTOPTS", IPV6_DSTOPTS
);
4848 #ifdef IPV6_HOPLIMIT
4849 PyModule_AddIntConstant(m
, "IPV6_HOPLIMIT", IPV6_HOPLIMIT
);
4852 PyModule_AddIntConstant(m
, "IPV6_HOPOPTS", IPV6_HOPOPTS
);
4855 PyModule_AddIntConstant(m
, "IPV6_NEXTHOP", IPV6_NEXTHOP
);
4858 PyModule_AddIntConstant(m
, "IPV6_PATHMTU", IPV6_PATHMTU
);
4861 PyModule_AddIntConstant(m
, "IPV6_PKTINFO", IPV6_PKTINFO
);
4863 #ifdef IPV6_RECVDSTOPTS
4864 PyModule_AddIntConstant(m
, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS
);
4866 #ifdef IPV6_RECVHOPLIMIT
4867 PyModule_AddIntConstant(m
, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT
);
4869 #ifdef IPV6_RECVHOPOPTS
4870 PyModule_AddIntConstant(m
, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS
);
4872 #ifdef IPV6_RECVPKTINFO
4873 PyModule_AddIntConstant(m
, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO
);
4875 #ifdef IPV6_RECVRTHDR
4876 PyModule_AddIntConstant(m
, "IPV6_RECVRTHDR", IPV6_RECVRTHDR
);
4878 #ifdef IPV6_RECVTCLASS
4879 PyModule_AddIntConstant(m
, "IPV6_RECVTCLASS", IPV6_RECVTCLASS
);
4882 PyModule_AddIntConstant(m
, "IPV6_RTHDR", IPV6_RTHDR
);
4884 #ifdef IPV6_RTHDRDSTOPTS
4885 PyModule_AddIntConstant(m
, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS
);
4887 #ifdef IPV6_RTHDR_TYPE_0
4888 PyModule_AddIntConstant(m
, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0
);
4890 #ifdef IPV6_RECVPATHMTU
4891 PyModule_AddIntConstant(m
, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU
);
4894 PyModule_AddIntConstant(m
, "IPV6_TCLASS", IPV6_TCLASS
);
4896 #ifdef IPV6_USE_MIN_MTU
4897 PyModule_AddIntConstant(m
, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU
);
4902 PyModule_AddIntConstant(m
, "TCP_NODELAY", TCP_NODELAY
);
4905 PyModule_AddIntConstant(m
, "TCP_MAXSEG", TCP_MAXSEG
);
4908 PyModule_AddIntConstant(m
, "TCP_CORK", TCP_CORK
);
4911 PyModule_AddIntConstant(m
, "TCP_KEEPIDLE", TCP_KEEPIDLE
);
4913 #ifdef TCP_KEEPINTVL
4914 PyModule_AddIntConstant(m
, "TCP_KEEPINTVL", TCP_KEEPINTVL
);
4917 PyModule_AddIntConstant(m
, "TCP_KEEPCNT", TCP_KEEPCNT
);
4920 PyModule_AddIntConstant(m
, "TCP_SYNCNT", TCP_SYNCNT
);
4923 PyModule_AddIntConstant(m
, "TCP_LINGER2", TCP_LINGER2
);
4925 #ifdef TCP_DEFER_ACCEPT
4926 PyModule_AddIntConstant(m
, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT
);
4928 #ifdef TCP_WINDOW_CLAMP
4929 PyModule_AddIntConstant(m
, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP
);
4932 PyModule_AddIntConstant(m
, "TCP_INFO", TCP_INFO
);
4935 PyModule_AddIntConstant(m
, "TCP_QUICKACK", TCP_QUICKACK
);
4941 PyModule_AddIntConstant(m
, "IPX_TYPE", IPX_TYPE
);
4944 /* get{addr,name}info parameters */
4945 #ifdef EAI_ADDRFAMILY
4946 PyModule_AddIntConstant(m
, "EAI_ADDRFAMILY", EAI_ADDRFAMILY
);
4949 PyModule_AddIntConstant(m
, "EAI_AGAIN", EAI_AGAIN
);
4952 PyModule_AddIntConstant(m
, "EAI_BADFLAGS", EAI_BADFLAGS
);
4955 PyModule_AddIntConstant(m
, "EAI_FAIL", EAI_FAIL
);
4958 PyModule_AddIntConstant(m
, "EAI_FAMILY", EAI_FAMILY
);
4961 PyModule_AddIntConstant(m
, "EAI_MEMORY", EAI_MEMORY
);
4964 PyModule_AddIntConstant(m
, "EAI_NODATA", EAI_NODATA
);
4967 PyModule_AddIntConstant(m
, "EAI_NONAME", EAI_NONAME
);
4970 PyModule_AddIntConstant(m
, "EAI_OVERFLOW", EAI_OVERFLOW
);
4973 PyModule_AddIntConstant(m
, "EAI_SERVICE", EAI_SERVICE
);
4976 PyModule_AddIntConstant(m
, "EAI_SOCKTYPE", EAI_SOCKTYPE
);
4979 PyModule_AddIntConstant(m
, "EAI_SYSTEM", EAI_SYSTEM
);
4982 PyModule_AddIntConstant(m
, "EAI_BADHINTS", EAI_BADHINTS
);
4985 PyModule_AddIntConstant(m
, "EAI_PROTOCOL", EAI_PROTOCOL
);
4988 PyModule_AddIntConstant(m
, "EAI_MAX", EAI_MAX
);
4991 PyModule_AddIntConstant(m
, "AI_PASSIVE", AI_PASSIVE
);
4994 PyModule_AddIntConstant(m
, "AI_CANONNAME", AI_CANONNAME
);
4996 #ifdef AI_NUMERICHOST
4997 PyModule_AddIntConstant(m
, "AI_NUMERICHOST", AI_NUMERICHOST
);
4999 #ifdef AI_NUMERICSERV
5000 PyModule_AddIntConstant(m
, "AI_NUMERICSERV", AI_NUMERICSERV
);
5003 PyModule_AddIntConstant(m
, "AI_MASK", AI_MASK
);
5006 PyModule_AddIntConstant(m
, "AI_ALL", AI_ALL
);
5008 #ifdef AI_V4MAPPED_CFG
5009 PyModule_AddIntConstant(m
, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG
);
5011 #ifdef AI_ADDRCONFIG
5012 PyModule_AddIntConstant(m
, "AI_ADDRCONFIG", AI_ADDRCONFIG
);
5015 PyModule_AddIntConstant(m
, "AI_V4MAPPED", AI_V4MAPPED
);
5018 PyModule_AddIntConstant(m
, "AI_DEFAULT", AI_DEFAULT
);
5021 PyModule_AddIntConstant(m
, "NI_MAXHOST", NI_MAXHOST
);
5024 PyModule_AddIntConstant(m
, "NI_MAXSERV", NI_MAXSERV
);
5027 PyModule_AddIntConstant(m
, "NI_NOFQDN", NI_NOFQDN
);
5029 #ifdef NI_NUMERICHOST
5030 PyModule_AddIntConstant(m
, "NI_NUMERICHOST", NI_NUMERICHOST
);
5033 PyModule_AddIntConstant(m
, "NI_NAMEREQD", NI_NAMEREQD
);
5035 #ifdef NI_NUMERICSERV
5036 PyModule_AddIntConstant(m
, "NI_NUMERICSERV", NI_NUMERICSERV
);
5039 PyModule_AddIntConstant(m
, "NI_DGRAM", NI_DGRAM
);
5042 /* shutdown() parameters */
5044 PyModule_AddIntConstant(m
, "SHUT_RD", SHUT_RD
);
5045 #elif defined(SD_RECEIVE)
5046 PyModule_AddIntConstant(m
, "SHUT_RD", SD_RECEIVE
);
5048 PyModule_AddIntConstant(m
, "SHUT_RD", 0);
5051 PyModule_AddIntConstant(m
, "SHUT_WR", SHUT_WR
);
5052 #elif defined(SD_SEND)
5053 PyModule_AddIntConstant(m
, "SHUT_WR", SD_SEND
);
5055 PyModule_AddIntConstant(m
, "SHUT_WR", 1);
5058 PyModule_AddIntConstant(m
, "SHUT_RDWR", SHUT_RDWR
);
5059 #elif defined(SD_BOTH)
5060 PyModule_AddIntConstant(m
, "SHUT_RDWR", SD_BOTH
);
5062 PyModule_AddIntConstant(m
, "SHUT_RDWR", 2);
5065 /* Initialize gethostbyname lock */
5066 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
5067 netdb_lock
= PyThread_allocate_lock();
5072 #ifndef HAVE_INET_PTON
5074 /* Simplistic emulation code for inet_pton that only works for IPv4 */
5075 /* These are not exposed because they do not set errno properly */
5078 inet_pton(int af
, const char *src
, void *dst
)
5080 if (af
== AF_INET
) {
5082 packed_addr
= inet_addr(src
);
5083 if (packed_addr
== INADDR_NONE
)
5085 memcpy(dst
, &packed_addr
, 4);
5088 /* Should set errno to EAFNOSUPPORT */
5093 inet_ntop(int af
, const void *src
, char *dst
, socklen_t size
)
5095 if (af
== AF_INET
) {
5096 struct in_addr packed_addr
;
5098 /* Should set errno to ENOSPC. */
5100 memcpy(&packed_addr
, src
, sizeof(packed_addr
));
5101 return strncpy(dst
, inet_ntoa(packed_addr
), size
);
5103 /* Should set errno to EAFNOSUPPORT */