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 BTPROTO_HCI BLUETOOTH_PROTO_HCI
366 #define sockaddr_l2 sockaddr_l2cap
367 #define sockaddr_rc sockaddr_rfcomm
368 #define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb)
369 #define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)
370 #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
371 #elif defined(__NetBSD__)
372 #define sockaddr_l2 sockaddr_bt
373 #define sockaddr_rc sockaddr_bt
374 #define sockaddr_hci sockaddr_bt
375 #define sockaddr_sco sockaddr_bt
376 #define _BT_L2_MEMB(sa, memb) ((sa)->bt_##memb)
377 #define _BT_RC_MEMB(sa, memb) ((sa)->bt_##memb)
378 #define _BT_HCI_MEMB(sa, memb) ((sa)->bt_##memb)
379 #define _BT_SCO_MEMB(sa, memb) ((sa)->bt_##memb)
381 #define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb)
382 #define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb)
383 #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
384 #define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)
389 /* TCP/IP Services for VMS uses a maximum send/recv buffer length */
390 #define SEGMENT_SIZE (32 * 1024 -1)
393 #define SAS2SA(x) ((struct sockaddr *)(x))
396 * Constants for getnameinfo()
398 #if !defined(NI_MAXHOST)
399 #define NI_MAXHOST 1025
401 #if !defined(NI_MAXSERV)
402 #define NI_MAXSERV 32
405 /* XXX There's a problem here: *static* functions are not supposed to have
406 a Py prefix (or use CapitalizedWords). Later... */
408 /* Global variable holding the exception type for errors detected
409 by this module (but not argument type or memory errors, etc.). */
410 static PyObject
*socket_error
;
411 static PyObject
*socket_herror
;
412 static PyObject
*socket_gaierror
;
413 static PyObject
*socket_timeout
;
416 /* Global variable which is !=0 if Python is running in a RISC OS taskwindow */
417 static int taskwindow
;
420 /* A forward reference to the socket type object.
421 The sock_type variable contains pointers to various functions,
422 some of which call new_sockobject(), which uses sock_type, so
423 there has to be a circular reference. */
424 static PyTypeObject sock_type
;
426 #if defined(HAVE_POLL_H)
428 #elif defined(HAVE_SYS_POLL_H)
429 #include <sys/poll.h>
432 #ifdef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
433 /* Platform can select file descriptors beyond FD_SETSIZE */
434 #define IS_SELECTABLE(s) 1
435 #elif defined(HAVE_POLL)
436 /* Instead of select(), we'll use poll() since poll() works on any fd. */
437 #define IS_SELECTABLE(s) 1
438 /* Can we call select() with this socket without a buffer overrun? */
440 /* POSIX says selecting file descriptors beyond FD_SETSIZE
441 has undefined behaviour. If there's no timeout left, we don't have to
442 call select, so it's a safe, little white lie. */
443 #define IS_SELECTABLE(s) ((s)->sock_fd < FD_SETSIZE || s->sock_timeout <= 0.0)
449 PyErr_SetString(socket_error
, "unable to select on socket");
453 /* Convenience function to raise an error according to errno
454 and return a NULL pointer from a function. */
460 int err_no
= WSAGetLastError();
465 {WSAEINTR
, "Interrupted system call"},
466 {WSAEBADF
, "Bad file descriptor"},
467 {WSAEACCES
, "Permission denied"},
468 {WSAEFAULT
, "Bad address"},
469 {WSAEINVAL
, "Invalid argument"},
470 {WSAEMFILE
, "Too many open files"},
472 "The socket operation could not complete "
474 {WSAEINPROGRESS
, "Operation now in progress"},
475 {WSAEALREADY
, "Operation already in progress"},
476 {WSAENOTSOCK
, "Socket operation on non-socket"},
477 {WSAEDESTADDRREQ
, "Destination address required"},
478 {WSAEMSGSIZE
, "Message too long"},
479 {WSAEPROTOTYPE
, "Protocol wrong type for socket"},
480 {WSAENOPROTOOPT
, "Protocol not available"},
481 {WSAEPROTONOSUPPORT
, "Protocol not supported"},
482 {WSAESOCKTNOSUPPORT
, "Socket type not supported"},
483 {WSAEOPNOTSUPP
, "Operation not supported"},
484 {WSAEPFNOSUPPORT
, "Protocol family not supported"},
485 {WSAEAFNOSUPPORT
, "Address family not supported"},
486 {WSAEADDRINUSE
, "Address already in use"},
487 {WSAEADDRNOTAVAIL
, "Can't assign requested address"},
488 {WSAENETDOWN
, "Network is down"},
489 {WSAENETUNREACH
, "Network is unreachable"},
490 {WSAENETRESET
, "Network dropped connection on reset"},
491 {WSAECONNABORTED
, "Software caused connection abort"},
492 {WSAECONNRESET
, "Connection reset by peer"},
493 {WSAENOBUFS
, "No buffer space available"},
494 {WSAEISCONN
, "Socket is already connected"},
495 {WSAENOTCONN
, "Socket is not connected"},
496 {WSAESHUTDOWN
, "Can't send after socket shutdown"},
497 {WSAETOOMANYREFS
, "Too many references: can't splice"},
498 {WSAETIMEDOUT
, "Operation timed out"},
499 {WSAECONNREFUSED
, "Connection refused"},
500 {WSAELOOP
, "Too many levels of symbolic links"},
501 {WSAENAMETOOLONG
, "File name too long"},
502 {WSAEHOSTDOWN
, "Host is down"},
503 {WSAEHOSTUNREACH
, "No route to host"},
504 {WSAENOTEMPTY
, "Directory not empty"},
505 {WSAEPROCLIM
, "Too many processes"},
506 {WSAEUSERS
, "Too many users"},
507 {WSAEDQUOT
, "Disc quota exceeded"},
508 {WSAESTALE
, "Stale NFS file handle"},
509 {WSAEREMOTE
, "Too many levels of remote in path"},
510 {WSASYSNOTREADY
, "Network subsystem is unvailable"},
511 {WSAVERNOTSUPPORTED
, "WinSock version is not supported"},
513 "Successful WSAStartup() not yet performed"},
514 {WSAEDISCON
, "Graceful shutdown in progress"},
515 /* Resolver errors */
516 {WSAHOST_NOT_FOUND
, "No such host is known"},
517 {WSATRY_AGAIN
, "Host not found, or server failed"},
518 {WSANO_RECOVERY
, "Unexpected server error encountered"},
519 {WSANO_DATA
, "Valid name without requested data"},
520 {WSANO_ADDRESS
, "No address, look for MX record"},
525 const char *msg
= "winsock error";
527 for (msgp
= msgs
; msgp
->msg
; msgp
++) {
528 if (err_no
== msgp
->no
) {
534 v
= Py_BuildValue("(is)", err_no
, msg
);
536 PyErr_SetObject(socket_error
, v
);
544 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
545 if (sock_errno() != NO_ERROR
) {
549 int myerrorcode
= sock_errno();
551 /* Retrieve socket-related error message from MPTN.MSG file */
552 rc
= DosGetMessage(NULL
, 0, outbuf
, sizeof(outbuf
),
553 myerrorcode
- SOCBASEERR
+ 26,
556 if (rc
== NO_ERROR
) {
559 /* OS/2 doesn't guarantee a terminator */
560 outbuf
[msglen
] = '\0';
561 if (strlen(outbuf
) > 0) {
562 /* If non-empty msg, trim CRLF */
563 char *lastc
= &outbuf
[ strlen(outbuf
)-1 ];
564 while (lastc
> outbuf
&&
565 isspace(Py_CHARMASK(*lastc
))) {
566 /* Trim trailing whitespace (CRLF) */
570 v
= Py_BuildValue("(is)", myerrorcode
, outbuf
);
572 PyErr_SetObject(socket_error
, v
);
581 if (_inet_error
.errnum
!= NULL
) {
583 v
= Py_BuildValue("(is)", errno
, _inet_err());
585 PyErr_SetObject(socket_error
, v
);
592 return PyErr_SetFromErrno(socket_error
);
597 set_herror(int h_error
)
601 #ifdef HAVE_HSTRERROR
602 v
= Py_BuildValue("(is)", h_error
, (char *)hstrerror(h_error
));
604 v
= Py_BuildValue("(is)", h_error
, "host not found");
607 PyErr_SetObject(socket_herror
, v
);
616 set_gaierror(int error
)
621 /* EAI_SYSTEM is not available on Windows XP. */
622 if (error
== EAI_SYSTEM
)
626 #ifdef HAVE_GAI_STRERROR
627 v
= Py_BuildValue("(is)", error
, gai_strerror(error
));
629 v
= Py_BuildValue("(is)", error
, "getaddrinfo failed");
632 PyErr_SetObject(socket_gaierror
, v
);
640 /* Function to send in segments */
642 sendsegmented(int sock_fd
, char *buf
, int len
, int flags
)
647 while (remaining
> 0) {
648 unsigned int segment
;
650 segment
= (remaining
>= SEGMENT_SIZE
? SEGMENT_SIZE
: remaining
);
651 n
= send(sock_fd
, buf
, segment
, flags
);
655 remaining
-= segment
;
663 /* Function to perform the setting of socket blocking mode
664 internally. block = (1 | 0). */
666 internal_setblocking(PySocketSockObject
*s
, int block
)
674 Py_BEGIN_ALLOW_THREADS
677 setsockopt(s
->sock_fd
, SOL_SOCKET
, SO_NONBLOCK
,
678 (void *)(&block
), sizeof(int));
682 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
684 ioctl(s
->sock_fd
, FIONBIO
, (caddr_t
)&block
, sizeof(block
));
687 ioctl(s
->sock_fd
, FIONBIO
, (unsigned int *)&block
);
688 #else /* !PYOS_OS2 && !__VMS */
689 delay_flag
= fcntl(s
->sock_fd
, F_GETFL
, 0);
691 delay_flag
&= (~O_NONBLOCK
);
693 delay_flag
|= O_NONBLOCK
;
694 fcntl(s
->sock_fd
, F_SETFL
, delay_flag
);
695 #endif /* !PYOS_OS2 */
696 #else /* MS_WINDOWS */
698 ioctlsocket(s
->sock_fd
, FIONBIO
, (u_long
*)&block
);
699 #endif /* MS_WINDOWS */
702 socketioctl(s
->sock_fd
, FIONBIO
, (u_long
*)&block
);
704 #endif /* __BEOS__ */
707 /* Since these don't return anything */
711 /* Do a select()/poll() on the socket, if necessary (sock_timeout > 0).
712 The argument writing indicates the direction.
713 This does not raise an exception; we'll let our caller do that
714 after they've reacquired the interpreter lock.
715 Returns 1 on timeout, -1 on error, 0 otherwise. */
717 internal_select(PySocketSockObject
*s
, int writing
)
721 /* Nothing to do unless we're in timeout mode (not non-blocking) */
722 if (s
->sock_timeout
<= 0.0)
725 /* Guard against closed socket */
729 /* Prefer poll, if available, since you can poll() any fd
730 * which can't be done with select(). */
733 struct pollfd pollfd
;
736 pollfd
.fd
= s
->sock_fd
;
737 pollfd
.events
= writing
? POLLOUT
: POLLIN
;
739 /* s->sock_timeout is in seconds, timeout in ms */
740 timeout
= (int)(s
->sock_timeout
* 1000 + 0.5);
741 n
= poll(&pollfd
, 1, timeout
);
745 /* Construct the arguments to select */
748 tv
.tv_sec
= (int)s
->sock_timeout
;
749 tv
.tv_usec
= (int)((s
->sock_timeout
- tv
.tv_sec
) * 1e6
);
751 FD_SET(s
->sock_fd
, &fds
);
753 /* See if the socket is ready */
755 n
= select(s
->sock_fd
+1, NULL
, &fds
, NULL
, &tv
);
757 n
= select(s
->sock_fd
+1, &fds
, NULL
, NULL
, &tv
);
768 /* Initialize a new socket object. */
770 static double defaulttimeout
= -1.0; /* Default timeout for new sockets */
773 init_sockobject(PySocketSockObject
*s
,
774 SOCKET_T fd
, int family
, int type
, int proto
)
780 s
->sock_family
= family
;
782 s
->sock_proto
= proto
;
783 s
->sock_timeout
= defaulttimeout
;
785 s
->errorhandler
= &set_error
;
787 if (defaulttimeout
>= 0.0)
788 internal_setblocking(s
, 0);
792 socketioctl(s
->sock_fd
, 0x80046679, (u_long
*)&block
);
797 /* Create a new socket object.
798 This just creates the object and initializes it.
799 If the creation fails, return NULL and set an exception (implicit
802 static PySocketSockObject
*
803 new_sockobject(SOCKET_T fd
, int family
, int type
, int proto
)
805 PySocketSockObject
*s
;
806 s
= (PySocketSockObject
*)
807 PyType_GenericNew(&sock_type
, NULL
, NULL
);
809 init_sockobject(s
, fd
, family
, type
, proto
);
814 /* Lock to allow python interpreter to continue, but only allow one
815 thread to be in gethostbyname or getaddrinfo */
816 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
817 PyThread_type_lock netdb_lock
;
821 /* Convert a string specifying a host name or one of a few symbolic
822 names to a numeric IP address. This usually calls gethostbyname()
823 to do the work; the names "" and "<broadcast>" are special.
824 Return the length (IPv4 should be 4 bytes), or negative if
825 an error occurred; then an exception is raised. */
828 setipaddr(char *name
, struct sockaddr
*addr_ret
, size_t addr_ret_size
, int af
)
830 struct addrinfo hints
, *res
;
835 memset((void *) addr_ret
, '\0', sizeof(*addr_ret
));
836 if (name
[0] == '\0') {
838 memset(&hints
, 0, sizeof(hints
));
839 hints
.ai_family
= af
;
840 hints
.ai_socktype
= SOCK_DGRAM
; /*dummy*/
841 hints
.ai_flags
= AI_PASSIVE
;
842 Py_BEGIN_ALLOW_THREADS
843 ACQUIRE_GETADDRINFO_LOCK
844 error
= getaddrinfo(NULL
, "0", &hints
, &res
);
846 /* We assume that those thread-unsafe getaddrinfo() versions
847 *are* safe regarding their return value, ie. that a
848 subsequent call to getaddrinfo() does not destroy the
849 outcome of the first call. */
850 RELEASE_GETADDRINFO_LOCK
855 switch (res
->ai_family
) {
866 PyErr_SetString(socket_error
,
867 "unsupported address family");
872 PyErr_SetString(socket_error
,
873 "wildcard resolved to multiple address");
876 if (res
->ai_addrlen
< addr_ret_size
)
877 addr_ret_size
= res
->ai_addrlen
;
878 memcpy(addr_ret
, res
->ai_addr
, addr_ret_size
);
882 if (name
[0] == '<' && strcmp(name
, "<broadcast>") == 0) {
883 struct sockaddr_in
*sin
;
884 if (af
!= AF_INET
&& af
!= AF_UNSPEC
) {
885 PyErr_SetString(socket_error
,
886 "address family mismatched");
889 sin
= (struct sockaddr_in
*)addr_ret
;
890 memset((void *) sin
, '\0', sizeof(*sin
));
891 sin
->sin_family
= AF_INET
;
892 #ifdef HAVE_SOCKADDR_SA_LEN
893 sin
->sin_len
= sizeof(*sin
);
895 sin
->sin_addr
.s_addr
= INADDR_BROADCAST
;
896 return sizeof(sin
->sin_addr
);
898 if (sscanf(name
, "%d.%d.%d.%d%c", &d1
, &d2
, &d3
, &d4
, &ch
) == 4 &&
899 0 <= d1
&& d1
<= 255 && 0 <= d2
&& d2
<= 255 &&
900 0 <= d3
&& d3
<= 255 && 0 <= d4
&& d4
<= 255) {
901 struct sockaddr_in
*sin
;
902 sin
= (struct sockaddr_in
*)addr_ret
;
903 sin
->sin_addr
.s_addr
= htonl(
904 ((long) d1
<< 24) | ((long) d2
<< 16) |
905 ((long) d3
<< 8) | ((long) d4
<< 0));
906 sin
->sin_family
= AF_INET
;
907 #ifdef HAVE_SOCKADDR_SA_LEN
908 sin
->sin_len
= sizeof(*sin
);
912 memset(&hints
, 0, sizeof(hints
));
913 hints
.ai_family
= af
;
914 Py_BEGIN_ALLOW_THREADS
915 ACQUIRE_GETADDRINFO_LOCK
916 error
= getaddrinfo(name
, NULL
, &hints
, &res
);
917 #if defined(__digital__) && defined(__unix__)
918 if (error
== EAI_NONAME
&& af
== AF_UNSPEC
) {
919 /* On Tru64 V5.1, numeric-to-addr conversion fails
920 if no address family is given. Assume IPv4 for now.*/
921 hints
.ai_family
= AF_INET
;
922 error
= getaddrinfo(name
, NULL
, &hints
, &res
);
926 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
931 if (res
->ai_addrlen
< addr_ret_size
)
932 addr_ret_size
= res
->ai_addrlen
;
933 memcpy((char *) addr_ret
, res
->ai_addr
, addr_ret_size
);
935 switch (addr_ret
->sa_family
) {
943 PyErr_SetString(socket_error
, "unknown address family");
949 /* Create a string object representing an IP address.
950 This is always a string of the form 'dd.dd.dd.dd' (with variable
954 makeipaddr(struct sockaddr
*addr
, int addrlen
)
956 char buf
[NI_MAXHOST
];
959 error
= getnameinfo(addr
, addrlen
, buf
, sizeof(buf
), NULL
, 0,
965 return PyString_FromString(buf
);
970 /* Convert a string representation of a Bluetooth address into a numeric
971 address. Returns the length (6), or raises an exception and returns -1 if
972 an error occurred. */
975 setbdaddr(char *name
, bdaddr_t
*bdaddr
)
977 unsigned int b0
, b1
, b2
, b3
, b4
, b5
;
981 n
= sscanf(name
, "%X:%X:%X:%X:%X:%X%c",
982 &b5
, &b4
, &b3
, &b2
, &b1
, &b0
, &ch
);
983 if (n
== 6 && (b0
| b1
| b2
| b3
| b4
| b5
) < 256) {
992 PyErr_SetString(socket_error
, "bad bluetooth address");
997 /* Create a string representation of the Bluetooth address. This is always a
998 string of the form 'XX:XX:XX:XX:XX:XX' where XX is a two digit hexadecimal
999 value (zero padded if necessary). */
1002 makebdaddr(bdaddr_t
*bdaddr
)
1004 char buf
[(6 * 2) + 5 + 1];
1006 sprintf(buf
, "%02X:%02X:%02X:%02X:%02X:%02X",
1007 bdaddr
->b
[5], bdaddr
->b
[4], bdaddr
->b
[3],
1008 bdaddr
->b
[2], bdaddr
->b
[1], bdaddr
->b
[0]);
1009 return PyString_FromString(buf
);
1014 /* Create an object representing the given socket address,
1015 suitable for passing it back to bind(), connect() etc.
1016 The family field of the sockaddr structure is inspected
1017 to determine what kind of address it really is. */
1021 makesockaddr(int sockfd
, struct sockaddr
*addr
, int addrlen
, int proto
)
1024 /* No address -- may be recvfrom() from known socket */
1030 /* XXX: BeOS version of accept() doesn't set family correctly */
1031 addr
->sa_family
= AF_INET
;
1034 switch (addr
->sa_family
) {
1038 struct sockaddr_in
*a
;
1039 PyObject
*addrobj
= makeipaddr(addr
, sizeof(*a
));
1040 PyObject
*ret
= NULL
;
1042 a
= (struct sockaddr_in
*)addr
;
1043 ret
= Py_BuildValue("Oi", addrobj
, ntohs(a
->sin_port
));
1049 #if defined(AF_UNIX)
1052 struct sockaddr_un
*a
= (struct sockaddr_un
*) addr
;
1054 if (a
->sun_path
[0] == 0) { /* Linux abstract namespace */
1055 addrlen
-= (sizeof(*a
) - sizeof(a
->sun_path
));
1056 return PyString_FromStringAndSize(a
->sun_path
,
1062 /* regular NULL-terminated string */
1063 return PyString_FromString(a
->sun_path
);
1066 #endif /* AF_UNIX */
1068 #if defined(AF_NETLINK)
1071 struct sockaddr_nl
*a
= (struct sockaddr_nl
*) addr
;
1072 return Py_BuildValue("II", a
->nl_pid
, a
->nl_groups
);
1074 #endif /* AF_NETLINK */
1079 struct sockaddr_in6
*a
;
1080 PyObject
*addrobj
= makeipaddr(addr
, sizeof(*a
));
1081 PyObject
*ret
= NULL
;
1083 a
= (struct sockaddr_in6
*)addr
;
1084 ret
= Py_BuildValue("Oiii",
1086 ntohs(a
->sin6_port
),
1095 #ifdef USE_BLUETOOTH
1101 struct sockaddr_l2
*a
= (struct sockaddr_l2
*) addr
;
1102 PyObject
*addrobj
= makebdaddr(&_BT_L2_MEMB(a
, bdaddr
));
1103 PyObject
*ret
= NULL
;
1105 ret
= Py_BuildValue("Oi",
1107 _BT_L2_MEMB(a
, psm
));
1113 case BTPROTO_RFCOMM
:
1115 struct sockaddr_rc
*a
= (struct sockaddr_rc
*) addr
;
1116 PyObject
*addrobj
= makebdaddr(&_BT_RC_MEMB(a
, bdaddr
));
1117 PyObject
*ret
= NULL
;
1119 ret
= Py_BuildValue("Oi",
1121 _BT_RC_MEMB(a
, channel
));
1129 struct sockaddr_hci
*a
= (struct sockaddr_hci
*) addr
;
1130 PyObject
*ret
= NULL
;
1131 ret
= Py_BuildValue("i", _BT_HCI_MEMB(a
, dev
));
1135 #if !defined(__FreeBSD__)
1138 struct sockaddr_sco
*a
= (struct sockaddr_sco
*) addr
;
1139 return makebdaddr(&_BT_SCO_MEMB(a
, bdaddr
));
1146 #ifdef HAVE_NETPACKET_PACKET_H
1149 struct sockaddr_ll
*a
= (struct sockaddr_ll
*)addr
;
1152 /* need to look up interface name give index */
1153 if (a
->sll_ifindex
) {
1154 ifr
.ifr_ifindex
= a
->sll_ifindex
;
1155 if (ioctl(sockfd
, SIOCGIFNAME
, &ifr
) == 0)
1156 ifname
= ifr
.ifr_name
;
1158 return Py_BuildValue("shbhs#",
1160 ntohs(a
->sll_protocol
),
1168 /* More cases here... */
1171 /* If we don't know the address family, don't raise an
1172 exception -- return it as a tuple. */
1173 return Py_BuildValue("is#",
1176 sizeof(addr
->sa_data
));
1182 /* Parse a socket address argument according to the socket object's
1183 address family. Return 1 if the address was in the proper format,
1184 0 of not. The address is returned through addr_ret, its length
1188 getsockaddrarg(PySocketSockObject
*s
, PyObject
*args
,
1189 struct sockaddr
*addr_ret
, int *len_ret
)
1191 switch (s
->sock_family
) {
1193 #if defined(AF_UNIX)
1196 struct sockaddr_un
* addr
;
1199 if (!PyArg_Parse(args
, "t#", &path
, &len
))
1202 addr
= (struct sockaddr_un
*)addr_ret
;
1204 if (len
> 0 && path
[0] == 0) {
1205 /* Linux abstract namespace extension */
1206 if (len
> sizeof addr
->sun_path
) {
1207 PyErr_SetString(socket_error
,
1208 "AF_UNIX path too long");
1215 /* regular NULL-terminated string */
1216 if (len
>= sizeof addr
->sun_path
) {
1217 PyErr_SetString(socket_error
,
1218 "AF_UNIX path too long");
1221 addr
->sun_path
[len
] = 0;
1223 addr
->sun_family
= s
->sock_family
;
1224 memcpy(addr
->sun_path
, path
, len
);
1225 #if defined(PYOS_OS2)
1226 *len_ret
= sizeof(*addr
);
1228 *len_ret
= len
+ sizeof(*addr
) - sizeof(addr
->sun_path
);
1232 #endif /* AF_UNIX */
1234 #if defined(AF_NETLINK)
1237 struct sockaddr_nl
* addr
;
1239 addr
= (struct sockaddr_nl
*)addr_ret
;
1240 if (!PyTuple_Check(args
)) {
1244 "AF_NETLINK address must be tuple, not %.500s",
1245 args
->ob_type
->tp_name
);
1248 if (!PyArg_ParseTuple(args
, "II:getsockaddrarg", &pid
, &groups
))
1250 addr
->nl_family
= AF_NETLINK
;
1252 addr
->nl_groups
= groups
;
1253 *len_ret
= sizeof(*addr
);
1260 struct sockaddr_in
* addr
;
1263 if (!PyTuple_Check(args
)) {
1267 "AF_INET address must be tuple, not %.500s",
1268 args
->ob_type
->tp_name
);
1271 if (!PyArg_ParseTuple(args
, "eti:getsockaddrarg",
1272 "idna", &host
, &port
))
1274 addr
=(struct sockaddr_in
*)addr_ret
;
1275 result
= setipaddr(host
, (struct sockaddr
*)addr
,
1276 sizeof(*addr
), AF_INET
);
1280 addr
->sin_family
= AF_INET
;
1281 addr
->sin_port
= htons((short)port
);
1282 *len_ret
= sizeof *addr
;
1289 struct sockaddr_in6
* addr
;
1291 int port
, flowinfo
, scope_id
, result
;
1292 flowinfo
= scope_id
= 0;
1293 if (!PyTuple_Check(args
)) {
1297 "AF_INET6 address must be tuple, not %.500s",
1298 args
->ob_type
->tp_name
);
1301 if (!PyArg_ParseTuple(args
, "eti|ii",
1302 "idna", &host
, &port
, &flowinfo
,
1306 addr
= (struct sockaddr_in6
*)addr_ret
;
1307 result
= setipaddr(host
, (struct sockaddr
*)addr
,
1308 sizeof(*addr
), AF_INET6
);
1312 addr
->sin6_family
= s
->sock_family
;
1313 addr
->sin6_port
= htons((short)port
);
1314 addr
->sin6_flowinfo
= flowinfo
;
1315 addr
->sin6_scope_id
= scope_id
;
1316 *len_ret
= sizeof *addr
;
1321 #ifdef USE_BLUETOOTH
1324 switch (s
->sock_proto
) {
1327 struct sockaddr_l2
*addr
;
1330 addr
= (struct sockaddr_l2
*)addr_ret
;
1331 _BT_L2_MEMB(addr
, family
) = AF_BLUETOOTH
;
1332 if (!PyArg_ParseTuple(args
, "si", &straddr
,
1333 &_BT_L2_MEMB(addr
, psm
))) {
1334 PyErr_SetString(socket_error
, "getsockaddrarg: "
1338 if (setbdaddr(straddr
, &_BT_L2_MEMB(addr
, bdaddr
)) < 0)
1341 *len_ret
= sizeof *addr
;
1344 case BTPROTO_RFCOMM
:
1346 struct sockaddr_rc
*addr
;
1349 addr
= (struct sockaddr_rc
*)addr_ret
;
1350 _BT_RC_MEMB(addr
, family
) = AF_BLUETOOTH
;
1351 if (!PyArg_ParseTuple(args
, "si", &straddr
,
1352 &_BT_RC_MEMB(addr
, channel
))) {
1353 PyErr_SetString(socket_error
, "getsockaddrarg: "
1357 if (setbdaddr(straddr
, &_BT_RC_MEMB(addr
, bdaddr
)) < 0)
1360 *len_ret
= sizeof *addr
;
1365 struct sockaddr_hci
*addr
= (struct sockaddr_hci
*)addr_ret
;
1366 _BT_HCI_MEMB(addr
, family
) = AF_BLUETOOTH
;
1367 if (!PyArg_ParseTuple(args
, "i", &_BT_HCI_MEMB(addr
, dev
))) {
1368 PyErr_SetString(socket_error
, "getsockaddrarg: "
1372 *len_ret
= sizeof *addr
;
1375 #if !defined(__FreeBSD__)
1378 struct sockaddr_sco
*addr
;
1381 addr
= (struct sockaddr_sco
*)addr_ret
;
1382 _BT_SCO_MEMB(addr
, family
) = AF_BLUETOOTH
;
1383 straddr
= PyString_AsString(args
);
1384 if (straddr
== NULL
) {
1385 PyErr_SetString(socket_error
, "getsockaddrarg: "
1389 if (setbdaddr(straddr
, &_BT_SCO_MEMB(addr
, bdaddr
)) < 0)
1392 *len_ret
= sizeof *addr
;
1397 PyErr_SetString(socket_error
, "getsockaddrarg: unknown Bluetooth protocol");
1403 #ifdef HAVE_NETPACKET_PACKET_H
1406 struct sockaddr_ll
* addr
;
1408 char *interfaceName
;
1413 unsigned int halen
= 0;
1415 if (!PyTuple_Check(args
)) {
1419 "AF_PACKET address must be tuple, not %.500s",
1420 args
->ob_type
->tp_name
);
1423 if (!PyArg_ParseTuple(args
, "si|iis#", &interfaceName
,
1424 &protoNumber
, &pkttype
, &hatype
,
1427 strncpy(ifr
.ifr_name
, interfaceName
, sizeof(ifr
.ifr_name
));
1428 ifr
.ifr_name
[(sizeof(ifr
.ifr_name
))-1] = '\0';
1429 if (ioctl(s
->sock_fd
, SIOCGIFINDEX
, &ifr
) < 0) {
1434 PyErr_SetString(PyExc_ValueError
,
1435 "Hardware address must be 8 bytes or less");
1438 addr
= (struct sockaddr_ll
*)addr_ret
;
1439 addr
->sll_family
= AF_PACKET
;
1440 addr
->sll_protocol
= htons((short)protoNumber
);
1441 addr
->sll_ifindex
= ifr
.ifr_ifindex
;
1442 addr
->sll_pkttype
= pkttype
;
1443 addr
->sll_hatype
= hatype
;
1445 memcpy(&addr
->sll_addr
, haddr
, halen
);
1447 addr
->sll_halen
= halen
;
1448 *len_ret
= sizeof *addr
;
1453 /* More cases here... */
1456 PyErr_SetString(socket_error
, "getsockaddrarg: bad family");
1463 /* Get the address length according to the socket object's address family.
1464 Return 1 if the family is known, 0 otherwise. The length is returned
1468 getsockaddrlen(PySocketSockObject
*s
, socklen_t
*len_ret
)
1470 switch (s
->sock_family
) {
1472 #if defined(AF_UNIX)
1475 *len_ret
= sizeof (struct sockaddr_un
);
1478 #endif /* AF_UNIX */
1479 #if defined(AF_NETLINK)
1482 *len_ret
= sizeof (struct sockaddr_nl
);
1489 *len_ret
= sizeof (struct sockaddr_in
);
1496 *len_ret
= sizeof (struct sockaddr_in6
);
1501 #ifdef USE_BLUETOOTH
1504 switch(s
->sock_proto
)
1508 *len_ret
= sizeof (struct sockaddr_l2
);
1510 case BTPROTO_RFCOMM
:
1511 *len_ret
= sizeof (struct sockaddr_rc
);
1514 *len_ret
= sizeof (struct sockaddr_hci
);
1516 #if !defined(__FreeBSD__)
1518 *len_ret
= sizeof (struct sockaddr_sco
);
1522 PyErr_SetString(socket_error
, "getsockaddrlen: "
1523 "unknown BT protocol");
1530 #ifdef HAVE_NETPACKET_PACKET_H
1533 *len_ret
= sizeof (struct sockaddr_ll
);
1538 /* More cases here... */
1541 PyErr_SetString(socket_error
, "getsockaddrlen: bad family");
1548 /* s.accept() method */
1551 sock_accept(PySocketSockObject
*s
)
1553 sock_addr_t addrbuf
;
1556 PyObject
*sock
= NULL
;
1557 PyObject
*addr
= NULL
;
1558 PyObject
*res
= NULL
;
1561 if (!getsockaddrlen(s
, &addrlen
))
1563 memset(&addrbuf
, 0, addrlen
);
1566 newfd
= INVALID_SOCKET
;
1571 if (!IS_SELECTABLE(s
))
1572 return select_error();
1574 Py_BEGIN_ALLOW_THREADS
1575 timeout
= internal_select(s
, 0);
1577 newfd
= accept(s
->sock_fd
, SAS2SA(&addrbuf
), &addrlen
);
1578 Py_END_ALLOW_THREADS
1581 PyErr_SetString(socket_timeout
, "timed out");
1586 if (newfd
== INVALID_SOCKET
)
1590 return s
->errorhandler();
1592 /* Create the new object with unspecified family,
1593 to avoid calls to bind() etc. on it. */
1594 sock
= (PyObject
*) new_sockobject(newfd
,
1603 addr
= makesockaddr(s
->sock_fd
, SAS2SA(&addrbuf
),
1604 addrlen
, s
->sock_proto
);
1608 res
= PyTuple_Pack(2, sock
, addr
);
1616 PyDoc_STRVAR(accept_doc
,
1617 "accept() -> (socket object, address info)\n\
1619 Wait for an incoming connection. Return a new socket representing the\n\
1620 connection, and the address of the client. For IP sockets, the address\n\
1621 info is a pair (hostaddr, port).");
1623 /* s.setblocking(flag) method. Argument:
1624 False -- non-blocking mode; same as settimeout(0)
1625 True -- blocking mode; same as settimeout(None)
1629 sock_setblocking(PySocketSockObject
*s
, PyObject
*arg
)
1633 block
= PyInt_AsLong(arg
);
1634 if (block
== -1 && PyErr_Occurred())
1637 s
->sock_timeout
= block
? -1.0 : 0.0;
1638 internal_setblocking(s
, block
);
1644 PyDoc_STRVAR(setblocking_doc
,
1645 "setblocking(flag)\n\
1647 Set the socket to blocking (flag is true) or non-blocking (false).\n\
1648 setblocking(True) is equivalent to settimeout(None);\n\
1649 setblocking(False) is equivalent to settimeout(0.0).");
1651 /* s.settimeout(timeout) method. Argument:
1652 None -- no timeout, blocking mode; same as setblocking(True)
1653 0.0 -- non-blocking mode; same as setblocking(False)
1654 > 0 -- timeout mode; operations time out after timeout seconds
1655 < 0 -- illegal; raises an exception
1658 sock_settimeout(PySocketSockObject
*s
, PyObject
*arg
)
1665 timeout
= PyFloat_AsDouble(arg
);
1666 if (timeout
< 0.0) {
1667 if (!PyErr_Occurred())
1668 PyErr_SetString(PyExc_ValueError
,
1669 "Timeout value out of range");
1674 s
->sock_timeout
= timeout
;
1675 internal_setblocking(s
, timeout
< 0.0);
1681 PyDoc_STRVAR(settimeout_doc
,
1682 "settimeout(timeout)\n\
1684 Set a timeout on socket operations. 'timeout' can be a float,\n\
1685 giving in seconds, or None. Setting a timeout of None disables\n\
1686 the timeout feature and is equivalent to setblocking(1).\n\
1687 Setting a timeout of zero is the same as setblocking(0).");
1689 /* s.gettimeout() method.
1690 Returns the timeout associated with a socket. */
1692 sock_gettimeout(PySocketSockObject
*s
)
1694 if (s
->sock_timeout
< 0.0) {
1699 return PyFloat_FromDouble(s
->sock_timeout
);
1702 PyDoc_STRVAR(gettimeout_doc
,
1703 "gettimeout() -> timeout\n\
1705 Returns the timeout in floating seconds associated with socket \n\
1706 operations. A timeout of None indicates that timeouts on socket \n\
1707 operations are disabled.");
1710 /* s.sleeptaskw(1 | 0) method */
1713 sock_sleeptaskw(PySocketSockObject
*s
,PyObject
*arg
)
1716 block
= PyInt_AsLong(arg
);
1717 if (block
== -1 && PyErr_Occurred())
1719 Py_BEGIN_ALLOW_THREADS
1720 socketioctl(s
->sock_fd
, 0x80046679, (u_long
*)&block
);
1721 Py_END_ALLOW_THREADS
1726 PyDoc_STRVAR(sleeptaskw_doc
,
1727 "sleeptaskw(flag)\n\
1729 Allow sleeps in taskwindows.");
1733 /* s.setsockopt() method.
1734 With an integer third argument, sets an integer option.
1735 With a string third argument, sets an option from a buffer;
1736 use optional built-in module 'struct' to encode the string. */
1739 sock_setsockopt(PySocketSockObject
*s
, PyObject
*args
)
1748 if (PyArg_ParseTuple(args
, "iii:setsockopt",
1749 &level
, &optname
, &flag
)) {
1750 buf
= (char *) &flag
;
1751 buflen
= sizeof flag
;
1755 if (!PyArg_ParseTuple(args
, "iis#:setsockopt",
1756 &level
, &optname
, &buf
, &buflen
))
1759 res
= setsockopt(s
->sock_fd
, level
, optname
, (void *)buf
, buflen
);
1761 return s
->errorhandler();
1766 PyDoc_STRVAR(setsockopt_doc
,
1767 "setsockopt(level, option, value)\n\
1769 Set a socket option. See the Unix manual for level and option.\n\
1770 The value argument can either be an integer or a string.");
1773 /* s.getsockopt() method.
1774 With two arguments, retrieves an integer option.
1775 With a third integer argument, retrieves a string buffer of that size;
1776 use optional built-in module 'struct' to decode the string. */
1779 sock_getsockopt(PySocketSockObject
*s
, PyObject
*args
)
1785 socklen_t buflen
= 0;
1788 /* We have incomplete socket support. */
1789 PyErr_SetString(socket_error
, "getsockopt not supported");
1793 if (!PyArg_ParseTuple(args
, "ii|i:getsockopt",
1794 &level
, &optname
, &buflen
))
1799 socklen_t flagsize
= sizeof flag
;
1800 res
= getsockopt(s
->sock_fd
, level
, optname
,
1801 (void *)&flag
, &flagsize
);
1803 return s
->errorhandler();
1804 return PyInt_FromLong(flag
);
1807 /* socklen_t is unsigned so no negative test is needed,
1808 test buflen == 0 is previously done */
1809 if (buflen
> 1024) {
1811 if (buflen
<= 0 || buflen
> 1024) {
1813 PyErr_SetString(socket_error
,
1814 "getsockopt buflen out of range");
1817 buf
= PyString_FromStringAndSize((char *)NULL
, buflen
);
1820 res
= getsockopt(s
->sock_fd
, level
, optname
,
1821 (void *)PyString_AS_STRING(buf
), &buflen
);
1824 return s
->errorhandler();
1826 _PyString_Resize(&buf
, buflen
);
1828 #endif /* __BEOS__ */
1831 PyDoc_STRVAR(getsockopt_doc
,
1832 "getsockopt(level, option[, buffersize]) -> value\n\
1834 Get a socket option. See the Unix manual for level and option.\n\
1835 If a nonzero buffersize argument is given, the return value is a\n\
1836 string of that length; otherwise it is an integer.");
1839 /* s.bind(sockaddr) method */
1842 sock_bind(PySocketSockObject
*s
, PyObject
*addro
)
1844 sock_addr_t addrbuf
;
1848 if (!getsockaddrarg(s
, addro
, SAS2SA(&addrbuf
), &addrlen
))
1850 Py_BEGIN_ALLOW_THREADS
1851 res
= bind(s
->sock_fd
, SAS2SA(&addrbuf
), addrlen
);
1852 Py_END_ALLOW_THREADS
1854 return s
->errorhandler();
1859 PyDoc_STRVAR(bind_doc
,
1862 Bind the socket to a local address. For IP sockets, the address is a\n\
1863 pair (host, port); the host must refer to the local host. For raw packet\n\
1864 sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");
1867 /* s.close() method.
1868 Set the file descriptor to -1 so operations tried subsequently
1869 will surely fail. */
1872 sock_close(PySocketSockObject
*s
)
1876 if ((fd
= s
->sock_fd
) != -1) {
1878 Py_BEGIN_ALLOW_THREADS
1879 (void) SOCKETCLOSE(fd
);
1880 Py_END_ALLOW_THREADS
1886 PyDoc_STRVAR(close_doc
,
1889 Close the socket. It cannot be used after this call.");
1892 internal_connect(PySocketSockObject
*s
, struct sockaddr
*addr
, int addrlen
,
1898 res
= connect(s
->sock_fd
, addr
, addrlen
);
1902 if (s
->sock_timeout
> 0.0) {
1903 if (res
< 0 && WSAGetLastError() == WSAEWOULDBLOCK
&&
1905 /* This is a mess. Best solution: trust select */
1909 tv
.tv_sec
= (int)s
->sock_timeout
;
1910 tv
.tv_usec
= (int)((s
->sock_timeout
- tv
.tv_sec
) * 1e6
);
1912 FD_SET(s
->sock_fd
, &fds
);
1914 FD_SET(s
->sock_fd
, &fds_exc
);
1915 res
= select(s
->sock_fd
+1, NULL
, &fds
, &fds_exc
, &tv
);
1917 res
= WSAEWOULDBLOCK
;
1919 } else if (res
> 0) {
1920 if (FD_ISSET(s
->sock_fd
, &fds
))
1921 /* The socket is in the writeable set - this
1925 /* As per MS docs, we need to call getsockopt()
1926 to get the underlying error */
1927 int res_size
= sizeof res
;
1928 /* It must be in the exception set */
1929 assert(FD_ISSET(s
->sock_fd
, &fds_exc
));
1930 if (0 == getsockopt(s
->sock_fd
, SOL_SOCKET
, SO_ERROR
,
1931 (char *)&res
, &res_size
))
1932 /* getsockopt also clears WSAGetLastError,
1933 so reset it back. */
1934 WSASetLastError(res
);
1936 res
= WSAGetLastError();
1939 /* else if (res < 0) an error occurred */
1944 res
= WSAGetLastError();
1948 if (s
->sock_timeout
> 0.0) {
1949 if (res
< 0 && errno
== EINPROGRESS
&& IS_SELECTABLE(s
)) {
1950 timeout
= internal_select(s
, 1);
1952 res
= connect(s
->sock_fd
, addr
, addrlen
);
1953 if (res
< 0 && errno
== EISCONN
)
1956 else if (timeout
== -1)
1957 res
= errno
; /* had error */
1959 res
= EWOULDBLOCK
; /* timed out */
1967 *timeoutp
= timeout
;
1972 /* s.connect(sockaddr) method */
1975 sock_connect(PySocketSockObject
*s
, PyObject
*addro
)
1977 sock_addr_t addrbuf
;
1982 if (!getsockaddrarg(s
, addro
, SAS2SA(&addrbuf
), &addrlen
))
1985 Py_BEGIN_ALLOW_THREADS
1986 res
= internal_connect(s
, SAS2SA(&addrbuf
), addrlen
, &timeout
);
1987 Py_END_ALLOW_THREADS
1990 PyErr_SetString(socket_timeout
, "timed out");
1994 return s
->errorhandler();
1999 PyDoc_STRVAR(connect_doc
,
2000 "connect(address)\n\
2002 Connect the socket to a remote address. For IP sockets, the address\n\
2003 is a pair (host, port).");
2006 /* s.connect_ex(sockaddr) method */
2009 sock_connect_ex(PySocketSockObject
*s
, PyObject
*addro
)
2011 sock_addr_t addrbuf
;
2016 if (!getsockaddrarg(s
, addro
, SAS2SA(&addrbuf
), &addrlen
))
2019 Py_BEGIN_ALLOW_THREADS
2020 res
= internal_connect(s
, SAS2SA(&addrbuf
), addrlen
, &timeout
);
2021 Py_END_ALLOW_THREADS
2023 /* Signals are not errors (though they may raise exceptions). Adapted
2024 from PyErr_SetFromErrnoWithFilenameObject(). */
2026 if (res
== EINTR
&& PyErr_CheckSignals())
2030 return PyInt_FromLong((long) res
);
2033 PyDoc_STRVAR(connect_ex_doc
,
2034 "connect_ex(address) -> errno\n\
2036 This is like connect(address), but returns an error code (the errno value)\n\
2037 instead of raising an exception when an error occurs.");
2040 /* s.fileno() method */
2043 sock_fileno(PySocketSockObject
*s
)
2045 #if SIZEOF_SOCKET_T <= SIZEOF_LONG
2046 return PyInt_FromLong((long) s
->sock_fd
);
2048 return PyLong_FromLongLong((PY_LONG_LONG
)s
->sock_fd
);
2052 PyDoc_STRVAR(fileno_doc
,
2053 "fileno() -> integer\n\
2055 Return the integer file descriptor of the socket.");
2059 /* s.dup() method */
2062 sock_dup(PySocketSockObject
*s
)
2067 newfd
= dup(s
->sock_fd
);
2069 return s
->errorhandler();
2070 sock
= (PyObject
*) new_sockobject(newfd
,
2079 PyDoc_STRVAR(dup_doc
,
2080 "dup() -> socket object\n\
2082 Return a new socket object connected to the same system resource.");
2087 /* s.getsockname() method */
2090 sock_getsockname(PySocketSockObject
*s
)
2092 sock_addr_t addrbuf
;
2096 if (!getsockaddrlen(s
, &addrlen
))
2098 memset(&addrbuf
, 0, addrlen
);
2099 Py_BEGIN_ALLOW_THREADS
2100 res
= getsockname(s
->sock_fd
, SAS2SA(&addrbuf
), &addrlen
);
2101 Py_END_ALLOW_THREADS
2103 return s
->errorhandler();
2104 return makesockaddr(s
->sock_fd
, SAS2SA(&addrbuf
), addrlen
,
2108 PyDoc_STRVAR(getsockname_doc
,
2109 "getsockname() -> address info\n\
2111 Return the address of the local endpoint. For IP sockets, the address\n\
2112 info is a pair (hostaddr, port).");
2115 #ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
2116 /* s.getpeername() method */
2119 sock_getpeername(PySocketSockObject
*s
)
2121 sock_addr_t addrbuf
;
2125 if (!getsockaddrlen(s
, &addrlen
))
2127 memset(&addrbuf
, 0, addrlen
);
2128 Py_BEGIN_ALLOW_THREADS
2129 res
= getpeername(s
->sock_fd
, SAS2SA(&addrbuf
), &addrlen
);
2130 Py_END_ALLOW_THREADS
2132 return s
->errorhandler();
2133 return makesockaddr(s
->sock_fd
, SAS2SA(&addrbuf
), addrlen
,
2137 PyDoc_STRVAR(getpeername_doc
,
2138 "getpeername() -> address info\n\
2140 Return the address of the remote endpoint. For IP sockets, the address\n\
2141 info is a pair (hostaddr, port).");
2143 #endif /* HAVE_GETPEERNAME */
2146 /* s.listen(n) method */
2149 sock_listen(PySocketSockObject
*s
, PyObject
*arg
)
2154 backlog
= PyInt_AsLong(arg
);
2155 if (backlog
== -1 && PyErr_Occurred())
2157 Py_BEGIN_ALLOW_THREADS
2160 res
= listen(s
->sock_fd
, backlog
);
2161 Py_END_ALLOW_THREADS
2163 return s
->errorhandler();
2168 PyDoc_STRVAR(listen_doc
,
2171 Enable a server to accept connections. The backlog argument must be at\n\
2172 least 1; it specifies the number of unaccepted connection that the system\n\
2173 will allow before refusing new connections.");
2177 /* s.makefile(mode) method.
2178 Create a new open file object referring to a dupped version of
2179 the socket's file descriptor. (The dup() call is necessary so
2180 that the open file and socket objects may be closed independent
2182 The mode argument specifies 'r' or 'w' passed to fdopen(). */
2185 sock_makefile(PySocketSockObject
*s
, PyObject
*args
)
2187 extern int fclose(FILE *);
2202 if (!PyArg_ParseTuple(args
, "|si:makefile", &mode
, &bufsize
))
2205 if (strcmp(mode
,"rb") == 0) {
2209 if (strcmp(mode
,"wb") == 0) {
2215 if (((fd
= _open_osfhandle(s
->sock_fd
, _O_BINARY
)) < 0) ||
2216 ((fd
= dup(fd
)) < 0) || ((fp
= fdopen(fd
, mode
)) == NULL
))
2218 if ((fd
= dup(s
->sock_fd
)) < 0 || (fp
= fdopen(fd
, mode
)) == NULL
)
2223 return s
->errorhandler();
2225 f
= PyFile_FromFile(fp
, "<socket>", mode
, fclose
);
2227 PyFile_SetBufSize(f
, bufsize
);
2231 PyDoc_STRVAR(makefile_doc
,
2232 "makefile([mode[, buffersize]]) -> file object\n\
2234 Return a regular file object corresponding to the socket.\n\
2235 The mode and buffersize arguments are as for the built-in open() function.");
2240 * This is the guts of the recv() and recv_into() methods, which reads into a
2241 * char buffer. If you have any inc/dec ref to do to the objects that contain
2242 * the buffer, do it in the caller. This function returns the number of bytes
2243 * succesfully read. If there was an error, it returns -1. Note that it is
2244 * also possible that we return a number of bytes smaller than the request
2248 sock_recv_guts(PySocketSockObject
*s
, char* cbuf
, int len
, int flags
)
2250 ssize_t outlen
= -1;
2257 if (!IS_SELECTABLE(s
)) {
2263 Py_BEGIN_ALLOW_THREADS
2264 timeout
= internal_select(s
, 0);
2266 outlen
= recv(s
->sock_fd
, cbuf
, len
, flags
);
2267 Py_END_ALLOW_THREADS
2270 PyErr_SetString(socket_timeout
, "timed out");
2274 /* Note: the call to errorhandler() ALWAYS indirectly returned
2275 NULL, so ignore its return value */
2282 while (remaining
!= 0) {
2283 unsigned int segment
;
2286 segment
= remaining
/SEGMENT_SIZE
;
2288 segment
= SEGMENT_SIZE
;
2291 segment
= remaining
;
2294 Py_BEGIN_ALLOW_THREADS
2295 timeout
= internal_select(s
, 0);
2297 nread
= recv(s
->sock_fd
, read_buf
, segment
, flags
);
2298 Py_END_ALLOW_THREADS
2301 PyErr_SetString(socket_timeout
, "timed out");
2308 if (nread
!= remaining
) {
2313 remaining
-= segment
;
2314 read_buf
+= segment
;
2316 outlen
= read_buf
- cbuf
;
2323 /* s.recv(nbytes [,flags]) method */
2326 sock_recv(PySocketSockObject
*s
, PyObject
*args
)
2328 int recvlen
, flags
= 0;
2332 if (!PyArg_ParseTuple(args
, "i|i:recv", &recvlen
, &flags
))
2336 PyErr_SetString(PyExc_ValueError
,
2337 "negative buffersize in recv");
2341 /* Allocate a new string. */
2342 buf
= PyString_FromStringAndSize((char *) 0, recvlen
);
2347 outlen
= sock_recv_guts(s
, PyString_AS_STRING(buf
), recvlen
, flags
);
2349 /* An error occurred, release the string and return an
2354 if (outlen
!= recvlen
) {
2355 /* We did not read as many bytes as we anticipated, resize the
2356 string if possible and be succesful. */
2357 if (_PyString_Resize(&buf
, outlen
) < 0)
2358 /* Oopsy, not so succesful after all. */
2365 PyDoc_STRVAR(recv_doc
,
2366 "recv(buffersize[, flags]) -> data\n\
2368 Receive up to buffersize bytes from the socket. For the optional flags\n\
2369 argument, see the Unix manual. When no data is available, block until\n\
2370 at least one byte is available or until the remote end is closed. When\n\
2371 the remote end is closed and all data is read, return the empty string.");
2374 /* s.recv_into(buffer, [nbytes [,flags]]) method */
2377 sock_recv_into(PySocketSockObject
*s
, PyObject
*args
, PyObject
*kwds
)
2379 static char *kwlist
[] = {"buffer", "nbytes", "flags", 0};
2381 int recvlen
= 0, flags
= 0;
2386 /* Get the buffer's memory */
2387 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "w#|ii:recv_into", kwlist
,
2388 &buf
, &buflen
, &recvlen
, &flags
))
2390 assert(buf
!= 0 && buflen
> 0);
2393 PyErr_SetString(PyExc_ValueError
,
2394 "negative buffersize in recv_into");
2398 /* If nbytes was not specified, use the buffer's length */
2402 /* Check if the buffer is large enough */
2403 if (buflen
< recvlen
) {
2404 PyErr_SetString(PyExc_ValueError
,
2405 "buffer too small for requested bytes");
2410 readlen
= sock_recv_guts(s
, buf
, recvlen
, flags
);
2412 /* Return an error. */
2416 /* Return the number of bytes read. Note that we do not do anything
2417 special here in the case that readlen < recvlen. */
2418 return PyInt_FromSsize_t(readlen
);
2421 PyDoc_STRVAR(recv_into_doc
,
2422 "recv_into(buffer, [nbytes[, flags]]) -> nbytes_read\n\
2424 A version of recv() that stores its data into a buffer rather than creating \n\
2425 a new string. Receive up to buffersize bytes from the socket. If buffersize \n\
2426 is not specified (or 0), receive up to the size available in the given buffer.\n\
2428 See recv() for documentation about the flags.");
2432 * This is the guts of the recv() and recv_into() methods, which reads into a
2433 * char buffer. If you have any inc/def ref to do to the objects that contain
2434 * the buffer, do it in the caller. This function returns the number of bytes
2435 * succesfully read. If there was an error, it returns -1. Note that it is
2436 * also possible that we return a number of bytes smaller than the request
2439 * 'addr' is a return value for the address object. Note that you must decref
2443 sock_recvfrom_guts(PySocketSockObject
*s
, char* cbuf
, int len
, int flags
,
2446 sock_addr_t addrbuf
;
2453 if (!getsockaddrlen(s
, &addrlen
))
2456 if (!IS_SELECTABLE(s
)) {
2461 Py_BEGIN_ALLOW_THREADS
2462 memset(&addrbuf
, 0, addrlen
);
2463 timeout
= internal_select(s
, 0);
2466 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
2467 n
= recvfrom(s
->sock_fd
, cbuf
, len
, flags
,
2468 SAS2SA(&addrbuf
), &addrlen
);
2470 n
= recvfrom(s
->sock_fd
, cbuf
, len
, flags
,
2471 (void *) &addrbuf
, &addrlen
);
2474 n
= recvfrom(s
->sock_fd
, cbuf
, len
, flags
,
2475 SAS2SA(&addrbuf
), &addrlen
);
2478 Py_END_ALLOW_THREADS
2481 PyErr_SetString(socket_timeout
, "timed out");
2489 if (!(*addr
= makesockaddr(s
->sock_fd
, SAS2SA(&addrbuf
),
2490 addrlen
, s
->sock_proto
)))
2496 /* s.recvfrom(nbytes [,flags]) method */
2499 sock_recvfrom(PySocketSockObject
*s
, PyObject
*args
)
2501 PyObject
*buf
= NULL
;
2502 PyObject
*addr
= NULL
;
2503 PyObject
*ret
= NULL
;
2504 int recvlen
, flags
= 0;
2507 if (!PyArg_ParseTuple(args
, "i|i:recvfrom", &recvlen
, &flags
))
2511 PyErr_SetString(PyExc_ValueError
,
2512 "negative buffersize in recvfrom");
2516 buf
= PyString_FromStringAndSize((char *) 0, recvlen
);
2520 outlen
= sock_recvfrom_guts(s
, PyString_AS_STRING(buf
),
2521 recvlen
, flags
, &addr
);
2526 if (outlen
!= recvlen
) {
2527 /* We did not read as many bytes as we anticipated, resize the
2528 string if possible and be succesful. */
2529 if (_PyString_Resize(&buf
, outlen
) < 0)
2530 /* Oopsy, not so succesful after all. */
2534 ret
= PyTuple_Pack(2, buf
, addr
);
2542 PyDoc_STRVAR(recvfrom_doc
,
2543 "recvfrom(buffersize[, flags]) -> (data, address info)\n\
2545 Like recv(buffersize, flags) but also return the sender's address info.");
2548 /* s.recvfrom_into(buffer[, nbytes [,flags]]) method */
2551 sock_recvfrom_into(PySocketSockObject
*s
, PyObject
*args
, PyObject
* kwds
)
2553 static char *kwlist
[] = {"buffer", "nbytes", "flags", 0};
2555 int recvlen
= 0, flags
= 0;
2560 PyObject
*addr
= NULL
;
2562 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "w#|ii:recvfrom_into",
2563 kwlist
, &buf
, &buflen
,
2566 assert(buf
!= 0 && buflen
> 0);
2569 PyErr_SetString(PyExc_ValueError
,
2570 "negative buffersize in recvfrom_into");
2574 /* If nbytes was not specified, use the buffer's length */
2578 readlen
= sock_recvfrom_guts(s
, buf
, recvlen
, flags
, &addr
);
2580 /* Return an error */
2585 /* Return the number of bytes read and the address. Note that we do
2586 not do anything special here in the case that readlen < recvlen. */
2587 return Py_BuildValue("lN", readlen
, addr
);
2590 PyDoc_STRVAR(recvfrom_into_doc
,
2591 "recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)\n\
2593 Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.");
2596 /* s.send(data [,flags]) method */
2599 sock_send(PySocketSockObject
*s
, PyObject
*args
)
2602 int len
, n
= -1, flags
= 0, timeout
;
2604 if (!PyArg_ParseTuple(args
, "s#|i:send", &buf
, &len
, &flags
))
2607 if (!IS_SELECTABLE(s
))
2608 return select_error();
2610 Py_BEGIN_ALLOW_THREADS
2611 timeout
= internal_select(s
, 1);
2614 n
= sendsegmented(s
->sock_fd
, buf
, len
, flags
);
2616 n
= send(s
->sock_fd
, buf
, len
, flags
);
2618 Py_END_ALLOW_THREADS
2621 PyErr_SetString(socket_timeout
, "timed out");
2625 return s
->errorhandler();
2626 return PyInt_FromLong((long)n
);
2629 PyDoc_STRVAR(send_doc
,
2630 "send(data[, flags]) -> count\n\
2632 Send a data string to the socket. For the optional flags\n\
2633 argument, see the Unix manual. Return the number of bytes\n\
2634 sent; this may be less than len(data) if the network is busy.");
2637 /* s.sendall(data [,flags]) method */
2640 sock_sendall(PySocketSockObject
*s
, PyObject
*args
)
2643 int len
, n
= -1, flags
= 0, timeout
;
2645 if (!PyArg_ParseTuple(args
, "s#|i:sendall", &buf
, &len
, &flags
))
2648 if (!IS_SELECTABLE(s
))
2649 return select_error();
2651 Py_BEGIN_ALLOW_THREADS
2653 timeout
= internal_select(s
, 1);
2658 n
= sendsegmented(s
->sock_fd
, buf
, len
, flags
);
2660 n
= send(s
->sock_fd
, buf
, len
, flags
);
2667 Py_END_ALLOW_THREADS
2670 PyErr_SetString(socket_timeout
, "timed out");
2674 return s
->errorhandler();
2680 PyDoc_STRVAR(sendall_doc
,
2681 "sendall(data[, flags])\n\
2683 Send a data string to the socket. For the optional flags\n\
2684 argument, see the Unix manual. This calls send() repeatedly\n\
2685 until all data is sent. If an error occurs, it's impossible\n\
2686 to tell how much data has been sent.");
2689 /* s.sendto(data, [flags,] sockaddr) method */
2692 sock_sendto(PySocketSockObject
*s
, PyObject
*args
)
2696 sock_addr_t addrbuf
;
2697 int addrlen
, len
, n
= -1, flags
, timeout
;
2700 if (!PyArg_ParseTuple(args
, "s#O:sendto", &buf
, &len
, &addro
)) {
2702 if (!PyArg_ParseTuple(args
, "s#iO:sendto",
2703 &buf
, &len
, &flags
, &addro
))
2707 if (!IS_SELECTABLE(s
))
2708 return select_error();
2710 if (!getsockaddrarg(s
, addro
, SAS2SA(&addrbuf
), &addrlen
))
2713 Py_BEGIN_ALLOW_THREADS
2714 timeout
= internal_select(s
, 1);
2716 n
= sendto(s
->sock_fd
, buf
, len
, flags
, SAS2SA(&addrbuf
), addrlen
);
2717 Py_END_ALLOW_THREADS
2720 PyErr_SetString(socket_timeout
, "timed out");
2724 return s
->errorhandler();
2725 return PyInt_FromLong((long)n
);
2728 PyDoc_STRVAR(sendto_doc
,
2729 "sendto(data[, flags], address) -> count\n\
2731 Like send(data, flags) but allows specifying the destination address.\n\
2732 For IP sockets, the address is a pair (hostaddr, port).");
2735 /* s.shutdown(how) method */
2738 sock_shutdown(PySocketSockObject
*s
, PyObject
*arg
)
2743 how
= PyInt_AsLong(arg
);
2744 if (how
== -1 && PyErr_Occurred())
2746 Py_BEGIN_ALLOW_THREADS
2747 res
= shutdown(s
->sock_fd
, how
);
2748 Py_END_ALLOW_THREADS
2750 return s
->errorhandler();
2755 PyDoc_STRVAR(shutdown_doc
,
2758 Shut down the reading side of the socket (flag == SHUT_RD), the writing side\n\
2759 of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).");
2762 /* List of methods for socket objects */
2764 static PyMethodDef sock_methods
[] = {
2765 {"accept", (PyCFunction
)sock_accept
, METH_NOARGS
,
2767 {"bind", (PyCFunction
)sock_bind
, METH_O
,
2769 {"close", (PyCFunction
)sock_close
, METH_NOARGS
,
2771 {"connect", (PyCFunction
)sock_connect
, METH_O
,
2773 {"connect_ex", (PyCFunction
)sock_connect_ex
, METH_O
,
2776 {"dup", (PyCFunction
)sock_dup
, METH_NOARGS
,
2779 {"fileno", (PyCFunction
)sock_fileno
, METH_NOARGS
,
2781 #ifdef HAVE_GETPEERNAME
2782 {"getpeername", (PyCFunction
)sock_getpeername
,
2783 METH_NOARGS
, getpeername_doc
},
2785 {"getsockname", (PyCFunction
)sock_getsockname
,
2786 METH_NOARGS
, getsockname_doc
},
2787 {"getsockopt", (PyCFunction
)sock_getsockopt
, METH_VARARGS
,
2789 {"listen", (PyCFunction
)sock_listen
, METH_O
,
2792 {"makefile", (PyCFunction
)sock_makefile
, METH_VARARGS
,
2795 {"recv", (PyCFunction
)sock_recv
, METH_VARARGS
,
2797 {"recv_into", (PyCFunction
)sock_recv_into
, METH_VARARGS
| METH_KEYWORDS
,
2799 {"recvfrom", (PyCFunction
)sock_recvfrom
, METH_VARARGS
,
2801 {"recvfrom_into", (PyCFunction
)sock_recvfrom_into
, METH_VARARGS
| METH_KEYWORDS
,
2803 {"send", (PyCFunction
)sock_send
, METH_VARARGS
,
2805 {"sendall", (PyCFunction
)sock_sendall
, METH_VARARGS
,
2807 {"sendto", (PyCFunction
)sock_sendto
, METH_VARARGS
,
2809 {"setblocking", (PyCFunction
)sock_setblocking
, METH_O
,
2811 {"settimeout", (PyCFunction
)sock_settimeout
, METH_O
,
2813 {"gettimeout", (PyCFunction
)sock_gettimeout
, METH_NOARGS
,
2815 {"setsockopt", (PyCFunction
)sock_setsockopt
, METH_VARARGS
,
2817 {"shutdown", (PyCFunction
)sock_shutdown
, METH_O
,
2820 {"sleeptaskw", (PyCFunction
)sock_sleeptaskw
, METH_O
,
2823 {NULL
, NULL
} /* sentinel */
2826 /* SockObject members */
2827 static PyMemberDef sock_memberlist
[] = {
2828 {"family", T_INT
, offsetof(PySocketSockObject
, sock_family
), READONLY
, "the socket family"},
2829 {"type", T_INT
, offsetof(PySocketSockObject
, sock_type
), READONLY
, "the socket type"},
2830 {"proto", T_INT
, offsetof(PySocketSockObject
, sock_proto
), READONLY
, "the socket protocol"},
2831 {"timeout", T_DOUBLE
, offsetof(PySocketSockObject
, sock_timeout
), READONLY
, "the socket timeout"},
2835 /* Deallocate a socket object in response to the last Py_DECREF().
2836 First close the file description. */
2839 sock_dealloc(PySocketSockObject
*s
)
2841 if (s
->sock_fd
!= -1)
2842 (void) SOCKETCLOSE(s
->sock_fd
);
2843 s
->ob_type
->tp_free((PyObject
*)s
);
2848 sock_repr(PySocketSockObject
*s
)
2851 #if SIZEOF_SOCKET_T > SIZEOF_LONG
2852 if (s
->sock_fd
> LONG_MAX
) {
2853 /* this can occur on Win64, and actually there is a special
2854 ugly printf formatter for decimal pointer length integer
2855 printing, only bother if necessary*/
2856 PyErr_SetString(PyExc_OverflowError
,
2857 "no printf formatter to display "
2858 "the socket descriptor in decimal");
2864 "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
2865 (long)s
->sock_fd
, s
->sock_family
,
2868 return PyString_FromString(buf
);
2872 /* Create a new, uninitialized socket object. */
2875 sock_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
2879 new = type
->tp_alloc(type
, 0);
2881 ((PySocketSockObject
*)new)->sock_fd
= -1;
2882 ((PySocketSockObject
*)new)->sock_timeout
= -1.0;
2883 ((PySocketSockObject
*)new)->errorhandler
= &set_error
;
2889 /* Initialize a new socket object. */
2893 sock_initobj(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
2895 PySocketSockObject
*s
= (PySocketSockObject
*)self
;
2897 int family
= AF_INET
, type
= SOCK_STREAM
, proto
= 0;
2898 static char *keywords
[] = {"family", "type", "proto", 0};
2900 if (!PyArg_ParseTupleAndKeywords(args
, kwds
,
2901 "|iii:socket", keywords
,
2902 &family
, &type
, &proto
))
2905 Py_BEGIN_ALLOW_THREADS
2906 fd
= socket(family
, type
, proto
);
2907 Py_END_ALLOW_THREADS
2910 if (fd
== INVALID_SOCKET
)
2918 init_sockobject(s
, fd
, family
, type
, proto
);
2925 /* Type object for socket objects. */
2927 static PyTypeObject sock_type
= {
2928 PyObject_HEAD_INIT(0) /* Must fill in type value later */
2930 "_socket.socket", /* tp_name */
2931 sizeof(PySocketSockObject
), /* tp_basicsize */
2932 0, /* tp_itemsize */
2933 (destructor
)sock_dealloc
, /* tp_dealloc */
2938 (reprfunc
)sock_repr
, /* tp_repr */
2939 0, /* tp_as_number */
2940 0, /* tp_as_sequence */
2941 0, /* tp_as_mapping */
2945 PyObject_GenericGetAttr
, /* tp_getattro */
2946 0, /* tp_setattro */
2947 0, /* tp_as_buffer */
2948 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
2949 sock_doc
, /* tp_doc */
2950 0, /* tp_traverse */
2952 0, /* tp_richcompare */
2953 0, /* tp_weaklistoffset */
2955 0, /* tp_iternext */
2956 sock_methods
, /* tp_methods */
2957 sock_memberlist
, /* tp_members */
2961 0, /* tp_descr_get */
2962 0, /* tp_descr_set */
2963 0, /* tp_dictoffset */
2964 sock_initobj
, /* tp_init */
2965 PyType_GenericAlloc
, /* tp_alloc */
2966 sock_new
, /* tp_new */
2967 PyObject_Del
, /* tp_free */
2971 /* Python interface to gethostname(). */
2975 socket_gethostname(PyObject
*self
, PyObject
*unused
)
2979 Py_BEGIN_ALLOW_THREADS
2980 res
= gethostname(buf
, (int) sizeof buf
- 1);
2981 Py_END_ALLOW_THREADS
2984 buf
[sizeof buf
- 1] = '\0';
2985 return PyString_FromString(buf
);
2988 PyDoc_STRVAR(gethostname_doc
,
2989 "gethostname() -> string\n\
2991 Return the current host name.");
2994 /* Python interface to gethostbyname(name). */
2998 socket_gethostbyname(PyObject
*self
, PyObject
*args
)
3001 sock_addr_t addrbuf
;
3003 if (!PyArg_ParseTuple(args
, "s:gethostbyname", &name
))
3005 if (setipaddr(name
, SAS2SA(&addrbuf
), sizeof(addrbuf
), AF_INET
) < 0)
3007 return makeipaddr(SAS2SA(&addrbuf
), sizeof(struct sockaddr_in
));
3010 PyDoc_STRVAR(gethostbyname_doc
,
3011 "gethostbyname(host) -> address\n\
3013 Return the IP address (a string of the form '255.255.255.255') for a host.");
3016 /* Convenience function common to gethostbyname_ex and gethostbyaddr */
3019 gethost_common(struct hostent
*h
, struct sockaddr
*addr
, int alen
, int af
)
3022 PyObject
*rtn_tuple
= (PyObject
*)NULL
;
3023 PyObject
*name_list
= (PyObject
*)NULL
;
3024 PyObject
*addr_list
= (PyObject
*)NULL
;
3028 /* Let's get real error message to return */
3030 set_herror(h_errno
);
3032 PyErr_SetString(socket_error
, "host not found");
3037 if (h
->h_addrtype
!= af
) {
3038 #ifdef HAVE_STRERROR
3039 /* Let's get real error message to return */
3040 PyErr_SetString(socket_error
,
3041 (char *)strerror(EAFNOSUPPORT
));
3045 "Address family not supported by protocol family");
3053 if (alen
< sizeof(struct sockaddr_in
))
3059 if (alen
< sizeof(struct sockaddr_in6
))
3066 if ((name_list
= PyList_New(0)) == NULL
)
3069 if ((addr_list
= PyList_New(0)) == NULL
)
3072 /* SF #1511317: h_aliases can be NULL */
3074 for (pch
= h
->h_aliases
; *pch
!= NULL
; pch
++) {
3076 tmp
= PyString_FromString(*pch
);
3080 status
= PyList_Append(name_list
, tmp
);
3088 for (pch
= h
->h_addr_list
; *pch
!= NULL
; pch
++) {
3095 struct sockaddr_in sin
;
3096 memset(&sin
, 0, sizeof(sin
));
3097 sin
.sin_family
= af
;
3098 #ifdef HAVE_SOCKADDR_SA_LEN
3099 sin
.sin_len
= sizeof(sin
);
3101 memcpy(&sin
.sin_addr
, *pch
, sizeof(sin
.sin_addr
));
3102 tmp
= makeipaddr((struct sockaddr
*)&sin
, sizeof(sin
));
3104 if (pch
== h
->h_addr_list
&& alen
>= sizeof(sin
))
3105 memcpy((char *) addr
, &sin
, sizeof(sin
));
3112 struct sockaddr_in6 sin6
;
3113 memset(&sin6
, 0, sizeof(sin6
));
3114 sin6
.sin6_family
= af
;
3115 #ifdef HAVE_SOCKADDR_SA_LEN
3116 sin6
.sin6_len
= sizeof(sin6
);
3118 memcpy(&sin6
.sin6_addr
, *pch
, sizeof(sin6
.sin6_addr
));
3119 tmp
= makeipaddr((struct sockaddr
*)&sin6
,
3122 if (pch
== h
->h_addr_list
&& alen
>= sizeof(sin6
))
3123 memcpy((char *) addr
, &sin6
, sizeof(sin6
));
3128 default: /* can't happen */
3129 PyErr_SetString(socket_error
,
3130 "unsupported address family");
3137 status
= PyList_Append(addr_list
, tmp
);
3144 rtn_tuple
= Py_BuildValue("sOO", h
->h_name
, name_list
, addr_list
);
3147 Py_XDECREF(name_list
);
3148 Py_XDECREF(addr_list
);
3153 /* Python interface to gethostbyname_ex(name). */
3157 socket_gethostbyname_ex(PyObject
*self
, PyObject
*args
)
3162 struct sockaddr_storage addr
;
3164 struct sockaddr_in addr
;
3166 struct sockaddr
*sa
;
3168 #ifdef HAVE_GETHOSTBYNAME_R
3169 struct hostent hp_allocated
;
3170 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
3171 struct hostent_data data
;
3174 int buf_len
= (sizeof buf
) - 1;
3177 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3180 #endif /* HAVE_GETHOSTBYNAME_R */
3182 if (!PyArg_ParseTuple(args
, "s:gethostbyname_ex", &name
))
3184 if (setipaddr(name
, (struct sockaddr
*)&addr
, sizeof(addr
), AF_INET
) < 0)
3186 Py_BEGIN_ALLOW_THREADS
3187 #ifdef HAVE_GETHOSTBYNAME_R
3188 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3189 result
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
,
3191 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
3192 h
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
, &errnop
);
3193 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
3194 memset((void *) &data
, '\0', sizeof(data
));
3195 result
= gethostbyname_r(name
, &hp_allocated
, &data
);
3196 h
= (result
!= 0) ? NULL
: &hp_allocated
;
3198 #else /* not HAVE_GETHOSTBYNAME_R */
3199 #ifdef USE_GETHOSTBYNAME_LOCK
3200 PyThread_acquire_lock(netdb_lock
, 1);
3202 h
= gethostbyname(name
);
3203 #endif /* HAVE_GETHOSTBYNAME_R */
3204 Py_END_ALLOW_THREADS
3205 /* Some C libraries would require addr.__ss_family instead of
3207 Therefore, we cast the sockaddr_storage into sockaddr to
3208 access sa_family. */
3209 sa
= (struct sockaddr
*)&addr
;
3210 ret
= gethost_common(h
, (struct sockaddr
*)&addr
, sizeof(addr
),
3212 #ifdef USE_GETHOSTBYNAME_LOCK
3213 PyThread_release_lock(netdb_lock
);
3218 PyDoc_STRVAR(ghbn_ex_doc
,
3219 "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
3221 Return the true host name, a list of aliases, and a list of IP addresses,\n\
3222 for a host. The host argument is a string giving a host name or IP number.");
3225 /* Python interface to gethostbyaddr(IP). */
3229 socket_gethostbyaddr(PyObject
*self
, PyObject
*args
)
3232 struct sockaddr_storage addr
;
3234 struct sockaddr_in addr
;
3236 struct sockaddr
*sa
= (struct sockaddr
*)&addr
;
3240 #ifdef HAVE_GETHOSTBYNAME_R
3241 struct hostent hp_allocated
;
3242 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
3243 struct hostent_data data
;
3246 int buf_len
= (sizeof buf
) - 1;
3249 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3252 #endif /* HAVE_GETHOSTBYNAME_R */
3257 if (!PyArg_ParseTuple(args
, "s:gethostbyaddr", &ip_num
))
3260 if (setipaddr(ip_num
, sa
, sizeof(addr
), af
) < 0)
3267 ap
= (char *)&((struct sockaddr_in
*)sa
)->sin_addr
;
3268 al
= sizeof(((struct sockaddr_in
*)sa
)->sin_addr
);
3272 ap
= (char *)&((struct sockaddr_in6
*)sa
)->sin6_addr
;
3273 al
= sizeof(((struct sockaddr_in6
*)sa
)->sin6_addr
);
3277 PyErr_SetString(socket_error
, "unsupported address family");
3280 Py_BEGIN_ALLOW_THREADS
3281 #ifdef HAVE_GETHOSTBYNAME_R
3282 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3283 result
= gethostbyaddr_r(ap
, al
, af
,
3284 &hp_allocated
, buf
, buf_len
,
3286 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
3287 h
= gethostbyaddr_r(ap
, al
, af
,
3288 &hp_allocated
, buf
, buf_len
, &errnop
);
3289 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
3290 memset((void *) &data
, '\0', sizeof(data
));
3291 result
= gethostbyaddr_r(ap
, al
, af
, &hp_allocated
, &data
);
3292 h
= (result
!= 0) ? NULL
: &hp_allocated
;
3294 #else /* not HAVE_GETHOSTBYNAME_R */
3295 #ifdef USE_GETHOSTBYNAME_LOCK
3296 PyThread_acquire_lock(netdb_lock
, 1);
3298 h
= gethostbyaddr(ap
, al
, af
);
3299 #endif /* HAVE_GETHOSTBYNAME_R */
3300 Py_END_ALLOW_THREADS
3301 ret
= gethost_common(h
, (struct sockaddr
*)&addr
, sizeof(addr
), af
);
3302 #ifdef USE_GETHOSTBYNAME_LOCK
3303 PyThread_release_lock(netdb_lock
);
3308 PyDoc_STRVAR(gethostbyaddr_doc
,
3309 "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
3311 Return the true host name, a list of aliases, and a list of IP addresses,\n\
3312 for a host. The host argument is a string giving a host name or IP number.");
3315 /* Python interface to getservbyname(name).
3316 This only returns the port number, since the other info is already
3317 known or not useful (like the list of aliases). */
3321 socket_getservbyname(PyObject
*self
, PyObject
*args
)
3323 char *name
, *proto
=NULL
;
3325 if (!PyArg_ParseTuple(args
, "s|s:getservbyname", &name
, &proto
))
3327 Py_BEGIN_ALLOW_THREADS
3328 sp
= getservbyname(name
, proto
);
3329 Py_END_ALLOW_THREADS
3331 PyErr_SetString(socket_error
, "service/proto not found");
3334 return PyInt_FromLong((long) ntohs(sp
->s_port
));
3337 PyDoc_STRVAR(getservbyname_doc
,
3338 "getservbyname(servicename[, protocolname]) -> integer\n\
3340 Return a port number from a service name and protocol name.\n\
3341 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3342 otherwise any protocol will match.");
3345 /* Python interface to getservbyport(port).
3346 This only returns the service name, since the other info is already
3347 known or not useful (like the list of aliases). */
3351 socket_getservbyport(PyObject
*self
, PyObject
*args
)
3353 unsigned short port
;
3356 if (!PyArg_ParseTuple(args
, "H|s:getservbyport", &port
, &proto
))
3358 Py_BEGIN_ALLOW_THREADS
3359 sp
= getservbyport(htons(port
), proto
);
3360 Py_END_ALLOW_THREADS
3362 PyErr_SetString(socket_error
, "port/proto not found");
3365 return PyString_FromString(sp
->s_name
);
3368 PyDoc_STRVAR(getservbyport_doc
,
3369 "getservbyport(port[, protocolname]) -> string\n\
3371 Return the service name from a port number and protocol name.\n\
3372 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3373 otherwise any protocol will match.");
3375 /* Python interface to getprotobyname(name).
3376 This only returns the protocol number, since the other info is
3377 already known or not useful (like the list of aliases). */
3381 socket_getprotobyname(PyObject
*self
, PyObject
*args
)
3384 struct protoent
*sp
;
3386 /* Not available in BeOS yet. - [cjh] */
3387 PyErr_SetString(socket_error
, "getprotobyname not supported");
3390 if (!PyArg_ParseTuple(args
, "s:getprotobyname", &name
))
3392 Py_BEGIN_ALLOW_THREADS
3393 sp
= getprotobyname(name
);
3394 Py_END_ALLOW_THREADS
3396 PyErr_SetString(socket_error
, "protocol not found");
3399 return PyInt_FromLong((long) sp
->p_proto
);
3403 PyDoc_STRVAR(getprotobyname_doc
,
3404 "getprotobyname(name) -> integer\n\
3406 Return the protocol number for the named protocol. (Rarely used.)");
3409 #ifdef HAVE_SOCKETPAIR
3410 /* Create a pair of sockets using the socketpair() function.
3411 Arguments as for socket() except the default family is AF_UNIX if
3412 defined on the platform; otherwise, the default is AF_INET. */
3416 socket_socketpair(PyObject
*self
, PyObject
*args
)
3418 PySocketSockObject
*s0
= NULL
, *s1
= NULL
;
3420 int family
, type
= SOCK_STREAM
, proto
= 0;
3421 PyObject
*res
= NULL
;
3423 #if defined(AF_UNIX)
3428 if (!PyArg_ParseTuple(args
, "|iii:socketpair",
3429 &family
, &type
, &proto
))
3431 /* Create a pair of socket fds */
3432 if (socketpair(family
, type
, proto
, sv
) < 0)
3434 s0
= new_sockobject(sv
[0], family
, type
, proto
);
3437 s1
= new_sockobject(sv
[1], family
, type
, proto
);
3440 res
= PyTuple_Pack(2, s0
, s1
);
3454 PyDoc_STRVAR(socketpair_doc
,
3455 "socketpair([family[, type[, proto]]]) -> (socket object, socket object)\n\
3457 Create a pair of socket objects from the sockets returned by the platform\n\
3458 socketpair() function.\n\
3459 The arguments are the same as for socket() except the default family is\n\
3460 AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");
3462 #endif /* HAVE_SOCKETPAIR */
3466 /* Create a socket object from a numeric file description.
3467 Useful e.g. if stdin is a socket.
3468 Additional arguments as for socket(). */
3472 socket_fromfd(PyObject
*self
, PyObject
*args
)
3474 PySocketSockObject
*s
;
3476 int family
, type
, proto
= 0;
3477 if (!PyArg_ParseTuple(args
, "iii|i:fromfd",
3478 &fd
, &family
, &type
, &proto
))
3480 /* Dup the fd so it and the socket can be closed independently */
3484 s
= new_sockobject(fd
, family
, type
, proto
);
3485 return (PyObject
*) s
;
3488 PyDoc_STRVAR(fromfd_doc
,
3489 "fromfd(fd, family, type[, proto]) -> socket object\n\
3491 Create a socket object from a duplicate of the given\n\
3493 The remaining arguments are the same as for socket().");
3499 socket_ntohs(PyObject
*self
, PyObject
*args
)
3503 if (!PyArg_ParseTuple(args
, "i:ntohs", &x1
)) {
3507 PyErr_SetString(PyExc_OverflowError
,
3508 "can't convert negative number to unsigned long");
3511 x2
= (unsigned int)ntohs((unsigned short)x1
);
3512 return PyInt_FromLong(x2
);
3515 PyDoc_STRVAR(ntohs_doc
,
3516 "ntohs(integer) -> integer\n\
3518 Convert a 16-bit integer from network to host byte order.");
3522 socket_ntohl(PyObject
*self
, PyObject
*arg
)
3526 if (PyInt_Check(arg
)) {
3527 x
= PyInt_AS_LONG(arg
);
3528 if (x
== (unsigned long) -1 && PyErr_Occurred())
3531 PyErr_SetString(PyExc_OverflowError
,
3532 "can't convert negative number to unsigned long");
3536 else if (PyLong_Check(arg
)) {
3537 x
= PyLong_AsUnsignedLong(arg
);
3538 if (x
== (unsigned long) -1 && PyErr_Occurred())
3543 /* only want the trailing 32 bits */
3544 y
= x
& 0xFFFFFFFFUL
;
3546 return PyErr_Format(PyExc_OverflowError
,
3547 "long int larger than 32 bits");
3553 return PyErr_Format(PyExc_TypeError
,
3554 "expected int/long, %s found",
3555 arg
->ob_type
->tp_name
);
3556 if (x
== (unsigned long) -1 && PyErr_Occurred())
3558 return PyLong_FromUnsignedLong(ntohl(x
));
3561 PyDoc_STRVAR(ntohl_doc
,
3562 "ntohl(integer) -> integer\n\
3564 Convert a 32-bit integer from network to host byte order.");
3568 socket_htons(PyObject
*self
, PyObject
*args
)
3572 if (!PyArg_ParseTuple(args
, "i:htons", &x1
)) {
3576 PyErr_SetString(PyExc_OverflowError
,
3577 "can't convert negative number to unsigned long");
3580 x2
= (unsigned int)htons((unsigned short)x1
);
3581 return PyInt_FromLong(x2
);
3584 PyDoc_STRVAR(htons_doc
,
3585 "htons(integer) -> integer\n\
3587 Convert a 16-bit integer from host to network byte order.");
3591 socket_htonl(PyObject
*self
, PyObject
*arg
)
3595 if (PyInt_Check(arg
)) {
3596 x
= PyInt_AS_LONG(arg
);
3597 if (x
== (unsigned long) -1 && PyErr_Occurred())
3600 PyErr_SetString(PyExc_OverflowError
,
3601 "can't convert negative number to unsigned long");
3605 else if (PyLong_Check(arg
)) {
3606 x
= PyLong_AsUnsignedLong(arg
);
3607 if (x
== (unsigned long) -1 && PyErr_Occurred())
3612 /* only want the trailing 32 bits */
3613 y
= x
& 0xFFFFFFFFUL
;
3615 return PyErr_Format(PyExc_OverflowError
,
3616 "long int larger than 32 bits");
3622 return PyErr_Format(PyExc_TypeError
,
3623 "expected int/long, %s found",
3624 arg
->ob_type
->tp_name
);
3625 return PyLong_FromUnsignedLong(htonl((unsigned long)x
));
3628 PyDoc_STRVAR(htonl_doc
,
3629 "htonl(integer) -> integer\n\
3631 Convert a 32-bit integer from host to network byte order.");
3633 /* socket.inet_aton() and socket.inet_ntoa() functions. */
3635 PyDoc_STRVAR(inet_aton_doc
,
3636 "inet_aton(string) -> packed 32-bit IP representation\n\
3638 Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
3639 binary format used in low-level network functions.");
3642 socket_inet_aton(PyObject
*self
, PyObject
*args
)
3645 #define INADDR_NONE (-1)
3647 #ifdef HAVE_INET_ATON
3651 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
3652 /* Have to use inet_addr() instead */
3653 unsigned long packed_addr
;
3657 if (!PyArg_ParseTuple(args
, "s:inet_aton", &ip_addr
))
3661 #ifdef HAVE_INET_ATON
3663 #ifdef USE_INET_ATON_WEAKLINK
3664 if (inet_aton
!= NULL
) {
3666 if (inet_aton(ip_addr
, &buf
))
3667 return PyString_FromStringAndSize((char *)(&buf
),
3670 PyErr_SetString(socket_error
,
3671 "illegal IP address string passed to inet_aton");
3674 #ifdef USE_INET_ATON_WEAKLINK
3680 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
3682 /* special-case this address as inet_addr might return INADDR_NONE
3684 if (strcmp(ip_addr
, "255.255.255.255") == 0) {
3685 packed_addr
= 0xFFFFFFFF;
3688 packed_addr
= inet_addr(ip_addr
);
3690 if (packed_addr
== INADDR_NONE
) { /* invalid address */
3691 PyErr_SetString(socket_error
,
3692 "illegal IP address string passed to inet_aton");
3696 return PyString_FromStringAndSize((char *) &packed_addr
,
3697 sizeof(packed_addr
));
3699 #ifdef USE_INET_ATON_WEAKLINK
3706 PyDoc_STRVAR(inet_ntoa_doc
,
3707 "inet_ntoa(packed_ip) -> ip_address_string\n\
3709 Convert an IP address from 32-bit packed binary format to string format");
3712 socket_inet_ntoa(PyObject
*self
, PyObject
*args
)
3716 struct in_addr packed_addr
;
3718 if (!PyArg_ParseTuple(args
, "s#:inet_ntoa", &packed_str
, &addr_len
)) {
3722 if (addr_len
!= sizeof(packed_addr
)) {
3723 PyErr_SetString(socket_error
,
3724 "packed IP wrong length for inet_ntoa");
3728 memcpy(&packed_addr
, packed_str
, addr_len
);
3730 return PyString_FromString(inet_ntoa(packed_addr
));
3733 #ifdef HAVE_INET_PTON
3735 PyDoc_STRVAR(inet_pton_doc
,
3736 "inet_pton(af, ip) -> packed IP address string\n\
3738 Convert an IP address from string format to a packed string suitable\n\
3739 for use with low-level network functions.");
3742 socket_inet_pton(PyObject
*self
, PyObject
*args
)
3748 char packed
[MAX(sizeof(struct in_addr
), sizeof(struct in6_addr
))];
3750 char packed
[sizeof(struct in_addr
)];
3752 if (!PyArg_ParseTuple(args
, "is:inet_pton", &af
, &ip
)) {
3756 #if !defined(ENABLE_IPV6) && defined(AF_INET6)
3757 if(af
== AF_INET6
) {
3758 PyErr_SetString(socket_error
,
3759 "can't use AF_INET6, IPv6 is disabled");
3764 retval
= inet_pton(af
, ip
, packed
);
3766 PyErr_SetFromErrno(socket_error
);
3768 } else if (retval
== 0) {
3769 PyErr_SetString(socket_error
,
3770 "illegal IP address string passed to inet_pton");
3772 } else if (af
== AF_INET
) {
3773 return PyString_FromStringAndSize(packed
,
3774 sizeof(struct in_addr
));
3776 } else if (af
== AF_INET6
) {
3777 return PyString_FromStringAndSize(packed
,
3778 sizeof(struct in6_addr
));
3781 PyErr_SetString(socket_error
, "unknown address family");
3786 PyDoc_STRVAR(inet_ntop_doc
,
3787 "inet_ntop(af, packed_ip) -> string formatted IP address\n\
3789 Convert a packed IP address of the given family to string format.");
3792 socket_inet_ntop(PyObject
*self
, PyObject
*args
)
3799 char ip
[MAX(INET_ADDRSTRLEN
, INET6_ADDRSTRLEN
) + 1];
3801 char ip
[INET_ADDRSTRLEN
+ 1];
3804 /* Guarantee NUL-termination for PyString_FromString() below */
3805 memset((void *) &ip
[0], '\0', sizeof(ip
));
3807 if (!PyArg_ParseTuple(args
, "is#:inet_ntop", &af
, &packed
, &len
)) {
3811 if (af
== AF_INET
) {
3812 if (len
!= sizeof(struct in_addr
)) {
3813 PyErr_SetString(PyExc_ValueError
,
3814 "invalid length of packed IP address string");
3818 } else if (af
== AF_INET6
) {
3819 if (len
!= sizeof(struct in6_addr
)) {
3820 PyErr_SetString(PyExc_ValueError
,
3821 "invalid length of packed IP address string");
3826 PyErr_Format(PyExc_ValueError
,
3827 "unknown address family %d", af
);
3831 retval
= inet_ntop(af
, packed
, ip
, sizeof(ip
));
3833 PyErr_SetFromErrno(socket_error
);
3836 return PyString_FromString(retval
);
3840 PyErr_SetString(PyExc_RuntimeError
, "invalid handling of inet_ntop");
3844 #endif /* HAVE_INET_PTON */
3846 /* Python interface to getaddrinfo(host, port). */
3850 socket_getaddrinfo(PyObject
*self
, PyObject
*args
)
3852 struct addrinfo hints
, *res
;
3853 struct addrinfo
*res0
= NULL
;
3854 PyObject
*hobj
= NULL
;
3855 PyObject
*pobj
= (PyObject
*)NULL
;
3858 int family
, socktype
, protocol
, flags
;
3860 PyObject
*all
= (PyObject
*)NULL
;
3861 PyObject
*single
= (PyObject
*)NULL
;
3862 PyObject
*idna
= NULL
;
3864 family
= socktype
= protocol
= flags
= 0;
3866 if (!PyArg_ParseTuple(args
, "OO|iiii:getaddrinfo",
3867 &hobj
, &pobj
, &family
, &socktype
,
3868 &protocol
, &flags
)) {
3871 if (hobj
== Py_None
) {
3873 } else if (PyUnicode_Check(hobj
)) {
3874 idna
= PyObject_CallMethod(hobj
, "encode", "s", "idna");
3877 hptr
= PyString_AsString(idna
);
3878 } else if (PyString_Check(hobj
)) {
3879 hptr
= PyString_AsString(hobj
);
3881 PyErr_SetString(PyExc_TypeError
,
3882 "getaddrinfo() argument 1 must be string or None");
3885 if (PyInt_Check(pobj
)) {
3886 PyOS_snprintf(pbuf
, sizeof(pbuf
), "%ld", PyInt_AsLong(pobj
));
3888 } else if (PyString_Check(pobj
)) {
3889 pptr
= PyString_AsString(pobj
);
3890 } else if (pobj
== Py_None
) {
3891 pptr
= (char *)NULL
;
3893 PyErr_SetString(socket_error
, "Int or String expected");
3896 memset(&hints
, 0, sizeof(hints
));
3897 hints
.ai_family
= family
;
3898 hints
.ai_socktype
= socktype
;
3899 hints
.ai_protocol
= protocol
;
3900 hints
.ai_flags
= flags
;
3901 Py_BEGIN_ALLOW_THREADS
3902 ACQUIRE_GETADDRINFO_LOCK
3903 error
= getaddrinfo(hptr
, pptr
, &hints
, &res0
);
3904 Py_END_ALLOW_THREADS
3905 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
3907 set_gaierror(error
);
3911 if ((all
= PyList_New(0)) == NULL
)
3913 for (res
= res0
; res
; res
= res
->ai_next
) {
3915 makesockaddr(-1, res
->ai_addr
, res
->ai_addrlen
, protocol
);
3918 single
= Py_BuildValue("iiisO", res
->ai_family
,
3919 res
->ai_socktype
, res
->ai_protocol
,
3920 res
->ai_canonname
? res
->ai_canonname
: "",
3926 if (PyList_Append(all
, single
))
3940 return (PyObject
*)NULL
;
3943 PyDoc_STRVAR(getaddrinfo_doc
,
3944 "getaddrinfo(host, port [, family, socktype, proto, flags])\n\
3945 -> list of (family, socktype, proto, canonname, sockaddr)\n\
3947 Resolve host and port into addrinfo struct.");
3949 /* Python interface to getnameinfo(sa, flags). */
3953 socket_getnameinfo(PyObject
*self
, PyObject
*args
)
3955 PyObject
*sa
= (PyObject
*)NULL
;
3958 int port
, flowinfo
, scope_id
;
3959 char hbuf
[NI_MAXHOST
], pbuf
[NI_MAXSERV
];
3960 struct addrinfo hints
, *res
= NULL
;
3962 PyObject
*ret
= (PyObject
*)NULL
;
3964 flags
= flowinfo
= scope_id
= 0;
3965 if (!PyArg_ParseTuple(args
, "Oi:getnameinfo", &sa
, &flags
))
3967 if (!PyArg_ParseTuple(sa
, "si|ii",
3968 &hostp
, &port
, &flowinfo
, &scope_id
))
3970 PyOS_snprintf(pbuf
, sizeof(pbuf
), "%d", port
);
3971 memset(&hints
, 0, sizeof(hints
));
3972 hints
.ai_family
= AF_UNSPEC
;
3973 hints
.ai_socktype
= SOCK_DGRAM
; /* make numeric port happy */
3974 Py_BEGIN_ALLOW_THREADS
3975 ACQUIRE_GETADDRINFO_LOCK
3976 error
= getaddrinfo(hostp
, pbuf
, &hints
, &res
);
3977 Py_END_ALLOW_THREADS
3978 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
3980 set_gaierror(error
);
3984 PyErr_SetString(socket_error
,
3985 "sockaddr resolved to multiple addresses");
3988 switch (res
->ai_family
) {
3993 if (PyArg_ParseTuple(sa
, "si", &t1
, &t2
) == 0) {
3994 PyErr_SetString(socket_error
,
3995 "IPv4 sockaddr must be 2 tuple");
4003 struct sockaddr_in6
*sin6
;
4004 sin6
= (struct sockaddr_in6
*)res
->ai_addr
;
4005 sin6
->sin6_flowinfo
= flowinfo
;
4006 sin6
->sin6_scope_id
= scope_id
;
4011 error
= getnameinfo(res
->ai_addr
, res
->ai_addrlen
,
4012 hbuf
, sizeof(hbuf
), pbuf
, sizeof(pbuf
), flags
);
4014 set_gaierror(error
);
4017 ret
= Py_BuildValue("ss", hbuf
, pbuf
);
4025 PyDoc_STRVAR(getnameinfo_doc
,
4026 "getnameinfo(sockaddr, flags) --> (host, port)\n\
4028 Get host and port for a sockaddr.");
4031 /* Python API to getting and setting the default timeout value. */
4034 socket_getdefaulttimeout(PyObject
*self
)
4036 if (defaulttimeout
< 0.0) {
4041 return PyFloat_FromDouble(defaulttimeout
);
4044 PyDoc_STRVAR(getdefaulttimeout_doc
,
4045 "getdefaulttimeout() -> timeout\n\
4047 Returns the default timeout in floating seconds for new socket objects.\n\
4048 A value of None indicates that new socket objects have no timeout.\n\
4049 When the socket module is first imported, the default is None.");
4052 socket_setdefaulttimeout(PyObject
*self
, PyObject
*arg
)
4059 timeout
= PyFloat_AsDouble(arg
);
4060 if (timeout
< 0.0) {
4061 if (!PyErr_Occurred())
4062 PyErr_SetString(PyExc_ValueError
,
4063 "Timeout value out of range");
4068 defaulttimeout
= timeout
;
4074 PyDoc_STRVAR(setdefaulttimeout_doc
,
4075 "setdefaulttimeout(timeout)\n\
4077 Set the default timeout in floating seconds for new socket objects.\n\
4078 A value of None indicates that new socket objects have no timeout.\n\
4079 When the socket module is first imported, the default is None.");
4082 /* List of functions exported by this module. */
4084 static PyMethodDef socket_methods
[] = {
4085 {"gethostbyname", socket_gethostbyname
,
4086 METH_VARARGS
, gethostbyname_doc
},
4087 {"gethostbyname_ex", socket_gethostbyname_ex
,
4088 METH_VARARGS
, ghbn_ex_doc
},
4089 {"gethostbyaddr", socket_gethostbyaddr
,
4090 METH_VARARGS
, gethostbyaddr_doc
},
4091 {"gethostname", socket_gethostname
,
4092 METH_NOARGS
, gethostname_doc
},
4093 {"getservbyname", socket_getservbyname
,
4094 METH_VARARGS
, getservbyname_doc
},
4095 {"getservbyport", socket_getservbyport
,
4096 METH_VARARGS
, getservbyport_doc
},
4097 {"getprotobyname", socket_getprotobyname
,
4098 METH_VARARGS
, getprotobyname_doc
},
4100 {"fromfd", socket_fromfd
,
4101 METH_VARARGS
, fromfd_doc
},
4103 #ifdef HAVE_SOCKETPAIR
4104 {"socketpair", socket_socketpair
,
4105 METH_VARARGS
, socketpair_doc
},
4107 {"ntohs", socket_ntohs
,
4108 METH_VARARGS
, ntohs_doc
},
4109 {"ntohl", socket_ntohl
,
4111 {"htons", socket_htons
,
4112 METH_VARARGS
, htons_doc
},
4113 {"htonl", socket_htonl
,
4115 {"inet_aton", socket_inet_aton
,
4116 METH_VARARGS
, inet_aton_doc
},
4117 {"inet_ntoa", socket_inet_ntoa
,
4118 METH_VARARGS
, inet_ntoa_doc
},
4119 #ifdef HAVE_INET_PTON
4120 {"inet_pton", socket_inet_pton
,
4121 METH_VARARGS
, inet_pton_doc
},
4122 {"inet_ntop", socket_inet_ntop
,
4123 METH_VARARGS
, inet_ntop_doc
},
4125 {"getaddrinfo", socket_getaddrinfo
,
4126 METH_VARARGS
, getaddrinfo_doc
},
4127 {"getnameinfo", socket_getnameinfo
,
4128 METH_VARARGS
, getnameinfo_doc
},
4129 {"getdefaulttimeout", (PyCFunction
)socket_getdefaulttimeout
,
4130 METH_NOARGS
, getdefaulttimeout_doc
},
4131 {"setdefaulttimeout", socket_setdefaulttimeout
,
4132 METH_O
, setdefaulttimeout_doc
},
4133 {NULL
, NULL
} /* Sentinel */
4138 #define OS_INIT_DEFINED
4146 _kernel_swi(0x43380, &r
, &r
);
4147 taskwindow
= r
.r
[0];
4156 #define OS_INIT_DEFINED
4158 /* Additional initialization and cleanup for Windows */
4172 ret
= WSAStartup(0x0101, &WSAData
);
4174 case 0: /* No error */
4175 Py_AtExit(os_cleanup
);
4176 return 1; /* Success */
4177 case WSASYSNOTREADY
:
4178 PyErr_SetString(PyExc_ImportError
,
4179 "WSAStartup failed: network not ready");
4181 case WSAVERNOTSUPPORTED
:
4185 "WSAStartup failed: requested version not supported");
4188 PyOS_snprintf(buf
, sizeof(buf
),
4189 "WSAStartup failed: error code %d", ret
);
4190 PyErr_SetString(PyExc_ImportError
, buf
);
4193 return 0; /* Failure */
4196 #endif /* MS_WINDOWS */
4200 #define OS_INIT_DEFINED
4202 /* Additional initialization for OS/2 */
4209 int rc
= sock_init();
4212 return 1; /* Success */
4215 PyOS_snprintf(reason
, sizeof(reason
),
4216 "OS/2 TCP/IP Error# %d", sock_errno());
4217 PyErr_SetString(PyExc_ImportError
, reason
);
4219 return 0; /* Failure */
4221 /* No need to initialise sockets with GCC/EMX */
4222 return 1; /* Success */
4226 #endif /* PYOS_OS2 */
4229 #ifndef OS_INIT_DEFINED
4233 return 1; /* Success */
4238 /* C API table - always add new things to the end for binary
4241 PySocketModule_APIObject PySocketModuleAPI
=
4248 /* Initialize the _socket module.
4250 This module is actually called "_socket", and there's a wrapper
4251 "socket.py" which implements some additional functionality. On some
4252 platforms (e.g. Windows and OS/2), socket.py also implements a
4253 wrapper for the socket type that provides missing functionality such
4254 as makefile(), dup() and fromfd(). The import of "_socket" may fail
4255 with an ImportError exception if os-specific initialization fails.
4256 On Windows, this does WINSOCK initialization. When WINSOCK is
4257 initialized succesfully, a call to WSACleanup() is scheduled to be
4261 PyDoc_STRVAR(socket_doc
,
4262 "Implementation module for socket operations.\n\
4264 See the socket module for documentation.");
4269 PyObject
*m
, *has_ipv6
;
4274 sock_type
.ob_type
= &PyType_Type
;
4275 m
= Py_InitModule3(PySocket_MODULE_NAME
,
4281 socket_error
= PyErr_NewException("socket.error", NULL
, NULL
);
4282 if (socket_error
== NULL
)
4284 PySocketModuleAPI
.error
= socket_error
;
4285 Py_INCREF(socket_error
);
4286 PyModule_AddObject(m
, "error", socket_error
);
4287 socket_herror
= PyErr_NewException("socket.herror",
4288 socket_error
, NULL
);
4289 if (socket_herror
== NULL
)
4291 Py_INCREF(socket_herror
);
4292 PyModule_AddObject(m
, "herror", socket_herror
);
4293 socket_gaierror
= PyErr_NewException("socket.gaierror", socket_error
,
4295 if (socket_gaierror
== NULL
)
4297 Py_INCREF(socket_gaierror
);
4298 PyModule_AddObject(m
, "gaierror", socket_gaierror
);
4299 socket_timeout
= PyErr_NewException("socket.timeout",
4300 socket_error
, NULL
);
4301 if (socket_timeout
== NULL
)
4303 Py_INCREF(socket_timeout
);
4304 PyModule_AddObject(m
, "timeout", socket_timeout
);
4305 Py_INCREF((PyObject
*)&sock_type
);
4306 if (PyModule_AddObject(m
, "SocketType",
4307 (PyObject
*)&sock_type
) != 0)
4309 Py_INCREF((PyObject
*)&sock_type
);
4310 if (PyModule_AddObject(m
, "socket",
4311 (PyObject
*)&sock_type
) != 0)
4317 has_ipv6
= Py_False
;
4319 Py_INCREF(has_ipv6
);
4320 PyModule_AddObject(m
, "has_ipv6", has_ipv6
);
4323 if (PyModule_AddObject(m
, PySocket_CAPI_NAME
,
4324 PyCObject_FromVoidPtr((void *)&PySocketModuleAPI
, NULL
)
4328 /* Address families (we only support AF_INET and AF_UNIX) */
4330 PyModule_AddIntConstant(m
, "AF_UNSPEC", AF_UNSPEC
);
4332 PyModule_AddIntConstant(m
, "AF_INET", AF_INET
);
4334 PyModule_AddIntConstant(m
, "AF_INET6", AF_INET6
);
4335 #endif /* AF_INET6 */
4336 #if defined(AF_UNIX)
4337 PyModule_AddIntConstant(m
, "AF_UNIX", AF_UNIX
);
4338 #endif /* AF_UNIX */
4340 /* Amateur Radio AX.25 */
4341 PyModule_AddIntConstant(m
, "AF_AX25", AF_AX25
);
4344 PyModule_AddIntConstant(m
, "AF_IPX", AF_IPX
); /* Novell IPX */
4348 PyModule_AddIntConstant(m
, "AF_APPLETALK", AF_APPLETALK
);
4351 /* Amateur radio NetROM */
4352 PyModule_AddIntConstant(m
, "AF_NETROM", AF_NETROM
);
4355 /* Multiprotocol bridge */
4356 PyModule_AddIntConstant(m
, "AF_BRIDGE", AF_BRIDGE
);
4360 PyModule_AddIntConstant(m
, "AF_ATMPVC", AF_ATMPVC
);
4363 /* Reserved for Werner's ATM */
4364 PyModule_AddIntConstant(m
, "AF_AAL5", AF_AAL5
);
4367 /* Reserved for X.25 project */
4368 PyModule_AddIntConstant(m
, "AF_X25", AF_X25
);
4371 PyModule_AddIntConstant(m
, "AF_INET6", AF_INET6
); /* IP version 6 */
4374 /* Amateur Radio X.25 PLP */
4375 PyModule_AddIntConstant(m
, "AF_ROSE", AF_ROSE
);
4378 /* Reserved for DECnet project */
4379 PyModule_AddIntConstant(m
, "AF_DECnet", AF_DECnet
);
4382 /* Reserved for 802.2LLC project */
4383 PyModule_AddIntConstant(m
, "AF_NETBEUI", AF_NETBEUI
);
4386 /* Security callback pseudo AF */
4387 PyModule_AddIntConstant(m
, "AF_SECURITY", AF_SECURITY
);
4390 /* PF_KEY key management API */
4391 PyModule_AddIntConstant(m
, "AF_KEY", AF_KEY
);
4395 PyModule_AddIntConstant(m
, "AF_NETLINK", AF_NETLINK
);
4396 PyModule_AddIntConstant(m
, "NETLINK_ROUTE", NETLINK_ROUTE
);
4398 PyModule_AddIntConstant(m
, "NETLINK_SKIP", NETLINK_SKIP
);
4401 PyModule_AddIntConstant(m
, "NETLINK_W1", NETLINK_W1
);
4403 PyModule_AddIntConstant(m
, "NETLINK_USERSOCK", NETLINK_USERSOCK
);
4404 PyModule_AddIntConstant(m
, "NETLINK_FIREWALL", NETLINK_FIREWALL
);
4405 #ifdef NETLINK_TCPDIAG
4406 PyModule_AddIntConstant(m
, "NETLINK_TCPDIAG", NETLINK_TCPDIAG
);
4408 #ifdef NETLINK_NFLOG
4409 PyModule_AddIntConstant(m
, "NETLINK_NFLOG", NETLINK_NFLOG
);
4412 PyModule_AddIntConstant(m
, "NETLINK_XFRM", NETLINK_XFRM
);
4415 PyModule_AddIntConstant(m
, "NETLINK_ARPD", NETLINK_ARPD
);
4417 #ifdef NETLINK_ROUTE6
4418 PyModule_AddIntConstant(m
, "NETLINK_ROUTE6", NETLINK_ROUTE6
);
4420 PyModule_AddIntConstant(m
, "NETLINK_IP6_FW", NETLINK_IP6_FW
);
4421 #ifdef NETLINK_DNRTMSG
4422 PyModule_AddIntConstant(m
, "NETLINK_DNRTMSG", NETLINK_DNRTMSG
);
4424 #ifdef NETLINK_TAPBASE
4425 PyModule_AddIntConstant(m
, "NETLINK_TAPBASE", NETLINK_TAPBASE
);
4427 #endif /* AF_NETLINK */
4429 /* Alias to emulate 4.4BSD */
4430 PyModule_AddIntConstant(m
, "AF_ROUTE", AF_ROUTE
);
4434 PyModule_AddIntConstant(m
, "AF_ASH", AF_ASH
);
4438 PyModule_AddIntConstant(m
, "AF_ECONET", AF_ECONET
);
4442 PyModule_AddIntConstant(m
, "AF_ATMSVC", AF_ATMSVC
);
4445 /* Linux SNA Project (nutters!) */
4446 PyModule_AddIntConstant(m
, "AF_SNA", AF_SNA
);
4450 PyModule_AddIntConstant(m
, "AF_IRDA", AF_IRDA
);
4454 PyModule_AddIntConstant(m
, "AF_PPPOX", AF_PPPOX
);
4457 /* Wanpipe API Sockets */
4458 PyModule_AddIntConstant(m
, "AF_WANPIPE", AF_WANPIPE
);
4462 PyModule_AddIntConstant(m
, "AF_LLC", AF_LLC
);
4465 #ifdef USE_BLUETOOTH
4466 PyModule_AddIntConstant(m
, "AF_BLUETOOTH", AF_BLUETOOTH
);
4467 PyModule_AddIntConstant(m
, "BTPROTO_L2CAP", BTPROTO_L2CAP
);
4468 PyModule_AddIntConstant(m
, "BTPROTO_HCI", BTPROTO_HCI
);
4469 PyModule_AddIntConstant(m
, "SOL_HCI", SOL_HCI
);
4470 PyModule_AddIntConstant(m
, "HCI_TIME_STAMP", HCI_TIME_STAMP
);
4471 PyModule_AddIntConstant(m
, "HCI_DATA_DIR", HCI_DATA_DIR
);
4472 PyModule_AddIntConstant(m
, "HCI_FILTER", HCI_FILTER
);
4473 #if !defined(__FreeBSD__)
4474 PyModule_AddIntConstant(m
, "BTPROTO_SCO", BTPROTO_SCO
);
4476 PyModule_AddIntConstant(m
, "BTPROTO_RFCOMM", BTPROTO_RFCOMM
);
4477 PyModule_AddStringConstant(m
, "BDADDR_ANY", "00:00:00:00:00:00");
4478 PyModule_AddStringConstant(m
, "BDADDR_LOCAL", "00:00:00:FF:FF:FF");
4481 #ifdef HAVE_NETPACKET_PACKET_H
4482 PyModule_AddIntConstant(m
, "AF_PACKET", AF_PACKET
);
4483 PyModule_AddIntConstant(m
, "PF_PACKET", PF_PACKET
);
4484 PyModule_AddIntConstant(m
, "PACKET_HOST", PACKET_HOST
);
4485 PyModule_AddIntConstant(m
, "PACKET_BROADCAST", PACKET_BROADCAST
);
4486 PyModule_AddIntConstant(m
, "PACKET_MULTICAST", PACKET_MULTICAST
);
4487 PyModule_AddIntConstant(m
, "PACKET_OTHERHOST", PACKET_OTHERHOST
);
4488 PyModule_AddIntConstant(m
, "PACKET_OUTGOING", PACKET_OUTGOING
);
4489 PyModule_AddIntConstant(m
, "PACKET_LOOPBACK", PACKET_LOOPBACK
);
4490 PyModule_AddIntConstant(m
, "PACKET_FASTROUTE", PACKET_FASTROUTE
);
4494 PyModule_AddIntConstant(m
, "SOCK_STREAM", SOCK_STREAM
);
4495 PyModule_AddIntConstant(m
, "SOCK_DGRAM", SOCK_DGRAM
);
4497 /* We have incomplete socket support. */
4498 PyModule_AddIntConstant(m
, "SOCK_RAW", SOCK_RAW
);
4499 PyModule_AddIntConstant(m
, "SOCK_SEQPACKET", SOCK_SEQPACKET
);
4500 #if defined(SOCK_RDM)
4501 PyModule_AddIntConstant(m
, "SOCK_RDM", SOCK_RDM
);
4506 PyModule_AddIntConstant(m
, "SO_DEBUG", SO_DEBUG
);
4508 #ifdef SO_ACCEPTCONN
4509 PyModule_AddIntConstant(m
, "SO_ACCEPTCONN", SO_ACCEPTCONN
);
4512 PyModule_AddIntConstant(m
, "SO_REUSEADDR", SO_REUSEADDR
);
4514 #ifdef SO_EXCLUSIVEADDRUSE
4515 PyModule_AddIntConstant(m
, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE
);
4519 PyModule_AddIntConstant(m
, "SO_KEEPALIVE", SO_KEEPALIVE
);
4522 PyModule_AddIntConstant(m
, "SO_DONTROUTE", SO_DONTROUTE
);
4525 PyModule_AddIntConstant(m
, "SO_BROADCAST", SO_BROADCAST
);
4527 #ifdef SO_USELOOPBACK
4528 PyModule_AddIntConstant(m
, "SO_USELOOPBACK", SO_USELOOPBACK
);
4531 PyModule_AddIntConstant(m
, "SO_LINGER", SO_LINGER
);
4534 PyModule_AddIntConstant(m
, "SO_OOBINLINE", SO_OOBINLINE
);
4537 PyModule_AddIntConstant(m
, "SO_REUSEPORT", SO_REUSEPORT
);
4540 PyModule_AddIntConstant(m
, "SO_SNDBUF", SO_SNDBUF
);
4543 PyModule_AddIntConstant(m
, "SO_RCVBUF", SO_RCVBUF
);
4546 PyModule_AddIntConstant(m
, "SO_SNDLOWAT", SO_SNDLOWAT
);
4549 PyModule_AddIntConstant(m
, "SO_RCVLOWAT", SO_RCVLOWAT
);
4552 PyModule_AddIntConstant(m
, "SO_SNDTIMEO", SO_SNDTIMEO
);
4555 PyModule_AddIntConstant(m
, "SO_RCVTIMEO", SO_RCVTIMEO
);
4558 PyModule_AddIntConstant(m
, "SO_ERROR", SO_ERROR
);
4561 PyModule_AddIntConstant(m
, "SO_TYPE", SO_TYPE
);
4564 /* Maximum number of connections for "listen" */
4566 PyModule_AddIntConstant(m
, "SOMAXCONN", SOMAXCONN
);
4568 PyModule_AddIntConstant(m
, "SOMAXCONN", 5); /* Common value */
4571 /* Flags for send, recv */
4573 PyModule_AddIntConstant(m
, "MSG_OOB", MSG_OOB
);
4576 PyModule_AddIntConstant(m
, "MSG_PEEK", MSG_PEEK
);
4578 #ifdef MSG_DONTROUTE
4579 PyModule_AddIntConstant(m
, "MSG_DONTROUTE", MSG_DONTROUTE
);
4582 PyModule_AddIntConstant(m
, "MSG_DONTWAIT", MSG_DONTWAIT
);
4585 PyModule_AddIntConstant(m
, "MSG_EOR", MSG_EOR
);
4588 PyModule_AddIntConstant(m
, "MSG_TRUNC", MSG_TRUNC
);
4591 PyModule_AddIntConstant(m
, "MSG_CTRUNC", MSG_CTRUNC
);
4594 PyModule_AddIntConstant(m
, "MSG_WAITALL", MSG_WAITALL
);
4597 PyModule_AddIntConstant(m
, "MSG_BTAG", MSG_BTAG
);
4600 PyModule_AddIntConstant(m
, "MSG_ETAG", MSG_ETAG
);
4603 /* Protocol level and numbers, usable for [gs]etsockopt */
4605 PyModule_AddIntConstant(m
, "SOL_SOCKET", SOL_SOCKET
);
4608 PyModule_AddIntConstant(m
, "SOL_IP", SOL_IP
);
4610 PyModule_AddIntConstant(m
, "SOL_IP", 0);
4613 PyModule_AddIntConstant(m
, "SOL_IPX", SOL_IPX
);
4616 PyModule_AddIntConstant(m
, "SOL_AX25", SOL_AX25
);
4619 PyModule_AddIntConstant(m
, "SOL_ATALK", SOL_ATALK
);
4622 PyModule_AddIntConstant(m
, "SOL_NETROM", SOL_NETROM
);
4625 PyModule_AddIntConstant(m
, "SOL_ROSE", SOL_ROSE
);
4628 PyModule_AddIntConstant(m
, "SOL_TCP", SOL_TCP
);
4630 PyModule_AddIntConstant(m
, "SOL_TCP", 6);
4633 PyModule_AddIntConstant(m
, "SOL_UDP", SOL_UDP
);
4635 PyModule_AddIntConstant(m
, "SOL_UDP", 17);
4638 PyModule_AddIntConstant(m
, "IPPROTO_IP", IPPROTO_IP
);
4640 PyModule_AddIntConstant(m
, "IPPROTO_IP", 0);
4642 #ifdef IPPROTO_HOPOPTS
4643 PyModule_AddIntConstant(m
, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS
);
4646 PyModule_AddIntConstant(m
, "IPPROTO_ICMP", IPPROTO_ICMP
);
4648 PyModule_AddIntConstant(m
, "IPPROTO_ICMP", 1);
4651 PyModule_AddIntConstant(m
, "IPPROTO_IGMP", IPPROTO_IGMP
);
4654 PyModule_AddIntConstant(m
, "IPPROTO_GGP", IPPROTO_GGP
);
4657 PyModule_AddIntConstant(m
, "IPPROTO_IPV4", IPPROTO_IPV4
);
4660 PyModule_AddIntConstant(m
, "IPPROTO_IPV6", IPPROTO_IPV6
);
4663 PyModule_AddIntConstant(m
, "IPPROTO_IPIP", IPPROTO_IPIP
);
4666 PyModule_AddIntConstant(m
, "IPPROTO_TCP", IPPROTO_TCP
);
4668 PyModule_AddIntConstant(m
, "IPPROTO_TCP", 6);
4671 PyModule_AddIntConstant(m
, "IPPROTO_EGP", IPPROTO_EGP
);
4674 PyModule_AddIntConstant(m
, "IPPROTO_PUP", IPPROTO_PUP
);
4677 PyModule_AddIntConstant(m
, "IPPROTO_UDP", IPPROTO_UDP
);
4679 PyModule_AddIntConstant(m
, "IPPROTO_UDP", 17);
4682 PyModule_AddIntConstant(m
, "IPPROTO_IDP", IPPROTO_IDP
);
4684 #ifdef IPPROTO_HELLO
4685 PyModule_AddIntConstant(m
, "IPPROTO_HELLO", IPPROTO_HELLO
);
4688 PyModule_AddIntConstant(m
, "IPPROTO_ND", IPPROTO_ND
);
4691 PyModule_AddIntConstant(m
, "IPPROTO_TP", IPPROTO_TP
);
4694 PyModule_AddIntConstant(m
, "IPPROTO_IPV6", IPPROTO_IPV6
);
4696 #ifdef IPPROTO_ROUTING
4697 PyModule_AddIntConstant(m
, "IPPROTO_ROUTING", IPPROTO_ROUTING
);
4699 #ifdef IPPROTO_FRAGMENT
4700 PyModule_AddIntConstant(m
, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT
);
4703 PyModule_AddIntConstant(m
, "IPPROTO_RSVP", IPPROTO_RSVP
);
4706 PyModule_AddIntConstant(m
, "IPPROTO_GRE", IPPROTO_GRE
);
4709 PyModule_AddIntConstant(m
, "IPPROTO_ESP", IPPROTO_ESP
);
4712 PyModule_AddIntConstant(m
, "IPPROTO_AH", IPPROTO_AH
);
4714 #ifdef IPPROTO_MOBILE
4715 PyModule_AddIntConstant(m
, "IPPROTO_MOBILE", IPPROTO_MOBILE
);
4717 #ifdef IPPROTO_ICMPV6
4718 PyModule_AddIntConstant(m
, "IPPROTO_ICMPV6", IPPROTO_ICMPV6
);
4721 PyModule_AddIntConstant(m
, "IPPROTO_NONE", IPPROTO_NONE
);
4723 #ifdef IPPROTO_DSTOPTS
4724 PyModule_AddIntConstant(m
, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS
);
4727 PyModule_AddIntConstant(m
, "IPPROTO_XTP", IPPROTO_XTP
);
4730 PyModule_AddIntConstant(m
, "IPPROTO_EON", IPPROTO_EON
);
4733 PyModule_AddIntConstant(m
, "IPPROTO_PIM", IPPROTO_PIM
);
4735 #ifdef IPPROTO_IPCOMP
4736 PyModule_AddIntConstant(m
, "IPPROTO_IPCOMP", IPPROTO_IPCOMP
);
4739 PyModule_AddIntConstant(m
, "IPPROTO_VRRP", IPPROTO_VRRP
);
4742 PyModule_AddIntConstant(m
, "IPPROTO_BIP", IPPROTO_BIP
);
4746 PyModule_AddIntConstant(m
, "IPPROTO_RAW", IPPROTO_RAW
);
4748 PyModule_AddIntConstant(m
, "IPPROTO_RAW", 255);
4751 PyModule_AddIntConstant(m
, "IPPROTO_MAX", IPPROTO_MAX
);
4754 /* Some port configuration */
4755 #ifdef IPPORT_RESERVED
4756 PyModule_AddIntConstant(m
, "IPPORT_RESERVED", IPPORT_RESERVED
);
4758 PyModule_AddIntConstant(m
, "IPPORT_RESERVED", 1024);
4760 #ifdef IPPORT_USERRESERVED
4761 PyModule_AddIntConstant(m
, "IPPORT_USERRESERVED", IPPORT_USERRESERVED
);
4763 PyModule_AddIntConstant(m
, "IPPORT_USERRESERVED", 5000);
4766 /* Some reserved IP v.4 addresses */
4768 PyModule_AddIntConstant(m
, "INADDR_ANY", INADDR_ANY
);
4770 PyModule_AddIntConstant(m
, "INADDR_ANY", 0x00000000);
4772 #ifdef INADDR_BROADCAST
4773 PyModule_AddIntConstant(m
, "INADDR_BROADCAST", INADDR_BROADCAST
);
4775 PyModule_AddIntConstant(m
, "INADDR_BROADCAST", 0xffffffff);
4777 #ifdef INADDR_LOOPBACK
4778 PyModule_AddIntConstant(m
, "INADDR_LOOPBACK", INADDR_LOOPBACK
);
4780 PyModule_AddIntConstant(m
, "INADDR_LOOPBACK", 0x7F000001);
4782 #ifdef INADDR_UNSPEC_GROUP
4783 PyModule_AddIntConstant(m
, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP
);
4785 PyModule_AddIntConstant(m
, "INADDR_UNSPEC_GROUP", 0xe0000000);
4787 #ifdef INADDR_ALLHOSTS_GROUP
4788 PyModule_AddIntConstant(m
, "INADDR_ALLHOSTS_GROUP",
4789 INADDR_ALLHOSTS_GROUP
);
4791 PyModule_AddIntConstant(m
, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
4793 #ifdef INADDR_MAX_LOCAL_GROUP
4794 PyModule_AddIntConstant(m
, "INADDR_MAX_LOCAL_GROUP",
4795 INADDR_MAX_LOCAL_GROUP
);
4797 PyModule_AddIntConstant(m
, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
4800 PyModule_AddIntConstant(m
, "INADDR_NONE", INADDR_NONE
);
4802 PyModule_AddIntConstant(m
, "INADDR_NONE", 0xffffffff);
4805 /* IPv4 [gs]etsockopt options */
4807 PyModule_AddIntConstant(m
, "IP_OPTIONS", IP_OPTIONS
);
4810 PyModule_AddIntConstant(m
, "IP_HDRINCL", IP_HDRINCL
);
4813 PyModule_AddIntConstant(m
, "IP_TOS", IP_TOS
);
4816 PyModule_AddIntConstant(m
, "IP_TTL", IP_TTL
);
4819 PyModule_AddIntConstant(m
, "IP_RECVOPTS", IP_RECVOPTS
);
4821 #ifdef IP_RECVRETOPTS
4822 PyModule_AddIntConstant(m
, "IP_RECVRETOPTS", IP_RECVRETOPTS
);
4824 #ifdef IP_RECVDSTADDR
4825 PyModule_AddIntConstant(m
, "IP_RECVDSTADDR", IP_RECVDSTADDR
);
4828 PyModule_AddIntConstant(m
, "IP_RETOPTS", IP_RETOPTS
);
4830 #ifdef IP_MULTICAST_IF
4831 PyModule_AddIntConstant(m
, "IP_MULTICAST_IF", IP_MULTICAST_IF
);
4833 #ifdef IP_MULTICAST_TTL
4834 PyModule_AddIntConstant(m
, "IP_MULTICAST_TTL", IP_MULTICAST_TTL
);
4836 #ifdef IP_MULTICAST_LOOP
4837 PyModule_AddIntConstant(m
, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP
);
4839 #ifdef IP_ADD_MEMBERSHIP
4840 PyModule_AddIntConstant(m
, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP
);
4842 #ifdef IP_DROP_MEMBERSHIP
4843 PyModule_AddIntConstant(m
, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP
);
4845 #ifdef IP_DEFAULT_MULTICAST_TTL
4846 PyModule_AddIntConstant(m
, "IP_DEFAULT_MULTICAST_TTL",
4847 IP_DEFAULT_MULTICAST_TTL
);
4849 #ifdef IP_DEFAULT_MULTICAST_LOOP
4850 PyModule_AddIntConstant(m
, "IP_DEFAULT_MULTICAST_LOOP",
4851 IP_DEFAULT_MULTICAST_LOOP
);
4853 #ifdef IP_MAX_MEMBERSHIPS
4854 PyModule_AddIntConstant(m
, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS
);
4857 /* IPv6 [gs]etsockopt options, defined in RFC2553 */
4858 #ifdef IPV6_JOIN_GROUP
4859 PyModule_AddIntConstant(m
, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP
);
4861 #ifdef IPV6_LEAVE_GROUP
4862 PyModule_AddIntConstant(m
, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP
);
4864 #ifdef IPV6_MULTICAST_HOPS
4865 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS
);
4867 #ifdef IPV6_MULTICAST_IF
4868 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF
);
4870 #ifdef IPV6_MULTICAST_LOOP
4871 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP
);
4873 #ifdef IPV6_UNICAST_HOPS
4874 PyModule_AddIntConstant(m
, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS
);
4876 /* Additional IPV6 socket options, defined in RFC 3493 */
4878 PyModule_AddIntConstant(m
, "IPV6_V6ONLY", IPV6_V6ONLY
);
4880 /* Advanced IPV6 socket options, from RFC 3542 */
4881 #ifdef IPV6_CHECKSUM
4882 PyModule_AddIntConstant(m
, "IPV6_CHECKSUM", IPV6_CHECKSUM
);
4884 #ifdef IPV6_DONTFRAG
4885 PyModule_AddIntConstant(m
, "IPV6_DONTFRAG", IPV6_DONTFRAG
);
4888 PyModule_AddIntConstant(m
, "IPV6_DSTOPTS", IPV6_DSTOPTS
);
4890 #ifdef IPV6_HOPLIMIT
4891 PyModule_AddIntConstant(m
, "IPV6_HOPLIMIT", IPV6_HOPLIMIT
);
4894 PyModule_AddIntConstant(m
, "IPV6_HOPOPTS", IPV6_HOPOPTS
);
4897 PyModule_AddIntConstant(m
, "IPV6_NEXTHOP", IPV6_NEXTHOP
);
4900 PyModule_AddIntConstant(m
, "IPV6_PATHMTU", IPV6_PATHMTU
);
4903 PyModule_AddIntConstant(m
, "IPV6_PKTINFO", IPV6_PKTINFO
);
4905 #ifdef IPV6_RECVDSTOPTS
4906 PyModule_AddIntConstant(m
, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS
);
4908 #ifdef IPV6_RECVHOPLIMIT
4909 PyModule_AddIntConstant(m
, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT
);
4911 #ifdef IPV6_RECVHOPOPTS
4912 PyModule_AddIntConstant(m
, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS
);
4914 #ifdef IPV6_RECVPKTINFO
4915 PyModule_AddIntConstant(m
, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO
);
4917 #ifdef IPV6_RECVRTHDR
4918 PyModule_AddIntConstant(m
, "IPV6_RECVRTHDR", IPV6_RECVRTHDR
);
4920 #ifdef IPV6_RECVTCLASS
4921 PyModule_AddIntConstant(m
, "IPV6_RECVTCLASS", IPV6_RECVTCLASS
);
4924 PyModule_AddIntConstant(m
, "IPV6_RTHDR", IPV6_RTHDR
);
4926 #ifdef IPV6_RTHDRDSTOPTS
4927 PyModule_AddIntConstant(m
, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS
);
4929 #ifdef IPV6_RTHDR_TYPE_0
4930 PyModule_AddIntConstant(m
, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0
);
4932 #ifdef IPV6_RECVPATHMTU
4933 PyModule_AddIntConstant(m
, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU
);
4936 PyModule_AddIntConstant(m
, "IPV6_TCLASS", IPV6_TCLASS
);
4938 #ifdef IPV6_USE_MIN_MTU
4939 PyModule_AddIntConstant(m
, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU
);
4944 PyModule_AddIntConstant(m
, "TCP_NODELAY", TCP_NODELAY
);
4947 PyModule_AddIntConstant(m
, "TCP_MAXSEG", TCP_MAXSEG
);
4950 PyModule_AddIntConstant(m
, "TCP_CORK", TCP_CORK
);
4953 PyModule_AddIntConstant(m
, "TCP_KEEPIDLE", TCP_KEEPIDLE
);
4955 #ifdef TCP_KEEPINTVL
4956 PyModule_AddIntConstant(m
, "TCP_KEEPINTVL", TCP_KEEPINTVL
);
4959 PyModule_AddIntConstant(m
, "TCP_KEEPCNT", TCP_KEEPCNT
);
4962 PyModule_AddIntConstant(m
, "TCP_SYNCNT", TCP_SYNCNT
);
4965 PyModule_AddIntConstant(m
, "TCP_LINGER2", TCP_LINGER2
);
4967 #ifdef TCP_DEFER_ACCEPT
4968 PyModule_AddIntConstant(m
, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT
);
4970 #ifdef TCP_WINDOW_CLAMP
4971 PyModule_AddIntConstant(m
, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP
);
4974 PyModule_AddIntConstant(m
, "TCP_INFO", TCP_INFO
);
4977 PyModule_AddIntConstant(m
, "TCP_QUICKACK", TCP_QUICKACK
);
4983 PyModule_AddIntConstant(m
, "IPX_TYPE", IPX_TYPE
);
4986 /* get{addr,name}info parameters */
4987 #ifdef EAI_ADDRFAMILY
4988 PyModule_AddIntConstant(m
, "EAI_ADDRFAMILY", EAI_ADDRFAMILY
);
4991 PyModule_AddIntConstant(m
, "EAI_AGAIN", EAI_AGAIN
);
4994 PyModule_AddIntConstant(m
, "EAI_BADFLAGS", EAI_BADFLAGS
);
4997 PyModule_AddIntConstant(m
, "EAI_FAIL", EAI_FAIL
);
5000 PyModule_AddIntConstant(m
, "EAI_FAMILY", EAI_FAMILY
);
5003 PyModule_AddIntConstant(m
, "EAI_MEMORY", EAI_MEMORY
);
5006 PyModule_AddIntConstant(m
, "EAI_NODATA", EAI_NODATA
);
5009 PyModule_AddIntConstant(m
, "EAI_NONAME", EAI_NONAME
);
5012 PyModule_AddIntConstant(m
, "EAI_OVERFLOW", EAI_OVERFLOW
);
5015 PyModule_AddIntConstant(m
, "EAI_SERVICE", EAI_SERVICE
);
5018 PyModule_AddIntConstant(m
, "EAI_SOCKTYPE", EAI_SOCKTYPE
);
5021 PyModule_AddIntConstant(m
, "EAI_SYSTEM", EAI_SYSTEM
);
5024 PyModule_AddIntConstant(m
, "EAI_BADHINTS", EAI_BADHINTS
);
5027 PyModule_AddIntConstant(m
, "EAI_PROTOCOL", EAI_PROTOCOL
);
5030 PyModule_AddIntConstant(m
, "EAI_MAX", EAI_MAX
);
5033 PyModule_AddIntConstant(m
, "AI_PASSIVE", AI_PASSIVE
);
5036 PyModule_AddIntConstant(m
, "AI_CANONNAME", AI_CANONNAME
);
5038 #ifdef AI_NUMERICHOST
5039 PyModule_AddIntConstant(m
, "AI_NUMERICHOST", AI_NUMERICHOST
);
5041 #ifdef AI_NUMERICSERV
5042 PyModule_AddIntConstant(m
, "AI_NUMERICSERV", AI_NUMERICSERV
);
5045 PyModule_AddIntConstant(m
, "AI_MASK", AI_MASK
);
5048 PyModule_AddIntConstant(m
, "AI_ALL", AI_ALL
);
5050 #ifdef AI_V4MAPPED_CFG
5051 PyModule_AddIntConstant(m
, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG
);
5053 #ifdef AI_ADDRCONFIG
5054 PyModule_AddIntConstant(m
, "AI_ADDRCONFIG", AI_ADDRCONFIG
);
5057 PyModule_AddIntConstant(m
, "AI_V4MAPPED", AI_V4MAPPED
);
5060 PyModule_AddIntConstant(m
, "AI_DEFAULT", AI_DEFAULT
);
5063 PyModule_AddIntConstant(m
, "NI_MAXHOST", NI_MAXHOST
);
5066 PyModule_AddIntConstant(m
, "NI_MAXSERV", NI_MAXSERV
);
5069 PyModule_AddIntConstant(m
, "NI_NOFQDN", NI_NOFQDN
);
5071 #ifdef NI_NUMERICHOST
5072 PyModule_AddIntConstant(m
, "NI_NUMERICHOST", NI_NUMERICHOST
);
5075 PyModule_AddIntConstant(m
, "NI_NAMEREQD", NI_NAMEREQD
);
5077 #ifdef NI_NUMERICSERV
5078 PyModule_AddIntConstant(m
, "NI_NUMERICSERV", NI_NUMERICSERV
);
5081 PyModule_AddIntConstant(m
, "NI_DGRAM", NI_DGRAM
);
5084 /* shutdown() parameters */
5086 PyModule_AddIntConstant(m
, "SHUT_RD", SHUT_RD
);
5087 #elif defined(SD_RECEIVE)
5088 PyModule_AddIntConstant(m
, "SHUT_RD", SD_RECEIVE
);
5090 PyModule_AddIntConstant(m
, "SHUT_RD", 0);
5093 PyModule_AddIntConstant(m
, "SHUT_WR", SHUT_WR
);
5094 #elif defined(SD_SEND)
5095 PyModule_AddIntConstant(m
, "SHUT_WR", SD_SEND
);
5097 PyModule_AddIntConstant(m
, "SHUT_WR", 1);
5100 PyModule_AddIntConstant(m
, "SHUT_RDWR", SHUT_RDWR
);
5101 #elif defined(SD_BOTH)
5102 PyModule_AddIntConstant(m
, "SHUT_RDWR", SD_BOTH
);
5104 PyModule_AddIntConstant(m
, "SHUT_RDWR", 2);
5107 /* Initialize gethostbyname lock */
5108 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
5109 netdb_lock
= PyThread_allocate_lock();
5114 #ifndef HAVE_INET_PTON
5116 /* Simplistic emulation code for inet_pton that only works for IPv4 */
5117 /* These are not exposed because they do not set errno properly */
5120 inet_pton(int af
, const char *src
, void *dst
)
5122 if (af
== AF_INET
) {
5124 packed_addr
= inet_addr(src
);
5125 if (packed_addr
== INADDR_NONE
)
5127 memcpy(dst
, &packed_addr
, 4);
5130 /* Should set errno to EAFNOSUPPORT */
5135 inet_ntop(int af
, const void *src
, char *dst
, socklen_t size
)
5137 if (af
== AF_INET
) {
5138 struct in_addr packed_addr
;
5140 /* Should set errno to ENOSPC. */
5142 memcpy(&packed_addr
, src
, sizeof(packed_addr
));
5143 return strncpy(dst
, inet_ntoa(packed_addr
), size
);
5145 /* Should set errno to EAFNOSUPPORT */