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 SOL_HCI SOL_HCI_RAW
367 #define HCI_FILTER SO_HCI_RAW_FILTER
368 #define sockaddr_l2 sockaddr_l2cap
369 #define sockaddr_rc sockaddr_rfcomm
370 #define hci_dev hci_node
371 #define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb)
372 #define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)
373 #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
374 #elif defined(__NetBSD__)
375 #define sockaddr_l2 sockaddr_bt
376 #define sockaddr_rc sockaddr_bt
377 #define sockaddr_hci sockaddr_bt
378 #define sockaddr_sco sockaddr_bt
379 #define _BT_L2_MEMB(sa, memb) ((sa)->bt_##memb)
380 #define _BT_RC_MEMB(sa, memb) ((sa)->bt_##memb)
381 #define _BT_HCI_MEMB(sa, memb) ((sa)->bt_##memb)
382 #define _BT_SCO_MEMB(sa, memb) ((sa)->bt_##memb)
384 #define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb)
385 #define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb)
386 #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
387 #define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)
392 /* TCP/IP Services for VMS uses a maximum send/recv buffer length */
393 #define SEGMENT_SIZE (32 * 1024 -1)
396 #define SAS2SA(x) ((struct sockaddr *)(x))
399 * Constants for getnameinfo()
401 #if !defined(NI_MAXHOST)
402 #define NI_MAXHOST 1025
404 #if !defined(NI_MAXSERV)
405 #define NI_MAXSERV 32
408 /* XXX There's a problem here: *static* functions are not supposed to have
409 a Py prefix (or use CapitalizedWords). Later... */
411 /* Global variable holding the exception type for errors detected
412 by this module (but not argument type or memory errors, etc.). */
413 static PyObject
*socket_error
;
414 static PyObject
*socket_herror
;
415 static PyObject
*socket_gaierror
;
416 static PyObject
*socket_timeout
;
419 /* Global variable which is !=0 if Python is running in a RISC OS taskwindow */
420 static int taskwindow
;
423 /* A forward reference to the socket type object.
424 The sock_type variable contains pointers to various functions,
425 some of which call new_sockobject(), which uses sock_type, so
426 there has to be a circular reference. */
427 static PyTypeObject sock_type
;
429 #if defined(HAVE_POLL_H)
431 #elif defined(HAVE_SYS_POLL_H)
432 #include <sys/poll.h>
435 #ifdef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
436 /* Platform can select file descriptors beyond FD_SETSIZE */
437 #define IS_SELECTABLE(s) 1
438 #elif defined(HAVE_POLL)
439 /* Instead of select(), we'll use poll() since poll() works on any fd. */
440 #define IS_SELECTABLE(s) 1
441 /* Can we call select() with this socket without a buffer overrun? */
443 /* POSIX says selecting file descriptors beyond FD_SETSIZE
444 has undefined behaviour. If there's no timeout left, we don't have to
445 call select, so it's a safe, little white lie. */
446 #define IS_SELECTABLE(s) ((s)->sock_fd < FD_SETSIZE || s->sock_timeout <= 0.0)
452 PyErr_SetString(socket_error
, "unable to select on socket");
456 /* Convenience function to raise an error according to errno
457 and return a NULL pointer from a function. */
463 int err_no
= WSAGetLastError();
468 {WSAEINTR
, "Interrupted system call"},
469 {WSAEBADF
, "Bad file descriptor"},
470 {WSAEACCES
, "Permission denied"},
471 {WSAEFAULT
, "Bad address"},
472 {WSAEINVAL
, "Invalid argument"},
473 {WSAEMFILE
, "Too many open files"},
475 "The socket operation could not complete "
477 {WSAEINPROGRESS
, "Operation now in progress"},
478 {WSAEALREADY
, "Operation already in progress"},
479 {WSAENOTSOCK
, "Socket operation on non-socket"},
480 {WSAEDESTADDRREQ
, "Destination address required"},
481 {WSAEMSGSIZE
, "Message too long"},
482 {WSAEPROTOTYPE
, "Protocol wrong type for socket"},
483 {WSAENOPROTOOPT
, "Protocol not available"},
484 {WSAEPROTONOSUPPORT
, "Protocol not supported"},
485 {WSAESOCKTNOSUPPORT
, "Socket type not supported"},
486 {WSAEOPNOTSUPP
, "Operation not supported"},
487 {WSAEPFNOSUPPORT
, "Protocol family not supported"},
488 {WSAEAFNOSUPPORT
, "Address family not supported"},
489 {WSAEADDRINUSE
, "Address already in use"},
490 {WSAEADDRNOTAVAIL
, "Can't assign requested address"},
491 {WSAENETDOWN
, "Network is down"},
492 {WSAENETUNREACH
, "Network is unreachable"},
493 {WSAENETRESET
, "Network dropped connection on reset"},
494 {WSAECONNABORTED
, "Software caused connection abort"},
495 {WSAECONNRESET
, "Connection reset by peer"},
496 {WSAENOBUFS
, "No buffer space available"},
497 {WSAEISCONN
, "Socket is already connected"},
498 {WSAENOTCONN
, "Socket is not connected"},
499 {WSAESHUTDOWN
, "Can't send after socket shutdown"},
500 {WSAETOOMANYREFS
, "Too many references: can't splice"},
501 {WSAETIMEDOUT
, "Operation timed out"},
502 {WSAECONNREFUSED
, "Connection refused"},
503 {WSAELOOP
, "Too many levels of symbolic links"},
504 {WSAENAMETOOLONG
, "File name too long"},
505 {WSAEHOSTDOWN
, "Host is down"},
506 {WSAEHOSTUNREACH
, "No route to host"},
507 {WSAENOTEMPTY
, "Directory not empty"},
508 {WSAEPROCLIM
, "Too many processes"},
509 {WSAEUSERS
, "Too many users"},
510 {WSAEDQUOT
, "Disc quota exceeded"},
511 {WSAESTALE
, "Stale NFS file handle"},
512 {WSAEREMOTE
, "Too many levels of remote in path"},
513 {WSASYSNOTREADY
, "Network subsystem is unvailable"},
514 {WSAVERNOTSUPPORTED
, "WinSock version is not supported"},
516 "Successful WSAStartup() not yet performed"},
517 {WSAEDISCON
, "Graceful shutdown in progress"},
518 /* Resolver errors */
519 {WSAHOST_NOT_FOUND
, "No such host is known"},
520 {WSATRY_AGAIN
, "Host not found, or server failed"},
521 {WSANO_RECOVERY
, "Unexpected server error encountered"},
522 {WSANO_DATA
, "Valid name without requested data"},
523 {WSANO_ADDRESS
, "No address, look for MX record"},
528 const char *msg
= "winsock error";
530 for (msgp
= msgs
; msgp
->msg
; msgp
++) {
531 if (err_no
== msgp
->no
) {
537 v
= Py_BuildValue("(is)", err_no
, msg
);
539 PyErr_SetObject(socket_error
, v
);
547 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
548 if (sock_errno() != NO_ERROR
) {
552 int myerrorcode
= sock_errno();
554 /* Retrieve socket-related error message from MPTN.MSG file */
555 rc
= DosGetMessage(NULL
, 0, outbuf
, sizeof(outbuf
),
556 myerrorcode
- SOCBASEERR
+ 26,
559 if (rc
== NO_ERROR
) {
562 /* OS/2 doesn't guarantee a terminator */
563 outbuf
[msglen
] = '\0';
564 if (strlen(outbuf
) > 0) {
565 /* If non-empty msg, trim CRLF */
566 char *lastc
= &outbuf
[ strlen(outbuf
)-1 ];
567 while (lastc
> outbuf
&&
568 isspace(Py_CHARMASK(*lastc
))) {
569 /* Trim trailing whitespace (CRLF) */
573 v
= Py_BuildValue("(is)", myerrorcode
, outbuf
);
575 PyErr_SetObject(socket_error
, v
);
584 if (_inet_error
.errnum
!= NULL
) {
586 v
= Py_BuildValue("(is)", errno
, _inet_err());
588 PyErr_SetObject(socket_error
, v
);
595 return PyErr_SetFromErrno(socket_error
);
600 set_herror(int h_error
)
604 #ifdef HAVE_HSTRERROR
605 v
= Py_BuildValue("(is)", h_error
, (char *)hstrerror(h_error
));
607 v
= Py_BuildValue("(is)", h_error
, "host not found");
610 PyErr_SetObject(socket_herror
, v
);
619 set_gaierror(int error
)
624 /* EAI_SYSTEM is not available on Windows XP. */
625 if (error
== EAI_SYSTEM
)
629 #ifdef HAVE_GAI_STRERROR
630 v
= Py_BuildValue("(is)", error
, gai_strerror(error
));
632 v
= Py_BuildValue("(is)", error
, "getaddrinfo failed");
635 PyErr_SetObject(socket_gaierror
, v
);
643 /* Function to send in segments */
645 sendsegmented(int sock_fd
, char *buf
, int len
, int flags
)
650 while (remaining
> 0) {
651 unsigned int segment
;
653 segment
= (remaining
>= SEGMENT_SIZE
? SEGMENT_SIZE
: remaining
);
654 n
= send(sock_fd
, buf
, segment
, flags
);
658 remaining
-= segment
;
666 /* Function to perform the setting of socket blocking mode
667 internally. block = (1 | 0). */
669 internal_setblocking(PySocketSockObject
*s
, int block
)
677 Py_BEGIN_ALLOW_THREADS
680 setsockopt(s
->sock_fd
, SOL_SOCKET
, SO_NONBLOCK
,
681 (void *)(&block
), sizeof(int));
685 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
687 ioctl(s
->sock_fd
, FIONBIO
, (caddr_t
)&block
, sizeof(block
));
690 ioctl(s
->sock_fd
, FIONBIO
, (unsigned int *)&block
);
691 #else /* !PYOS_OS2 && !__VMS */
692 delay_flag
= fcntl(s
->sock_fd
, F_GETFL
, 0);
694 delay_flag
&= (~O_NONBLOCK
);
696 delay_flag
|= O_NONBLOCK
;
697 fcntl(s
->sock_fd
, F_SETFL
, delay_flag
);
698 #endif /* !PYOS_OS2 */
699 #else /* MS_WINDOWS */
701 ioctlsocket(s
->sock_fd
, FIONBIO
, (u_long
*)&block
);
702 #endif /* MS_WINDOWS */
705 socketioctl(s
->sock_fd
, FIONBIO
, (u_long
*)&block
);
707 #endif /* __BEOS__ */
710 /* Since these don't return anything */
714 /* Do a select()/poll() on the socket, if necessary (sock_timeout > 0).
715 The argument writing indicates the direction.
716 This does not raise an exception; we'll let our caller do that
717 after they've reacquired the interpreter lock.
718 Returns 1 on timeout, -1 on error, 0 otherwise. */
720 internal_select(PySocketSockObject
*s
, int writing
)
724 /* Nothing to do unless we're in timeout mode (not non-blocking) */
725 if (s
->sock_timeout
<= 0.0)
728 /* Guard against closed socket */
732 /* Prefer poll, if available, since you can poll() any fd
733 * which can't be done with select(). */
736 struct pollfd pollfd
;
739 pollfd
.fd
= s
->sock_fd
;
740 pollfd
.events
= writing
? POLLOUT
: POLLIN
;
742 /* s->sock_timeout is in seconds, timeout in ms */
743 timeout
= (int)(s
->sock_timeout
* 1000 + 0.5);
744 n
= poll(&pollfd
, 1, timeout
);
748 /* Construct the arguments to select */
751 tv
.tv_sec
= (int)s
->sock_timeout
;
752 tv
.tv_usec
= (int)((s
->sock_timeout
- tv
.tv_sec
) * 1e6
);
754 FD_SET(s
->sock_fd
, &fds
);
756 /* See if the socket is ready */
758 n
= select(s
->sock_fd
+1, NULL
, &fds
, NULL
, &tv
);
760 n
= select(s
->sock_fd
+1, &fds
, NULL
, NULL
, &tv
);
771 /* Initialize a new socket object. */
773 static double defaulttimeout
= -1.0; /* Default timeout for new sockets */
776 init_sockobject(PySocketSockObject
*s
,
777 SOCKET_T fd
, int family
, int type
, int proto
)
783 s
->sock_family
= family
;
785 s
->sock_proto
= proto
;
786 s
->sock_timeout
= defaulttimeout
;
788 s
->errorhandler
= &set_error
;
790 if (defaulttimeout
>= 0.0)
791 internal_setblocking(s
, 0);
795 socketioctl(s
->sock_fd
, 0x80046679, (u_long
*)&block
);
800 /* Create a new socket object.
801 This just creates the object and initializes it.
802 If the creation fails, return NULL and set an exception (implicit
805 static PySocketSockObject
*
806 new_sockobject(SOCKET_T fd
, int family
, int type
, int proto
)
808 PySocketSockObject
*s
;
809 s
= (PySocketSockObject
*)
810 PyType_GenericNew(&sock_type
, NULL
, NULL
);
812 init_sockobject(s
, fd
, family
, type
, proto
);
817 /* Lock to allow python interpreter to continue, but only allow one
818 thread to be in gethostbyname or getaddrinfo */
819 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
820 PyThread_type_lock netdb_lock
;
824 /* Convert a string specifying a host name or one of a few symbolic
825 names to a numeric IP address. This usually calls gethostbyname()
826 to do the work; the names "" and "<broadcast>" are special.
827 Return the length (IPv4 should be 4 bytes), or negative if
828 an error occurred; then an exception is raised. */
831 setipaddr(char *name
, struct sockaddr
*addr_ret
, size_t addr_ret_size
, int af
)
833 struct addrinfo hints
, *res
;
838 memset((void *) addr_ret
, '\0', sizeof(*addr_ret
));
839 if (name
[0] == '\0') {
841 memset(&hints
, 0, sizeof(hints
));
842 hints
.ai_family
= af
;
843 hints
.ai_socktype
= SOCK_DGRAM
; /*dummy*/
844 hints
.ai_flags
= AI_PASSIVE
;
845 Py_BEGIN_ALLOW_THREADS
846 ACQUIRE_GETADDRINFO_LOCK
847 error
= getaddrinfo(NULL
, "0", &hints
, &res
);
849 /* We assume that those thread-unsafe getaddrinfo() versions
850 *are* safe regarding their return value, ie. that a
851 subsequent call to getaddrinfo() does not destroy the
852 outcome of the first call. */
853 RELEASE_GETADDRINFO_LOCK
858 switch (res
->ai_family
) {
869 PyErr_SetString(socket_error
,
870 "unsupported address family");
875 PyErr_SetString(socket_error
,
876 "wildcard resolved to multiple address");
879 if (res
->ai_addrlen
< addr_ret_size
)
880 addr_ret_size
= res
->ai_addrlen
;
881 memcpy(addr_ret
, res
->ai_addr
, addr_ret_size
);
885 if (name
[0] == '<' && strcmp(name
, "<broadcast>") == 0) {
886 struct sockaddr_in
*sin
;
887 if (af
!= AF_INET
&& af
!= AF_UNSPEC
) {
888 PyErr_SetString(socket_error
,
889 "address family mismatched");
892 sin
= (struct sockaddr_in
*)addr_ret
;
893 memset((void *) sin
, '\0', sizeof(*sin
));
894 sin
->sin_family
= AF_INET
;
895 #ifdef HAVE_SOCKADDR_SA_LEN
896 sin
->sin_len
= sizeof(*sin
);
898 sin
->sin_addr
.s_addr
= INADDR_BROADCAST
;
899 return sizeof(sin
->sin_addr
);
901 if (sscanf(name
, "%d.%d.%d.%d%c", &d1
, &d2
, &d3
, &d4
, &ch
) == 4 &&
902 0 <= d1
&& d1
<= 255 && 0 <= d2
&& d2
<= 255 &&
903 0 <= d3
&& d3
<= 255 && 0 <= d4
&& d4
<= 255) {
904 struct sockaddr_in
*sin
;
905 sin
= (struct sockaddr_in
*)addr_ret
;
906 sin
->sin_addr
.s_addr
= htonl(
907 ((long) d1
<< 24) | ((long) d2
<< 16) |
908 ((long) d3
<< 8) | ((long) d4
<< 0));
909 sin
->sin_family
= AF_INET
;
910 #ifdef HAVE_SOCKADDR_SA_LEN
911 sin
->sin_len
= sizeof(*sin
);
915 memset(&hints
, 0, sizeof(hints
));
916 hints
.ai_family
= af
;
917 Py_BEGIN_ALLOW_THREADS
918 ACQUIRE_GETADDRINFO_LOCK
919 error
= getaddrinfo(name
, NULL
, &hints
, &res
);
920 #if defined(__digital__) && defined(__unix__)
921 if (error
== EAI_NONAME
&& af
== AF_UNSPEC
) {
922 /* On Tru64 V5.1, numeric-to-addr conversion fails
923 if no address family is given. Assume IPv4 for now.*/
924 hints
.ai_family
= AF_INET
;
925 error
= getaddrinfo(name
, NULL
, &hints
, &res
);
929 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
934 if (res
->ai_addrlen
< addr_ret_size
)
935 addr_ret_size
= res
->ai_addrlen
;
936 memcpy((char *) addr_ret
, res
->ai_addr
, addr_ret_size
);
938 switch (addr_ret
->sa_family
) {
946 PyErr_SetString(socket_error
, "unknown address family");
952 /* Create a string object representing an IP address.
953 This is always a string of the form 'dd.dd.dd.dd' (with variable
957 makeipaddr(struct sockaddr
*addr
, int addrlen
)
959 char buf
[NI_MAXHOST
];
962 error
= getnameinfo(addr
, addrlen
, buf
, sizeof(buf
), NULL
, 0,
968 return PyString_FromString(buf
);
973 /* Convert a string representation of a Bluetooth address into a numeric
974 address. Returns the length (6), or raises an exception and returns -1 if
975 an error occurred. */
978 setbdaddr(char *name
, bdaddr_t
*bdaddr
)
980 unsigned int b0
, b1
, b2
, b3
, b4
, b5
;
984 n
= sscanf(name
, "%X:%X:%X:%X:%X:%X%c",
985 &b5
, &b4
, &b3
, &b2
, &b1
, &b0
, &ch
);
986 if (n
== 6 && (b0
| b1
| b2
| b3
| b4
| b5
) < 256) {
995 PyErr_SetString(socket_error
, "bad bluetooth address");
1000 /* Create a string representation of the Bluetooth address. This is always a
1001 string of the form 'XX:XX:XX:XX:XX:XX' where XX is a two digit hexadecimal
1002 value (zero padded if necessary). */
1005 makebdaddr(bdaddr_t
*bdaddr
)
1007 char buf
[(6 * 2) + 5 + 1];
1009 sprintf(buf
, "%02X:%02X:%02X:%02X:%02X:%02X",
1010 bdaddr
->b
[5], bdaddr
->b
[4], bdaddr
->b
[3],
1011 bdaddr
->b
[2], bdaddr
->b
[1], bdaddr
->b
[0]);
1012 return PyString_FromString(buf
);
1017 /* Create an object representing the given socket address,
1018 suitable for passing it back to bind(), connect() etc.
1019 The family field of the sockaddr structure is inspected
1020 to determine what kind of address it really is. */
1024 makesockaddr(int sockfd
, struct sockaddr
*addr
, int addrlen
, int proto
)
1027 /* No address -- may be recvfrom() from known socket */
1033 /* XXX: BeOS version of accept() doesn't set family correctly */
1034 addr
->sa_family
= AF_INET
;
1037 switch (addr
->sa_family
) {
1041 struct sockaddr_in
*a
;
1042 PyObject
*addrobj
= makeipaddr(addr
, sizeof(*a
));
1043 PyObject
*ret
= NULL
;
1045 a
= (struct sockaddr_in
*)addr
;
1046 ret
= Py_BuildValue("Oi", addrobj
, ntohs(a
->sin_port
));
1052 #if defined(AF_UNIX)
1055 struct sockaddr_un
*a
= (struct sockaddr_un
*) addr
;
1057 if (a
->sun_path
[0] == 0) { /* Linux abstract namespace */
1058 addrlen
-= (sizeof(*a
) - sizeof(a
->sun_path
));
1059 return PyString_FromStringAndSize(a
->sun_path
,
1065 /* regular NULL-terminated string */
1066 return PyString_FromString(a
->sun_path
);
1069 #endif /* AF_UNIX */
1071 #if defined(AF_NETLINK)
1074 struct sockaddr_nl
*a
= (struct sockaddr_nl
*) addr
;
1075 return Py_BuildValue("II", a
->nl_pid
, a
->nl_groups
);
1077 #endif /* AF_NETLINK */
1082 struct sockaddr_in6
*a
;
1083 PyObject
*addrobj
= makeipaddr(addr
, sizeof(*a
));
1084 PyObject
*ret
= NULL
;
1086 a
= (struct sockaddr_in6
*)addr
;
1087 ret
= Py_BuildValue("Oiii",
1089 ntohs(a
->sin6_port
),
1098 #ifdef USE_BLUETOOTH
1104 struct sockaddr_l2
*a
= (struct sockaddr_l2
*) addr
;
1105 PyObject
*addrobj
= makebdaddr(&_BT_L2_MEMB(a
, bdaddr
));
1106 PyObject
*ret
= NULL
;
1108 ret
= Py_BuildValue("Oi",
1110 _BT_L2_MEMB(a
, psm
));
1116 case BTPROTO_RFCOMM
:
1118 struct sockaddr_rc
*a
= (struct sockaddr_rc
*) addr
;
1119 PyObject
*addrobj
= makebdaddr(&_BT_RC_MEMB(a
, bdaddr
));
1120 PyObject
*ret
= NULL
;
1122 ret
= Py_BuildValue("Oi",
1124 _BT_RC_MEMB(a
, channel
));
1132 struct sockaddr_hci
*a
= (struct sockaddr_hci
*) addr
;
1133 PyObject
*ret
= NULL
;
1134 ret
= Py_BuildValue("i", _BT_HCI_MEMB(a
, dev
));
1138 #if !defined(__FreeBSD__)
1141 struct sockaddr_sco
*a
= (struct sockaddr_sco
*) addr
;
1142 return makebdaddr(&_BT_SCO_MEMB(a
, bdaddr
));
1149 #ifdef HAVE_NETPACKET_PACKET_H
1152 struct sockaddr_ll
*a
= (struct sockaddr_ll
*)addr
;
1155 /* need to look up interface name give index */
1156 if (a
->sll_ifindex
) {
1157 ifr
.ifr_ifindex
= a
->sll_ifindex
;
1158 if (ioctl(sockfd
, SIOCGIFNAME
, &ifr
) == 0)
1159 ifname
= ifr
.ifr_name
;
1161 return Py_BuildValue("shbhs#",
1163 ntohs(a
->sll_protocol
),
1171 /* More cases here... */
1174 /* If we don't know the address family, don't raise an
1175 exception -- return it as a tuple. */
1176 return Py_BuildValue("is#",
1179 sizeof(addr
->sa_data
));
1185 /* Parse a socket address argument according to the socket object's
1186 address family. Return 1 if the address was in the proper format,
1187 0 of not. The address is returned through addr_ret, its length
1191 getsockaddrarg(PySocketSockObject
*s
, PyObject
*args
,
1192 struct sockaddr
*addr_ret
, int *len_ret
)
1194 switch (s
->sock_family
) {
1196 #if defined(AF_UNIX)
1199 struct sockaddr_un
* addr
;
1202 if (!PyArg_Parse(args
, "t#", &path
, &len
))
1205 addr
= (struct sockaddr_un
*)addr_ret
;
1207 if (len
> 0 && path
[0] == 0) {
1208 /* Linux abstract namespace extension */
1209 if (len
> sizeof addr
->sun_path
) {
1210 PyErr_SetString(socket_error
,
1211 "AF_UNIX path too long");
1218 /* regular NULL-terminated string */
1219 if (len
>= sizeof addr
->sun_path
) {
1220 PyErr_SetString(socket_error
,
1221 "AF_UNIX path too long");
1224 addr
->sun_path
[len
] = 0;
1226 addr
->sun_family
= s
->sock_family
;
1227 memcpy(addr
->sun_path
, path
, len
);
1228 #if defined(PYOS_OS2)
1229 *len_ret
= sizeof(*addr
);
1231 *len_ret
= len
+ sizeof(*addr
) - sizeof(addr
->sun_path
);
1235 #endif /* AF_UNIX */
1237 #if defined(AF_NETLINK)
1240 struct sockaddr_nl
* addr
;
1242 addr
= (struct sockaddr_nl
*)addr_ret
;
1243 if (!PyTuple_Check(args
)) {
1247 "AF_NETLINK address must be tuple, not %.500s",
1248 Py_Type(args
)->tp_name
);
1251 if (!PyArg_ParseTuple(args
, "II:getsockaddrarg", &pid
, &groups
))
1253 addr
->nl_family
= AF_NETLINK
;
1255 addr
->nl_groups
= groups
;
1256 *len_ret
= sizeof(*addr
);
1263 struct sockaddr_in
* addr
;
1266 if (!PyTuple_Check(args
)) {
1270 "AF_INET address must be tuple, not %.500s",
1271 Py_Type(args
)->tp_name
);
1274 if (!PyArg_ParseTuple(args
, "eti:getsockaddrarg",
1275 "idna", &host
, &port
))
1277 addr
=(struct sockaddr_in
*)addr_ret
;
1278 result
= setipaddr(host
, (struct sockaddr
*)addr
,
1279 sizeof(*addr
), AF_INET
);
1283 addr
->sin_family
= AF_INET
;
1284 addr
->sin_port
= htons((short)port
);
1285 *len_ret
= sizeof *addr
;
1292 struct sockaddr_in6
* addr
;
1294 int port
, flowinfo
, scope_id
, result
;
1295 flowinfo
= scope_id
= 0;
1296 if (!PyTuple_Check(args
)) {
1300 "AF_INET6 address must be tuple, not %.500s",
1301 Py_Type(args
)->tp_name
);
1304 if (!PyArg_ParseTuple(args
, "eti|ii",
1305 "idna", &host
, &port
, &flowinfo
,
1309 addr
= (struct sockaddr_in6
*)addr_ret
;
1310 result
= setipaddr(host
, (struct sockaddr
*)addr
,
1311 sizeof(*addr
), AF_INET6
);
1315 addr
->sin6_family
= s
->sock_family
;
1316 addr
->sin6_port
= htons((short)port
);
1317 addr
->sin6_flowinfo
= flowinfo
;
1318 addr
->sin6_scope_id
= scope_id
;
1319 *len_ret
= sizeof *addr
;
1324 #ifdef USE_BLUETOOTH
1327 switch (s
->sock_proto
) {
1330 struct sockaddr_l2
*addr
;
1333 addr
= (struct sockaddr_l2
*)addr_ret
;
1334 _BT_L2_MEMB(addr
, family
) = AF_BLUETOOTH
;
1335 if (!PyArg_ParseTuple(args
, "si", &straddr
,
1336 &_BT_L2_MEMB(addr
, psm
))) {
1337 PyErr_SetString(socket_error
, "getsockaddrarg: "
1341 if (setbdaddr(straddr
, &_BT_L2_MEMB(addr
, bdaddr
)) < 0)
1344 *len_ret
= sizeof *addr
;
1347 case BTPROTO_RFCOMM
:
1349 struct sockaddr_rc
*addr
;
1352 addr
= (struct sockaddr_rc
*)addr_ret
;
1353 _BT_RC_MEMB(addr
, family
) = AF_BLUETOOTH
;
1354 if (!PyArg_ParseTuple(args
, "si", &straddr
,
1355 &_BT_RC_MEMB(addr
, channel
))) {
1356 PyErr_SetString(socket_error
, "getsockaddrarg: "
1360 if (setbdaddr(straddr
, &_BT_RC_MEMB(addr
, bdaddr
)) < 0)
1363 *len_ret
= sizeof *addr
;
1368 struct sockaddr_hci
*addr
= (struct sockaddr_hci
*)addr_ret
;
1369 _BT_HCI_MEMB(addr
, family
) = AF_BLUETOOTH
;
1370 if (!PyArg_ParseTuple(args
, "i", &_BT_HCI_MEMB(addr
, dev
))) {
1371 PyErr_SetString(socket_error
, "getsockaddrarg: "
1375 *len_ret
= sizeof *addr
;
1378 #if !defined(__FreeBSD__)
1381 struct sockaddr_sco
*addr
;
1384 addr
= (struct sockaddr_sco
*)addr_ret
;
1385 _BT_SCO_MEMB(addr
, family
) = AF_BLUETOOTH
;
1386 straddr
= PyString_AsString(args
);
1387 if (straddr
== NULL
) {
1388 PyErr_SetString(socket_error
, "getsockaddrarg: "
1392 if (setbdaddr(straddr
, &_BT_SCO_MEMB(addr
, bdaddr
)) < 0)
1395 *len_ret
= sizeof *addr
;
1400 PyErr_SetString(socket_error
, "getsockaddrarg: unknown Bluetooth protocol");
1406 #ifdef HAVE_NETPACKET_PACKET_H
1409 struct sockaddr_ll
* addr
;
1411 char *interfaceName
;
1416 unsigned int halen
= 0;
1418 if (!PyTuple_Check(args
)) {
1422 "AF_PACKET address must be tuple, not %.500s",
1423 Py_Type(args
)->tp_name
);
1426 if (!PyArg_ParseTuple(args
, "si|iis#", &interfaceName
,
1427 &protoNumber
, &pkttype
, &hatype
,
1430 strncpy(ifr
.ifr_name
, interfaceName
, sizeof(ifr
.ifr_name
));
1431 ifr
.ifr_name
[(sizeof(ifr
.ifr_name
))-1] = '\0';
1432 if (ioctl(s
->sock_fd
, SIOCGIFINDEX
, &ifr
) < 0) {
1437 PyErr_SetString(PyExc_ValueError
,
1438 "Hardware address must be 8 bytes or less");
1441 addr
= (struct sockaddr_ll
*)addr_ret
;
1442 addr
->sll_family
= AF_PACKET
;
1443 addr
->sll_protocol
= htons((short)protoNumber
);
1444 addr
->sll_ifindex
= ifr
.ifr_ifindex
;
1445 addr
->sll_pkttype
= pkttype
;
1446 addr
->sll_hatype
= hatype
;
1448 memcpy(&addr
->sll_addr
, haddr
, halen
);
1450 addr
->sll_halen
= halen
;
1451 *len_ret
= sizeof *addr
;
1456 /* More cases here... */
1459 PyErr_SetString(socket_error
, "getsockaddrarg: bad family");
1466 /* Get the address length according to the socket object's address family.
1467 Return 1 if the family is known, 0 otherwise. The length is returned
1471 getsockaddrlen(PySocketSockObject
*s
, socklen_t
*len_ret
)
1473 switch (s
->sock_family
) {
1475 #if defined(AF_UNIX)
1478 *len_ret
= sizeof (struct sockaddr_un
);
1481 #endif /* AF_UNIX */
1482 #if defined(AF_NETLINK)
1485 *len_ret
= sizeof (struct sockaddr_nl
);
1492 *len_ret
= sizeof (struct sockaddr_in
);
1499 *len_ret
= sizeof (struct sockaddr_in6
);
1504 #ifdef USE_BLUETOOTH
1507 switch(s
->sock_proto
)
1511 *len_ret
= sizeof (struct sockaddr_l2
);
1513 case BTPROTO_RFCOMM
:
1514 *len_ret
= sizeof (struct sockaddr_rc
);
1517 *len_ret
= sizeof (struct sockaddr_hci
);
1519 #if !defined(__FreeBSD__)
1521 *len_ret
= sizeof (struct sockaddr_sco
);
1525 PyErr_SetString(socket_error
, "getsockaddrlen: "
1526 "unknown BT protocol");
1533 #ifdef HAVE_NETPACKET_PACKET_H
1536 *len_ret
= sizeof (struct sockaddr_ll
);
1541 /* More cases here... */
1544 PyErr_SetString(socket_error
, "getsockaddrlen: bad family");
1551 /* s.accept() method */
1554 sock_accept(PySocketSockObject
*s
)
1556 sock_addr_t addrbuf
;
1559 PyObject
*sock
= NULL
;
1560 PyObject
*addr
= NULL
;
1561 PyObject
*res
= NULL
;
1564 if (!getsockaddrlen(s
, &addrlen
))
1566 memset(&addrbuf
, 0, addrlen
);
1569 newfd
= INVALID_SOCKET
;
1574 if (!IS_SELECTABLE(s
))
1575 return select_error();
1577 Py_BEGIN_ALLOW_THREADS
1578 timeout
= internal_select(s
, 0);
1580 newfd
= accept(s
->sock_fd
, SAS2SA(&addrbuf
), &addrlen
);
1581 Py_END_ALLOW_THREADS
1584 PyErr_SetString(socket_timeout
, "timed out");
1589 if (newfd
== INVALID_SOCKET
)
1593 return s
->errorhandler();
1595 /* Create the new object with unspecified family,
1596 to avoid calls to bind() etc. on it. */
1597 sock
= (PyObject
*) new_sockobject(newfd
,
1606 addr
= makesockaddr(s
->sock_fd
, SAS2SA(&addrbuf
),
1607 addrlen
, s
->sock_proto
);
1611 res
= PyTuple_Pack(2, sock
, addr
);
1619 PyDoc_STRVAR(accept_doc
,
1620 "accept() -> (socket object, address info)\n\
1622 Wait for an incoming connection. Return a new socket representing the\n\
1623 connection, and the address of the client. For IP sockets, the address\n\
1624 info is a pair (hostaddr, port).");
1626 /* s.setblocking(flag) method. Argument:
1627 False -- non-blocking mode; same as settimeout(0)
1628 True -- blocking mode; same as settimeout(None)
1632 sock_setblocking(PySocketSockObject
*s
, PyObject
*arg
)
1636 block
= PyInt_AsLong(arg
);
1637 if (block
== -1 && PyErr_Occurred())
1640 s
->sock_timeout
= block
? -1.0 : 0.0;
1641 internal_setblocking(s
, block
);
1647 PyDoc_STRVAR(setblocking_doc
,
1648 "setblocking(flag)\n\
1650 Set the socket to blocking (flag is true) or non-blocking (false).\n\
1651 setblocking(True) is equivalent to settimeout(None);\n\
1652 setblocking(False) is equivalent to settimeout(0.0).");
1654 /* s.settimeout(timeout) method. Argument:
1655 None -- no timeout, blocking mode; same as setblocking(True)
1656 0.0 -- non-blocking mode; same as setblocking(False)
1657 > 0 -- timeout mode; operations time out after timeout seconds
1658 < 0 -- illegal; raises an exception
1661 sock_settimeout(PySocketSockObject
*s
, PyObject
*arg
)
1668 timeout
= PyFloat_AsDouble(arg
);
1669 if (timeout
< 0.0) {
1670 if (!PyErr_Occurred())
1671 PyErr_SetString(PyExc_ValueError
,
1672 "Timeout value out of range");
1677 s
->sock_timeout
= timeout
;
1678 internal_setblocking(s
, timeout
< 0.0);
1684 PyDoc_STRVAR(settimeout_doc
,
1685 "settimeout(timeout)\n\
1687 Set a timeout on socket operations. 'timeout' can be a float,\n\
1688 giving in seconds, or None. Setting a timeout of None disables\n\
1689 the timeout feature and is equivalent to setblocking(1).\n\
1690 Setting a timeout of zero is the same as setblocking(0).");
1692 /* s.gettimeout() method.
1693 Returns the timeout associated with a socket. */
1695 sock_gettimeout(PySocketSockObject
*s
)
1697 if (s
->sock_timeout
< 0.0) {
1702 return PyFloat_FromDouble(s
->sock_timeout
);
1705 PyDoc_STRVAR(gettimeout_doc
,
1706 "gettimeout() -> timeout\n\
1708 Returns the timeout in floating seconds associated with socket \n\
1709 operations. A timeout of None indicates that timeouts on socket \n\
1710 operations are disabled.");
1713 /* s.sleeptaskw(1 | 0) method */
1716 sock_sleeptaskw(PySocketSockObject
*s
,PyObject
*arg
)
1719 block
= PyInt_AsLong(arg
);
1720 if (block
== -1 && PyErr_Occurred())
1722 Py_BEGIN_ALLOW_THREADS
1723 socketioctl(s
->sock_fd
, 0x80046679, (u_long
*)&block
);
1724 Py_END_ALLOW_THREADS
1729 PyDoc_STRVAR(sleeptaskw_doc
,
1730 "sleeptaskw(flag)\n\
1732 Allow sleeps in taskwindows.");
1736 /* s.setsockopt() method.
1737 With an integer third argument, sets an integer option.
1738 With a string third argument, sets an option from a buffer;
1739 use optional built-in module 'struct' to encode the string. */
1742 sock_setsockopt(PySocketSockObject
*s
, PyObject
*args
)
1751 if (PyArg_ParseTuple(args
, "iii:setsockopt",
1752 &level
, &optname
, &flag
)) {
1753 buf
= (char *) &flag
;
1754 buflen
= sizeof flag
;
1758 if (!PyArg_ParseTuple(args
, "iis#:setsockopt",
1759 &level
, &optname
, &buf
, &buflen
))
1762 res
= setsockopt(s
->sock_fd
, level
, optname
, (void *)buf
, buflen
);
1764 return s
->errorhandler();
1769 PyDoc_STRVAR(setsockopt_doc
,
1770 "setsockopt(level, option, value)\n\
1772 Set a socket option. See the Unix manual for level and option.\n\
1773 The value argument can either be an integer or a string.");
1776 /* s.getsockopt() method.
1777 With two arguments, retrieves an integer option.
1778 With a third integer argument, retrieves a string buffer of that size;
1779 use optional built-in module 'struct' to decode the string. */
1782 sock_getsockopt(PySocketSockObject
*s
, PyObject
*args
)
1788 socklen_t buflen
= 0;
1791 /* We have incomplete socket support. */
1792 PyErr_SetString(socket_error
, "getsockopt not supported");
1796 if (!PyArg_ParseTuple(args
, "ii|i:getsockopt",
1797 &level
, &optname
, &buflen
))
1802 socklen_t flagsize
= sizeof flag
;
1803 res
= getsockopt(s
->sock_fd
, level
, optname
,
1804 (void *)&flag
, &flagsize
);
1806 return s
->errorhandler();
1807 return PyInt_FromLong(flag
);
1810 /* socklen_t is unsigned so no negative test is needed,
1811 test buflen == 0 is previously done */
1812 if (buflen
> 1024) {
1814 if (buflen
<= 0 || buflen
> 1024) {
1816 PyErr_SetString(socket_error
,
1817 "getsockopt buflen out of range");
1820 buf
= PyString_FromStringAndSize((char *)NULL
, buflen
);
1823 res
= getsockopt(s
->sock_fd
, level
, optname
,
1824 (void *)PyString_AS_STRING(buf
), &buflen
);
1827 return s
->errorhandler();
1829 _PyString_Resize(&buf
, buflen
);
1831 #endif /* __BEOS__ */
1834 PyDoc_STRVAR(getsockopt_doc
,
1835 "getsockopt(level, option[, buffersize]) -> value\n\
1837 Get a socket option. See the Unix manual for level and option.\n\
1838 If a nonzero buffersize argument is given, the return value is a\n\
1839 string of that length; otherwise it is an integer.");
1842 /* s.bind(sockaddr) method */
1845 sock_bind(PySocketSockObject
*s
, PyObject
*addro
)
1847 sock_addr_t addrbuf
;
1851 if (!getsockaddrarg(s
, addro
, SAS2SA(&addrbuf
), &addrlen
))
1853 Py_BEGIN_ALLOW_THREADS
1854 res
= bind(s
->sock_fd
, SAS2SA(&addrbuf
), addrlen
);
1855 Py_END_ALLOW_THREADS
1857 return s
->errorhandler();
1862 PyDoc_STRVAR(bind_doc
,
1865 Bind the socket to a local address. For IP sockets, the address is a\n\
1866 pair (host, port); the host must refer to the local host. For raw packet\n\
1867 sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");
1870 /* s.close() method.
1871 Set the file descriptor to -1 so operations tried subsequently
1872 will surely fail. */
1875 sock_close(PySocketSockObject
*s
)
1879 if ((fd
= s
->sock_fd
) != -1) {
1881 Py_BEGIN_ALLOW_THREADS
1882 (void) SOCKETCLOSE(fd
);
1883 Py_END_ALLOW_THREADS
1889 PyDoc_STRVAR(close_doc
,
1892 Close the socket. It cannot be used after this call.");
1895 internal_connect(PySocketSockObject
*s
, struct sockaddr
*addr
, int addrlen
,
1901 res
= connect(s
->sock_fd
, addr
, addrlen
);
1905 if (s
->sock_timeout
> 0.0) {
1906 if (res
< 0 && WSAGetLastError() == WSAEWOULDBLOCK
&&
1908 /* This is a mess. Best solution: trust select */
1912 tv
.tv_sec
= (int)s
->sock_timeout
;
1913 tv
.tv_usec
= (int)((s
->sock_timeout
- tv
.tv_sec
) * 1e6
);
1915 FD_SET(s
->sock_fd
, &fds
);
1917 FD_SET(s
->sock_fd
, &fds_exc
);
1918 res
= select(s
->sock_fd
+1, NULL
, &fds
, &fds_exc
, &tv
);
1920 res
= WSAEWOULDBLOCK
;
1922 } else if (res
> 0) {
1923 if (FD_ISSET(s
->sock_fd
, &fds
))
1924 /* The socket is in the writeable set - this
1928 /* As per MS docs, we need to call getsockopt()
1929 to get the underlying error */
1930 int res_size
= sizeof res
;
1931 /* It must be in the exception set */
1932 assert(FD_ISSET(s
->sock_fd
, &fds_exc
));
1933 if (0 == getsockopt(s
->sock_fd
, SOL_SOCKET
, SO_ERROR
,
1934 (char *)&res
, &res_size
))
1935 /* getsockopt also clears WSAGetLastError,
1936 so reset it back. */
1937 WSASetLastError(res
);
1939 res
= WSAGetLastError();
1942 /* else if (res < 0) an error occurred */
1947 res
= WSAGetLastError();
1951 if (s
->sock_timeout
> 0.0) {
1952 if (res
< 0 && errno
== EINPROGRESS
&& IS_SELECTABLE(s
)) {
1953 timeout
= internal_select(s
, 1);
1955 res
= connect(s
->sock_fd
, addr
, addrlen
);
1956 if (res
< 0 && errno
== EISCONN
)
1959 else if (timeout
== -1)
1960 res
= errno
; /* had error */
1962 res
= EWOULDBLOCK
; /* timed out */
1970 *timeoutp
= timeout
;
1975 /* s.connect(sockaddr) method */
1978 sock_connect(PySocketSockObject
*s
, PyObject
*addro
)
1980 sock_addr_t addrbuf
;
1985 if (!getsockaddrarg(s
, addro
, SAS2SA(&addrbuf
), &addrlen
))
1988 Py_BEGIN_ALLOW_THREADS
1989 res
= internal_connect(s
, SAS2SA(&addrbuf
), addrlen
, &timeout
);
1990 Py_END_ALLOW_THREADS
1993 PyErr_SetString(socket_timeout
, "timed out");
1997 return s
->errorhandler();
2002 PyDoc_STRVAR(connect_doc
,
2003 "connect(address)\n\
2005 Connect the socket to a remote address. For IP sockets, the address\n\
2006 is a pair (host, port).");
2009 /* s.connect_ex(sockaddr) method */
2012 sock_connect_ex(PySocketSockObject
*s
, PyObject
*addro
)
2014 sock_addr_t addrbuf
;
2019 if (!getsockaddrarg(s
, addro
, SAS2SA(&addrbuf
), &addrlen
))
2022 Py_BEGIN_ALLOW_THREADS
2023 res
= internal_connect(s
, SAS2SA(&addrbuf
), addrlen
, &timeout
);
2024 Py_END_ALLOW_THREADS
2026 /* Signals are not errors (though they may raise exceptions). Adapted
2027 from PyErr_SetFromErrnoWithFilenameObject(). */
2029 if (res
== EINTR
&& PyErr_CheckSignals())
2033 return PyInt_FromLong((long) res
);
2036 PyDoc_STRVAR(connect_ex_doc
,
2037 "connect_ex(address) -> errno\n\
2039 This is like connect(address), but returns an error code (the errno value)\n\
2040 instead of raising an exception when an error occurs.");
2043 /* s.fileno() method */
2046 sock_fileno(PySocketSockObject
*s
)
2048 #if SIZEOF_SOCKET_T <= SIZEOF_LONG
2049 return PyInt_FromLong((long) s
->sock_fd
);
2051 return PyLong_FromLongLong((PY_LONG_LONG
)s
->sock_fd
);
2055 PyDoc_STRVAR(fileno_doc
,
2056 "fileno() -> integer\n\
2058 Return the integer file descriptor of the socket.");
2062 /* s.dup() method */
2065 sock_dup(PySocketSockObject
*s
)
2070 newfd
= dup(s
->sock_fd
);
2072 return s
->errorhandler();
2073 sock
= (PyObject
*) new_sockobject(newfd
,
2082 PyDoc_STRVAR(dup_doc
,
2083 "dup() -> socket object\n\
2085 Return a new socket object connected to the same system resource.");
2090 /* s.getsockname() method */
2093 sock_getsockname(PySocketSockObject
*s
)
2095 sock_addr_t addrbuf
;
2099 if (!getsockaddrlen(s
, &addrlen
))
2101 memset(&addrbuf
, 0, addrlen
);
2102 Py_BEGIN_ALLOW_THREADS
2103 res
= getsockname(s
->sock_fd
, SAS2SA(&addrbuf
), &addrlen
);
2104 Py_END_ALLOW_THREADS
2106 return s
->errorhandler();
2107 return makesockaddr(s
->sock_fd
, SAS2SA(&addrbuf
), addrlen
,
2111 PyDoc_STRVAR(getsockname_doc
,
2112 "getsockname() -> address info\n\
2114 Return the address of the local endpoint. For IP sockets, the address\n\
2115 info is a pair (hostaddr, port).");
2118 #ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
2119 /* s.getpeername() method */
2122 sock_getpeername(PySocketSockObject
*s
)
2124 sock_addr_t addrbuf
;
2128 if (!getsockaddrlen(s
, &addrlen
))
2130 memset(&addrbuf
, 0, addrlen
);
2131 Py_BEGIN_ALLOW_THREADS
2132 res
= getpeername(s
->sock_fd
, SAS2SA(&addrbuf
), &addrlen
);
2133 Py_END_ALLOW_THREADS
2135 return s
->errorhandler();
2136 return makesockaddr(s
->sock_fd
, SAS2SA(&addrbuf
), addrlen
,
2140 PyDoc_STRVAR(getpeername_doc
,
2141 "getpeername() -> address info\n\
2143 Return the address of the remote endpoint. For IP sockets, the address\n\
2144 info is a pair (hostaddr, port).");
2146 #endif /* HAVE_GETPEERNAME */
2149 /* s.listen(n) method */
2152 sock_listen(PySocketSockObject
*s
, PyObject
*arg
)
2157 backlog
= PyInt_AsLong(arg
);
2158 if (backlog
== -1 && PyErr_Occurred())
2160 Py_BEGIN_ALLOW_THREADS
2163 res
= listen(s
->sock_fd
, backlog
);
2164 Py_END_ALLOW_THREADS
2166 return s
->errorhandler();
2171 PyDoc_STRVAR(listen_doc
,
2174 Enable a server to accept connections. The backlog argument must be at\n\
2175 least 1; it specifies the number of unaccepted connection that the system\n\
2176 will allow before refusing new connections.");
2180 /* s.makefile(mode) method.
2181 Create a new open file object referring to a dupped version of
2182 the socket's file descriptor. (The dup() call is necessary so
2183 that the open file and socket objects may be closed independent
2185 The mode argument specifies 'r' or 'w' passed to fdopen(). */
2188 sock_makefile(PySocketSockObject
*s
, PyObject
*args
)
2190 extern int fclose(FILE *);
2205 if (!PyArg_ParseTuple(args
, "|si:makefile", &mode
, &bufsize
))
2208 if (strcmp(mode
,"rb") == 0) {
2212 if (strcmp(mode
,"wb") == 0) {
2218 if (((fd
= _open_osfhandle(s
->sock_fd
, _O_BINARY
)) < 0) ||
2219 ((fd
= dup(fd
)) < 0) || ((fp
= fdopen(fd
, mode
)) == NULL
))
2221 if ((fd
= dup(s
->sock_fd
)) < 0 || (fp
= fdopen(fd
, mode
)) == NULL
)
2226 return s
->errorhandler();
2228 f
= PyFile_FromFile(fp
, "<socket>", mode
, fclose
);
2230 PyFile_SetBufSize(f
, bufsize
);
2234 PyDoc_STRVAR(makefile_doc
,
2235 "makefile([mode[, buffersize]]) -> file object\n\
2237 Return a regular file object corresponding to the socket.\n\
2238 The mode and buffersize arguments are as for the built-in open() function.");
2243 * This is the guts of the recv() and recv_into() methods, which reads into a
2244 * char buffer. If you have any inc/dec ref to do to the objects that contain
2245 * the buffer, do it in the caller. This function returns the number of bytes
2246 * succesfully read. If there was an error, it returns -1. Note that it is
2247 * also possible that we return a number of bytes smaller than the request
2251 sock_recv_guts(PySocketSockObject
*s
, char* cbuf
, int len
, int flags
)
2253 ssize_t outlen
= -1;
2260 if (!IS_SELECTABLE(s
)) {
2266 Py_BEGIN_ALLOW_THREADS
2267 timeout
= internal_select(s
, 0);
2269 outlen
= recv(s
->sock_fd
, cbuf
, len
, flags
);
2270 Py_END_ALLOW_THREADS
2273 PyErr_SetString(socket_timeout
, "timed out");
2277 /* Note: the call to errorhandler() ALWAYS indirectly returned
2278 NULL, so ignore its return value */
2285 while (remaining
!= 0) {
2286 unsigned int segment
;
2289 segment
= remaining
/SEGMENT_SIZE
;
2291 segment
= SEGMENT_SIZE
;
2294 segment
= remaining
;
2297 Py_BEGIN_ALLOW_THREADS
2298 timeout
= internal_select(s
, 0);
2300 nread
= recv(s
->sock_fd
, read_buf
, segment
, flags
);
2301 Py_END_ALLOW_THREADS
2304 PyErr_SetString(socket_timeout
, "timed out");
2311 if (nread
!= remaining
) {
2316 remaining
-= segment
;
2317 read_buf
+= segment
;
2319 outlen
= read_buf
- cbuf
;
2326 /* s.recv(nbytes [,flags]) method */
2329 sock_recv(PySocketSockObject
*s
, PyObject
*args
)
2331 int recvlen
, flags
= 0;
2335 if (!PyArg_ParseTuple(args
, "i|i:recv", &recvlen
, &flags
))
2339 PyErr_SetString(PyExc_ValueError
,
2340 "negative buffersize in recv");
2344 /* Allocate a new string. */
2345 buf
= PyString_FromStringAndSize((char *) 0, recvlen
);
2350 outlen
= sock_recv_guts(s
, PyString_AS_STRING(buf
), recvlen
, flags
);
2352 /* An error occurred, release the string and return an
2357 if (outlen
!= recvlen
) {
2358 /* We did not read as many bytes as we anticipated, resize the
2359 string if possible and be succesful. */
2360 if (_PyString_Resize(&buf
, outlen
) < 0)
2361 /* Oopsy, not so succesful after all. */
2368 PyDoc_STRVAR(recv_doc
,
2369 "recv(buffersize[, flags]) -> data\n\
2371 Receive up to buffersize bytes from the socket. For the optional flags\n\
2372 argument, see the Unix manual. When no data is available, block until\n\
2373 at least one byte is available or until the remote end is closed. When\n\
2374 the remote end is closed and all data is read, return the empty string.");
2377 /* s.recv_into(buffer, [nbytes [,flags]]) method */
2380 sock_recv_into(PySocketSockObject
*s
, PyObject
*args
, PyObject
*kwds
)
2382 static char *kwlist
[] = {"buffer", "nbytes", "flags", 0};
2384 int recvlen
= 0, flags
= 0;
2389 /* Get the buffer's memory */
2390 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "w#|ii:recv_into", kwlist
,
2391 &buf
, &buflen
, &recvlen
, &flags
))
2393 assert(buf
!= 0 && buflen
> 0);
2396 PyErr_SetString(PyExc_ValueError
,
2397 "negative buffersize in recv_into");
2401 /* If nbytes was not specified, use the buffer's length */
2405 /* Check if the buffer is large enough */
2406 if (buflen
< recvlen
) {
2407 PyErr_SetString(PyExc_ValueError
,
2408 "buffer too small for requested bytes");
2413 readlen
= sock_recv_guts(s
, buf
, recvlen
, flags
);
2415 /* Return an error. */
2419 /* Return the number of bytes read. Note that we do not do anything
2420 special here in the case that readlen < recvlen. */
2421 return PyInt_FromSsize_t(readlen
);
2424 PyDoc_STRVAR(recv_into_doc
,
2425 "recv_into(buffer, [nbytes[, flags]]) -> nbytes_read\n\
2427 A version of recv() that stores its data into a buffer rather than creating \n\
2428 a new string. Receive up to buffersize bytes from the socket. If buffersize \n\
2429 is not specified (or 0), receive up to the size available in the given buffer.\n\
2431 See recv() for documentation about the flags.");
2435 * This is the guts of the recv() and recv_into() methods, which reads into a
2436 * char buffer. If you have any inc/def ref to do to the objects that contain
2437 * the buffer, do it in the caller. This function returns the number of bytes
2438 * succesfully read. If there was an error, it returns -1. Note that it is
2439 * also possible that we return a number of bytes smaller than the request
2442 * 'addr' is a return value for the address object. Note that you must decref
2446 sock_recvfrom_guts(PySocketSockObject
*s
, char* cbuf
, int len
, int flags
,
2449 sock_addr_t addrbuf
;
2456 if (!getsockaddrlen(s
, &addrlen
))
2459 if (!IS_SELECTABLE(s
)) {
2464 Py_BEGIN_ALLOW_THREADS
2465 memset(&addrbuf
, 0, addrlen
);
2466 timeout
= internal_select(s
, 0);
2469 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
2470 n
= recvfrom(s
->sock_fd
, cbuf
, len
, flags
,
2471 SAS2SA(&addrbuf
), &addrlen
);
2473 n
= recvfrom(s
->sock_fd
, cbuf
, len
, flags
,
2474 (void *) &addrbuf
, &addrlen
);
2477 n
= recvfrom(s
->sock_fd
, cbuf
, len
, flags
,
2478 SAS2SA(&addrbuf
), &addrlen
);
2481 Py_END_ALLOW_THREADS
2484 PyErr_SetString(socket_timeout
, "timed out");
2492 if (!(*addr
= makesockaddr(s
->sock_fd
, SAS2SA(&addrbuf
),
2493 addrlen
, s
->sock_proto
)))
2499 /* s.recvfrom(nbytes [,flags]) method */
2502 sock_recvfrom(PySocketSockObject
*s
, PyObject
*args
)
2504 PyObject
*buf
= NULL
;
2505 PyObject
*addr
= NULL
;
2506 PyObject
*ret
= NULL
;
2507 int recvlen
, flags
= 0;
2510 if (!PyArg_ParseTuple(args
, "i|i:recvfrom", &recvlen
, &flags
))
2514 PyErr_SetString(PyExc_ValueError
,
2515 "negative buffersize in recvfrom");
2519 buf
= PyString_FromStringAndSize((char *) 0, recvlen
);
2523 outlen
= sock_recvfrom_guts(s
, PyString_AS_STRING(buf
),
2524 recvlen
, flags
, &addr
);
2529 if (outlen
!= recvlen
) {
2530 /* We did not read as many bytes as we anticipated, resize the
2531 string if possible and be succesful. */
2532 if (_PyString_Resize(&buf
, outlen
) < 0)
2533 /* Oopsy, not so succesful after all. */
2537 ret
= PyTuple_Pack(2, buf
, addr
);
2545 PyDoc_STRVAR(recvfrom_doc
,
2546 "recvfrom(buffersize[, flags]) -> (data, address info)\n\
2548 Like recv(buffersize, flags) but also return the sender's address info.");
2551 /* s.recvfrom_into(buffer[, nbytes [,flags]]) method */
2554 sock_recvfrom_into(PySocketSockObject
*s
, PyObject
*args
, PyObject
* kwds
)
2556 static char *kwlist
[] = {"buffer", "nbytes", "flags", 0};
2558 int recvlen
= 0, flags
= 0;
2563 PyObject
*addr
= NULL
;
2565 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "w#|ii:recvfrom_into",
2566 kwlist
, &buf
, &buflen
,
2569 assert(buf
!= 0 && buflen
> 0);
2572 PyErr_SetString(PyExc_ValueError
,
2573 "negative buffersize in recvfrom_into");
2577 /* If nbytes was not specified, use the buffer's length */
2581 readlen
= sock_recvfrom_guts(s
, buf
, recvlen
, flags
, &addr
);
2583 /* Return an error */
2588 /* Return the number of bytes read and the address. Note that we do
2589 not do anything special here in the case that readlen < recvlen. */
2590 return Py_BuildValue("lN", readlen
, addr
);
2593 PyDoc_STRVAR(recvfrom_into_doc
,
2594 "recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)\n\
2596 Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.");
2599 /* s.send(data [,flags]) method */
2602 sock_send(PySocketSockObject
*s
, PyObject
*args
)
2605 int len
, n
= -1, flags
= 0, timeout
;
2607 if (!PyArg_ParseTuple(args
, "s#|i:send", &buf
, &len
, &flags
))
2610 if (!IS_SELECTABLE(s
))
2611 return select_error();
2613 Py_BEGIN_ALLOW_THREADS
2614 timeout
= internal_select(s
, 1);
2617 n
= sendsegmented(s
->sock_fd
, buf
, len
, flags
);
2619 n
= send(s
->sock_fd
, buf
, len
, flags
);
2621 Py_END_ALLOW_THREADS
2624 PyErr_SetString(socket_timeout
, "timed out");
2628 return s
->errorhandler();
2629 return PyInt_FromLong((long)n
);
2632 PyDoc_STRVAR(send_doc
,
2633 "send(data[, flags]) -> count\n\
2635 Send a data string to the socket. For the optional flags\n\
2636 argument, see the Unix manual. Return the number of bytes\n\
2637 sent; this may be less than len(data) if the network is busy.");
2640 /* s.sendall(data [,flags]) method */
2643 sock_sendall(PySocketSockObject
*s
, PyObject
*args
)
2646 int len
, n
= -1, flags
= 0, timeout
;
2648 if (!PyArg_ParseTuple(args
, "s#|i:sendall", &buf
, &len
, &flags
))
2651 if (!IS_SELECTABLE(s
))
2652 return select_error();
2654 Py_BEGIN_ALLOW_THREADS
2656 timeout
= internal_select(s
, 1);
2661 n
= sendsegmented(s
->sock_fd
, buf
, len
, flags
);
2663 n
= send(s
->sock_fd
, buf
, len
, flags
);
2670 Py_END_ALLOW_THREADS
2673 PyErr_SetString(socket_timeout
, "timed out");
2677 return s
->errorhandler();
2683 PyDoc_STRVAR(sendall_doc
,
2684 "sendall(data[, flags])\n\
2686 Send a data string to the socket. For the optional flags\n\
2687 argument, see the Unix manual. This calls send() repeatedly\n\
2688 until all data is sent. If an error occurs, it's impossible\n\
2689 to tell how much data has been sent.");
2692 /* s.sendto(data, [flags,] sockaddr) method */
2695 sock_sendto(PySocketSockObject
*s
, PyObject
*args
)
2699 sock_addr_t addrbuf
;
2700 int addrlen
, len
, n
= -1, flags
, timeout
;
2703 if (!PyArg_ParseTuple(args
, "s#O:sendto", &buf
, &len
, &addro
)) {
2705 if (!PyArg_ParseTuple(args
, "s#iO:sendto",
2706 &buf
, &len
, &flags
, &addro
))
2710 if (!IS_SELECTABLE(s
))
2711 return select_error();
2713 if (!getsockaddrarg(s
, addro
, SAS2SA(&addrbuf
), &addrlen
))
2716 Py_BEGIN_ALLOW_THREADS
2717 timeout
= internal_select(s
, 1);
2719 n
= sendto(s
->sock_fd
, buf
, len
, flags
, SAS2SA(&addrbuf
), addrlen
);
2720 Py_END_ALLOW_THREADS
2723 PyErr_SetString(socket_timeout
, "timed out");
2727 return s
->errorhandler();
2728 return PyInt_FromLong((long)n
);
2731 PyDoc_STRVAR(sendto_doc
,
2732 "sendto(data[, flags], address) -> count\n\
2734 Like send(data, flags) but allows specifying the destination address.\n\
2735 For IP sockets, the address is a pair (hostaddr, port).");
2738 /* s.shutdown(how) method */
2741 sock_shutdown(PySocketSockObject
*s
, PyObject
*arg
)
2746 how
= PyInt_AsLong(arg
);
2747 if (how
== -1 && PyErr_Occurred())
2749 Py_BEGIN_ALLOW_THREADS
2750 res
= shutdown(s
->sock_fd
, how
);
2751 Py_END_ALLOW_THREADS
2753 return s
->errorhandler();
2758 PyDoc_STRVAR(shutdown_doc
,
2761 Shut down the reading side of the socket (flag == SHUT_RD), the writing side\n\
2762 of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).");
2765 /* List of methods for socket objects */
2767 static PyMethodDef sock_methods
[] = {
2768 {"accept", (PyCFunction
)sock_accept
, METH_NOARGS
,
2770 {"bind", (PyCFunction
)sock_bind
, METH_O
,
2772 {"close", (PyCFunction
)sock_close
, METH_NOARGS
,
2774 {"connect", (PyCFunction
)sock_connect
, METH_O
,
2776 {"connect_ex", (PyCFunction
)sock_connect_ex
, METH_O
,
2779 {"dup", (PyCFunction
)sock_dup
, METH_NOARGS
,
2782 {"fileno", (PyCFunction
)sock_fileno
, METH_NOARGS
,
2784 #ifdef HAVE_GETPEERNAME
2785 {"getpeername", (PyCFunction
)sock_getpeername
,
2786 METH_NOARGS
, getpeername_doc
},
2788 {"getsockname", (PyCFunction
)sock_getsockname
,
2789 METH_NOARGS
, getsockname_doc
},
2790 {"getsockopt", (PyCFunction
)sock_getsockopt
, METH_VARARGS
,
2792 {"listen", (PyCFunction
)sock_listen
, METH_O
,
2795 {"makefile", (PyCFunction
)sock_makefile
, METH_VARARGS
,
2798 {"recv", (PyCFunction
)sock_recv
, METH_VARARGS
,
2800 {"recv_into", (PyCFunction
)sock_recv_into
, METH_VARARGS
| METH_KEYWORDS
,
2802 {"recvfrom", (PyCFunction
)sock_recvfrom
, METH_VARARGS
,
2804 {"recvfrom_into", (PyCFunction
)sock_recvfrom_into
, METH_VARARGS
| METH_KEYWORDS
,
2806 {"send", (PyCFunction
)sock_send
, METH_VARARGS
,
2808 {"sendall", (PyCFunction
)sock_sendall
, METH_VARARGS
,
2810 {"sendto", (PyCFunction
)sock_sendto
, METH_VARARGS
,
2812 {"setblocking", (PyCFunction
)sock_setblocking
, METH_O
,
2814 {"settimeout", (PyCFunction
)sock_settimeout
, METH_O
,
2816 {"gettimeout", (PyCFunction
)sock_gettimeout
, METH_NOARGS
,
2818 {"setsockopt", (PyCFunction
)sock_setsockopt
, METH_VARARGS
,
2820 {"shutdown", (PyCFunction
)sock_shutdown
, METH_O
,
2823 {"sleeptaskw", (PyCFunction
)sock_sleeptaskw
, METH_O
,
2826 {NULL
, NULL
} /* sentinel */
2829 /* SockObject members */
2830 static PyMemberDef sock_memberlist
[] = {
2831 {"family", T_INT
, offsetof(PySocketSockObject
, sock_family
), READONLY
, "the socket family"},
2832 {"type", T_INT
, offsetof(PySocketSockObject
, sock_type
), READONLY
, "the socket type"},
2833 {"proto", T_INT
, offsetof(PySocketSockObject
, sock_proto
), READONLY
, "the socket protocol"},
2834 {"timeout", T_DOUBLE
, offsetof(PySocketSockObject
, sock_timeout
), READONLY
, "the socket timeout"},
2838 /* Deallocate a socket object in response to the last Py_DECREF().
2839 First close the file description. */
2842 sock_dealloc(PySocketSockObject
*s
)
2844 if (s
->sock_fd
!= -1)
2845 (void) SOCKETCLOSE(s
->sock_fd
);
2846 Py_Type(s
)->tp_free((PyObject
*)s
);
2851 sock_repr(PySocketSockObject
*s
)
2854 #if SIZEOF_SOCKET_T > SIZEOF_LONG
2855 if (s
->sock_fd
> LONG_MAX
) {
2856 /* this can occur on Win64, and actually there is a special
2857 ugly printf formatter for decimal pointer length integer
2858 printing, only bother if necessary*/
2859 PyErr_SetString(PyExc_OverflowError
,
2860 "no printf formatter to display "
2861 "the socket descriptor in decimal");
2867 "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
2868 (long)s
->sock_fd
, s
->sock_family
,
2871 return PyString_FromString(buf
);
2875 /* Create a new, uninitialized socket object. */
2878 sock_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
2882 new = type
->tp_alloc(type
, 0);
2884 ((PySocketSockObject
*)new)->sock_fd
= -1;
2885 ((PySocketSockObject
*)new)->sock_timeout
= -1.0;
2886 ((PySocketSockObject
*)new)->errorhandler
= &set_error
;
2892 /* Initialize a new socket object. */
2896 sock_initobj(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
2898 PySocketSockObject
*s
= (PySocketSockObject
*)self
;
2900 int family
= AF_INET
, type
= SOCK_STREAM
, proto
= 0;
2901 static char *keywords
[] = {"family", "type", "proto", 0};
2903 if (!PyArg_ParseTupleAndKeywords(args
, kwds
,
2904 "|iii:socket", keywords
,
2905 &family
, &type
, &proto
))
2908 Py_BEGIN_ALLOW_THREADS
2909 fd
= socket(family
, type
, proto
);
2910 Py_END_ALLOW_THREADS
2913 if (fd
== INVALID_SOCKET
)
2921 init_sockobject(s
, fd
, family
, type
, proto
);
2928 /* Type object for socket objects. */
2930 static PyTypeObject sock_type
= {
2931 PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */
2932 "_socket.socket", /* tp_name */
2933 sizeof(PySocketSockObject
), /* tp_basicsize */
2934 0, /* tp_itemsize */
2935 (destructor
)sock_dealloc
, /* tp_dealloc */
2940 (reprfunc
)sock_repr
, /* tp_repr */
2941 0, /* tp_as_number */
2942 0, /* tp_as_sequence */
2943 0, /* tp_as_mapping */
2947 PyObject_GenericGetAttr
, /* tp_getattro */
2948 0, /* tp_setattro */
2949 0, /* tp_as_buffer */
2950 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
2951 sock_doc
, /* tp_doc */
2952 0, /* tp_traverse */
2954 0, /* tp_richcompare */
2955 0, /* tp_weaklistoffset */
2957 0, /* tp_iternext */
2958 sock_methods
, /* tp_methods */
2959 sock_memberlist
, /* tp_members */
2963 0, /* tp_descr_get */
2964 0, /* tp_descr_set */
2965 0, /* tp_dictoffset */
2966 sock_initobj
, /* tp_init */
2967 PyType_GenericAlloc
, /* tp_alloc */
2968 sock_new
, /* tp_new */
2969 PyObject_Del
, /* tp_free */
2973 /* Python interface to gethostname(). */
2977 socket_gethostname(PyObject
*self
, PyObject
*unused
)
2981 Py_BEGIN_ALLOW_THREADS
2982 res
= gethostname(buf
, (int) sizeof buf
- 1);
2983 Py_END_ALLOW_THREADS
2986 buf
[sizeof buf
- 1] = '\0';
2987 return PyString_FromString(buf
);
2990 PyDoc_STRVAR(gethostname_doc
,
2991 "gethostname() -> string\n\
2993 Return the current host name.");
2996 /* Python interface to gethostbyname(name). */
3000 socket_gethostbyname(PyObject
*self
, PyObject
*args
)
3003 sock_addr_t addrbuf
;
3005 if (!PyArg_ParseTuple(args
, "s:gethostbyname", &name
))
3007 if (setipaddr(name
, SAS2SA(&addrbuf
), sizeof(addrbuf
), AF_INET
) < 0)
3009 return makeipaddr(SAS2SA(&addrbuf
), sizeof(struct sockaddr_in
));
3012 PyDoc_STRVAR(gethostbyname_doc
,
3013 "gethostbyname(host) -> address\n\
3015 Return the IP address (a string of the form '255.255.255.255') for a host.");
3018 /* Convenience function common to gethostbyname_ex and gethostbyaddr */
3021 gethost_common(struct hostent
*h
, struct sockaddr
*addr
, int alen
, int af
)
3024 PyObject
*rtn_tuple
= (PyObject
*)NULL
;
3025 PyObject
*name_list
= (PyObject
*)NULL
;
3026 PyObject
*addr_list
= (PyObject
*)NULL
;
3030 /* Let's get real error message to return */
3032 set_herror(h_errno
);
3034 PyErr_SetString(socket_error
, "host not found");
3039 if (h
->h_addrtype
!= af
) {
3040 #ifdef HAVE_STRERROR
3041 /* Let's get real error message to return */
3042 PyErr_SetString(socket_error
,
3043 (char *)strerror(EAFNOSUPPORT
));
3047 "Address family not supported by protocol family");
3055 if (alen
< sizeof(struct sockaddr_in
))
3061 if (alen
< sizeof(struct sockaddr_in6
))
3068 if ((name_list
= PyList_New(0)) == NULL
)
3071 if ((addr_list
= PyList_New(0)) == NULL
)
3074 /* SF #1511317: h_aliases can be NULL */
3076 for (pch
= h
->h_aliases
; *pch
!= NULL
; pch
++) {
3078 tmp
= PyString_FromString(*pch
);
3082 status
= PyList_Append(name_list
, tmp
);
3090 for (pch
= h
->h_addr_list
; *pch
!= NULL
; pch
++) {
3097 struct sockaddr_in sin
;
3098 memset(&sin
, 0, sizeof(sin
));
3099 sin
.sin_family
= af
;
3100 #ifdef HAVE_SOCKADDR_SA_LEN
3101 sin
.sin_len
= sizeof(sin
);
3103 memcpy(&sin
.sin_addr
, *pch
, sizeof(sin
.sin_addr
));
3104 tmp
= makeipaddr((struct sockaddr
*)&sin
, sizeof(sin
));
3106 if (pch
== h
->h_addr_list
&& alen
>= sizeof(sin
))
3107 memcpy((char *) addr
, &sin
, sizeof(sin
));
3114 struct sockaddr_in6 sin6
;
3115 memset(&sin6
, 0, sizeof(sin6
));
3116 sin6
.sin6_family
= af
;
3117 #ifdef HAVE_SOCKADDR_SA_LEN
3118 sin6
.sin6_len
= sizeof(sin6
);
3120 memcpy(&sin6
.sin6_addr
, *pch
, sizeof(sin6
.sin6_addr
));
3121 tmp
= makeipaddr((struct sockaddr
*)&sin6
,
3124 if (pch
== h
->h_addr_list
&& alen
>= sizeof(sin6
))
3125 memcpy((char *) addr
, &sin6
, sizeof(sin6
));
3130 default: /* can't happen */
3131 PyErr_SetString(socket_error
,
3132 "unsupported address family");
3139 status
= PyList_Append(addr_list
, tmp
);
3146 rtn_tuple
= Py_BuildValue("sOO", h
->h_name
, name_list
, addr_list
);
3149 Py_XDECREF(name_list
);
3150 Py_XDECREF(addr_list
);
3155 /* Python interface to gethostbyname_ex(name). */
3159 socket_gethostbyname_ex(PyObject
*self
, PyObject
*args
)
3164 struct sockaddr_storage addr
;
3166 struct sockaddr_in addr
;
3168 struct sockaddr
*sa
;
3170 #ifdef HAVE_GETHOSTBYNAME_R
3171 struct hostent hp_allocated
;
3172 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
3173 struct hostent_data data
;
3176 int buf_len
= (sizeof buf
) - 1;
3179 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3182 #endif /* HAVE_GETHOSTBYNAME_R */
3184 if (!PyArg_ParseTuple(args
, "s:gethostbyname_ex", &name
))
3186 if (setipaddr(name
, (struct sockaddr
*)&addr
, sizeof(addr
), AF_INET
) < 0)
3188 Py_BEGIN_ALLOW_THREADS
3189 #ifdef HAVE_GETHOSTBYNAME_R
3190 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3191 result
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
,
3193 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
3194 h
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
, &errnop
);
3195 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
3196 memset((void *) &data
, '\0', sizeof(data
));
3197 result
= gethostbyname_r(name
, &hp_allocated
, &data
);
3198 h
= (result
!= 0) ? NULL
: &hp_allocated
;
3200 #else /* not HAVE_GETHOSTBYNAME_R */
3201 #ifdef USE_GETHOSTBYNAME_LOCK
3202 PyThread_acquire_lock(netdb_lock
, 1);
3204 h
= gethostbyname(name
);
3205 #endif /* HAVE_GETHOSTBYNAME_R */
3206 Py_END_ALLOW_THREADS
3207 /* Some C libraries would require addr.__ss_family instead of
3209 Therefore, we cast the sockaddr_storage into sockaddr to
3210 access sa_family. */
3211 sa
= (struct sockaddr
*)&addr
;
3212 ret
= gethost_common(h
, (struct sockaddr
*)&addr
, sizeof(addr
),
3214 #ifdef USE_GETHOSTBYNAME_LOCK
3215 PyThread_release_lock(netdb_lock
);
3220 PyDoc_STRVAR(ghbn_ex_doc
,
3221 "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
3223 Return the true host name, a list of aliases, and a list of IP addresses,\n\
3224 for a host. The host argument is a string giving a host name or IP number.");
3227 /* Python interface to gethostbyaddr(IP). */
3231 socket_gethostbyaddr(PyObject
*self
, PyObject
*args
)
3234 struct sockaddr_storage addr
;
3236 struct sockaddr_in addr
;
3238 struct sockaddr
*sa
= (struct sockaddr
*)&addr
;
3242 #ifdef HAVE_GETHOSTBYNAME_R
3243 struct hostent hp_allocated
;
3244 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
3245 struct hostent_data data
;
3248 int buf_len
= (sizeof buf
) - 1;
3251 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3254 #endif /* HAVE_GETHOSTBYNAME_R */
3259 if (!PyArg_ParseTuple(args
, "s:gethostbyaddr", &ip_num
))
3262 if (setipaddr(ip_num
, sa
, sizeof(addr
), af
) < 0)
3269 ap
= (char *)&((struct sockaddr_in
*)sa
)->sin_addr
;
3270 al
= sizeof(((struct sockaddr_in
*)sa
)->sin_addr
);
3274 ap
= (char *)&((struct sockaddr_in6
*)sa
)->sin6_addr
;
3275 al
= sizeof(((struct sockaddr_in6
*)sa
)->sin6_addr
);
3279 PyErr_SetString(socket_error
, "unsupported address family");
3282 Py_BEGIN_ALLOW_THREADS
3283 #ifdef HAVE_GETHOSTBYNAME_R
3284 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
3285 result
= gethostbyaddr_r(ap
, al
, af
,
3286 &hp_allocated
, buf
, buf_len
,
3288 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
3289 h
= gethostbyaddr_r(ap
, al
, af
,
3290 &hp_allocated
, buf
, buf_len
, &errnop
);
3291 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
3292 memset((void *) &data
, '\0', sizeof(data
));
3293 result
= gethostbyaddr_r(ap
, al
, af
, &hp_allocated
, &data
);
3294 h
= (result
!= 0) ? NULL
: &hp_allocated
;
3296 #else /* not HAVE_GETHOSTBYNAME_R */
3297 #ifdef USE_GETHOSTBYNAME_LOCK
3298 PyThread_acquire_lock(netdb_lock
, 1);
3300 h
= gethostbyaddr(ap
, al
, af
);
3301 #endif /* HAVE_GETHOSTBYNAME_R */
3302 Py_END_ALLOW_THREADS
3303 ret
= gethost_common(h
, (struct sockaddr
*)&addr
, sizeof(addr
), af
);
3304 #ifdef USE_GETHOSTBYNAME_LOCK
3305 PyThread_release_lock(netdb_lock
);
3310 PyDoc_STRVAR(gethostbyaddr_doc
,
3311 "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
3313 Return the true host name, a list of aliases, and a list of IP addresses,\n\
3314 for a host. The host argument is a string giving a host name or IP number.");
3317 /* Python interface to getservbyname(name).
3318 This only returns the port number, since the other info is already
3319 known or not useful (like the list of aliases). */
3323 socket_getservbyname(PyObject
*self
, PyObject
*args
)
3325 char *name
, *proto
=NULL
;
3327 if (!PyArg_ParseTuple(args
, "s|s:getservbyname", &name
, &proto
))
3329 Py_BEGIN_ALLOW_THREADS
3330 sp
= getservbyname(name
, proto
);
3331 Py_END_ALLOW_THREADS
3333 PyErr_SetString(socket_error
, "service/proto not found");
3336 return PyInt_FromLong((long) ntohs(sp
->s_port
));
3339 PyDoc_STRVAR(getservbyname_doc
,
3340 "getservbyname(servicename[, protocolname]) -> integer\n\
3342 Return a port number from a service name and protocol name.\n\
3343 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3344 otherwise any protocol will match.");
3347 /* Python interface to getservbyport(port).
3348 This only returns the service name, since the other info is already
3349 known or not useful (like the list of aliases). */
3353 socket_getservbyport(PyObject
*self
, PyObject
*args
)
3355 unsigned short port
;
3358 if (!PyArg_ParseTuple(args
, "H|s:getservbyport", &port
, &proto
))
3360 Py_BEGIN_ALLOW_THREADS
3361 sp
= getservbyport(htons(port
), proto
);
3362 Py_END_ALLOW_THREADS
3364 PyErr_SetString(socket_error
, "port/proto not found");
3367 return PyString_FromString(sp
->s_name
);
3370 PyDoc_STRVAR(getservbyport_doc
,
3371 "getservbyport(port[, protocolname]) -> string\n\
3373 Return the service name from a port number and protocol name.\n\
3374 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3375 otherwise any protocol will match.");
3377 /* Python interface to getprotobyname(name).
3378 This only returns the protocol number, since the other info is
3379 already known or not useful (like the list of aliases). */
3383 socket_getprotobyname(PyObject
*self
, PyObject
*args
)
3386 struct protoent
*sp
;
3388 /* Not available in BeOS yet. - [cjh] */
3389 PyErr_SetString(socket_error
, "getprotobyname not supported");
3392 if (!PyArg_ParseTuple(args
, "s:getprotobyname", &name
))
3394 Py_BEGIN_ALLOW_THREADS
3395 sp
= getprotobyname(name
);
3396 Py_END_ALLOW_THREADS
3398 PyErr_SetString(socket_error
, "protocol not found");
3401 return PyInt_FromLong((long) sp
->p_proto
);
3405 PyDoc_STRVAR(getprotobyname_doc
,
3406 "getprotobyname(name) -> integer\n\
3408 Return the protocol number for the named protocol. (Rarely used.)");
3411 #ifdef HAVE_SOCKETPAIR
3412 /* Create a pair of sockets using the socketpair() function.
3413 Arguments as for socket() except the default family is AF_UNIX if
3414 defined on the platform; otherwise, the default is AF_INET. */
3418 socket_socketpair(PyObject
*self
, PyObject
*args
)
3420 PySocketSockObject
*s0
= NULL
, *s1
= NULL
;
3422 int family
, type
= SOCK_STREAM
, proto
= 0;
3423 PyObject
*res
= NULL
;
3425 #if defined(AF_UNIX)
3430 if (!PyArg_ParseTuple(args
, "|iii:socketpair",
3431 &family
, &type
, &proto
))
3433 /* Create a pair of socket fds */
3434 if (socketpair(family
, type
, proto
, sv
) < 0)
3436 s0
= new_sockobject(sv
[0], family
, type
, proto
);
3439 s1
= new_sockobject(sv
[1], family
, type
, proto
);
3442 res
= PyTuple_Pack(2, s0
, s1
);
3456 PyDoc_STRVAR(socketpair_doc
,
3457 "socketpair([family[, type[, proto]]]) -> (socket object, socket object)\n\
3459 Create a pair of socket objects from the sockets returned by the platform\n\
3460 socketpair() function.\n\
3461 The arguments are the same as for socket() except the default family is\n\
3462 AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");
3464 #endif /* HAVE_SOCKETPAIR */
3468 /* Create a socket object from a numeric file description.
3469 Useful e.g. if stdin is a socket.
3470 Additional arguments as for socket(). */
3474 socket_fromfd(PyObject
*self
, PyObject
*args
)
3476 PySocketSockObject
*s
;
3478 int family
, type
, proto
= 0;
3479 if (!PyArg_ParseTuple(args
, "iii|i:fromfd",
3480 &fd
, &family
, &type
, &proto
))
3482 /* Dup the fd so it and the socket can be closed independently */
3486 s
= new_sockobject(fd
, family
, type
, proto
);
3487 return (PyObject
*) s
;
3490 PyDoc_STRVAR(fromfd_doc
,
3491 "fromfd(fd, family, type[, proto]) -> socket object\n\
3493 Create a socket object from a duplicate of the given\n\
3495 The remaining arguments are the same as for socket().");
3501 socket_ntohs(PyObject
*self
, PyObject
*args
)
3505 if (!PyArg_ParseTuple(args
, "i:ntohs", &x1
)) {
3509 PyErr_SetString(PyExc_OverflowError
,
3510 "can't convert negative number to unsigned long");
3513 x2
= (unsigned int)ntohs((unsigned short)x1
);
3514 return PyInt_FromLong(x2
);
3517 PyDoc_STRVAR(ntohs_doc
,
3518 "ntohs(integer) -> integer\n\
3520 Convert a 16-bit integer from network to host byte order.");
3524 socket_ntohl(PyObject
*self
, PyObject
*arg
)
3528 if (PyInt_Check(arg
)) {
3529 x
= PyInt_AS_LONG(arg
);
3530 if (x
== (unsigned long) -1 && PyErr_Occurred())
3533 PyErr_SetString(PyExc_OverflowError
,
3534 "can't convert negative number to unsigned long");
3538 else if (PyLong_Check(arg
)) {
3539 x
= PyLong_AsUnsignedLong(arg
);
3540 if (x
== (unsigned long) -1 && PyErr_Occurred())
3545 /* only want the trailing 32 bits */
3546 y
= x
& 0xFFFFFFFFUL
;
3548 return PyErr_Format(PyExc_OverflowError
,
3549 "long int larger than 32 bits");
3555 return PyErr_Format(PyExc_TypeError
,
3556 "expected int/long, %s found",
3557 Py_Type(arg
)->tp_name
);
3558 if (x
== (unsigned long) -1 && PyErr_Occurred())
3560 return PyLong_FromUnsignedLong(ntohl(x
));
3563 PyDoc_STRVAR(ntohl_doc
,
3564 "ntohl(integer) -> integer\n\
3566 Convert a 32-bit integer from network to host byte order.");
3570 socket_htons(PyObject
*self
, PyObject
*args
)
3574 if (!PyArg_ParseTuple(args
, "i:htons", &x1
)) {
3578 PyErr_SetString(PyExc_OverflowError
,
3579 "can't convert negative number to unsigned long");
3582 x2
= (unsigned int)htons((unsigned short)x1
);
3583 return PyInt_FromLong(x2
);
3586 PyDoc_STRVAR(htons_doc
,
3587 "htons(integer) -> integer\n\
3589 Convert a 16-bit integer from host to network byte order.");
3593 socket_htonl(PyObject
*self
, PyObject
*arg
)
3597 if (PyInt_Check(arg
)) {
3598 x
= PyInt_AS_LONG(arg
);
3599 if (x
== (unsigned long) -1 && PyErr_Occurred())
3602 PyErr_SetString(PyExc_OverflowError
,
3603 "can't convert negative number to unsigned long");
3607 else if (PyLong_Check(arg
)) {
3608 x
= PyLong_AsUnsignedLong(arg
);
3609 if (x
== (unsigned long) -1 && PyErr_Occurred())
3614 /* only want the trailing 32 bits */
3615 y
= x
& 0xFFFFFFFFUL
;
3617 return PyErr_Format(PyExc_OverflowError
,
3618 "long int larger than 32 bits");
3624 return PyErr_Format(PyExc_TypeError
,
3625 "expected int/long, %s found",
3626 Py_Type(arg
)->tp_name
);
3627 return PyLong_FromUnsignedLong(htonl((unsigned long)x
));
3630 PyDoc_STRVAR(htonl_doc
,
3631 "htonl(integer) -> integer\n\
3633 Convert a 32-bit integer from host to network byte order.");
3635 /* socket.inet_aton() and socket.inet_ntoa() functions. */
3637 PyDoc_STRVAR(inet_aton_doc
,
3638 "inet_aton(string) -> packed 32-bit IP representation\n\
3640 Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
3641 binary format used in low-level network functions.");
3644 socket_inet_aton(PyObject
*self
, PyObject
*args
)
3647 #define INADDR_NONE (-1)
3649 #ifdef HAVE_INET_ATON
3653 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
3654 /* Have to use inet_addr() instead */
3655 unsigned long packed_addr
;
3659 if (!PyArg_ParseTuple(args
, "s:inet_aton", &ip_addr
))
3663 #ifdef HAVE_INET_ATON
3665 #ifdef USE_INET_ATON_WEAKLINK
3666 if (inet_aton
!= NULL
) {
3668 if (inet_aton(ip_addr
, &buf
))
3669 return PyString_FromStringAndSize((char *)(&buf
),
3672 PyErr_SetString(socket_error
,
3673 "illegal IP address string passed to inet_aton");
3676 #ifdef USE_INET_ATON_WEAKLINK
3682 #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
3684 /* special-case this address as inet_addr might return INADDR_NONE
3686 if (strcmp(ip_addr
, "255.255.255.255") == 0) {
3687 packed_addr
= 0xFFFFFFFF;
3690 packed_addr
= inet_addr(ip_addr
);
3692 if (packed_addr
== INADDR_NONE
) { /* invalid address */
3693 PyErr_SetString(socket_error
,
3694 "illegal IP address string passed to inet_aton");
3698 return PyString_FromStringAndSize((char *) &packed_addr
,
3699 sizeof(packed_addr
));
3701 #ifdef USE_INET_ATON_WEAKLINK
3708 PyDoc_STRVAR(inet_ntoa_doc
,
3709 "inet_ntoa(packed_ip) -> ip_address_string\n\
3711 Convert an IP address from 32-bit packed binary format to string format");
3714 socket_inet_ntoa(PyObject
*self
, PyObject
*args
)
3718 struct in_addr packed_addr
;
3720 if (!PyArg_ParseTuple(args
, "s#:inet_ntoa", &packed_str
, &addr_len
)) {
3724 if (addr_len
!= sizeof(packed_addr
)) {
3725 PyErr_SetString(socket_error
,
3726 "packed IP wrong length for inet_ntoa");
3730 memcpy(&packed_addr
, packed_str
, addr_len
);
3732 return PyString_FromString(inet_ntoa(packed_addr
));
3735 #ifdef HAVE_INET_PTON
3737 PyDoc_STRVAR(inet_pton_doc
,
3738 "inet_pton(af, ip) -> packed IP address string\n\
3740 Convert an IP address from string format to a packed string suitable\n\
3741 for use with low-level network functions.");
3744 socket_inet_pton(PyObject
*self
, PyObject
*args
)
3750 char packed
[MAX(sizeof(struct in_addr
), sizeof(struct in6_addr
))];
3752 char packed
[sizeof(struct in_addr
)];
3754 if (!PyArg_ParseTuple(args
, "is:inet_pton", &af
, &ip
)) {
3758 #if !defined(ENABLE_IPV6) && defined(AF_INET6)
3759 if(af
== AF_INET6
) {
3760 PyErr_SetString(socket_error
,
3761 "can't use AF_INET6, IPv6 is disabled");
3766 retval
= inet_pton(af
, ip
, packed
);
3768 PyErr_SetFromErrno(socket_error
);
3770 } else if (retval
== 0) {
3771 PyErr_SetString(socket_error
,
3772 "illegal IP address string passed to inet_pton");
3774 } else if (af
== AF_INET
) {
3775 return PyString_FromStringAndSize(packed
,
3776 sizeof(struct in_addr
));
3778 } else if (af
== AF_INET6
) {
3779 return PyString_FromStringAndSize(packed
,
3780 sizeof(struct in6_addr
));
3783 PyErr_SetString(socket_error
, "unknown address family");
3788 PyDoc_STRVAR(inet_ntop_doc
,
3789 "inet_ntop(af, packed_ip) -> string formatted IP address\n\
3791 Convert a packed IP address of the given family to string format.");
3794 socket_inet_ntop(PyObject
*self
, PyObject
*args
)
3801 char ip
[MAX(INET_ADDRSTRLEN
, INET6_ADDRSTRLEN
) + 1];
3803 char ip
[INET_ADDRSTRLEN
+ 1];
3806 /* Guarantee NUL-termination for PyString_FromString() below */
3807 memset((void *) &ip
[0], '\0', sizeof(ip
));
3809 if (!PyArg_ParseTuple(args
, "is#:inet_ntop", &af
, &packed
, &len
)) {
3813 if (af
== AF_INET
) {
3814 if (len
!= sizeof(struct in_addr
)) {
3815 PyErr_SetString(PyExc_ValueError
,
3816 "invalid length of packed IP address string");
3820 } else if (af
== AF_INET6
) {
3821 if (len
!= sizeof(struct in6_addr
)) {
3822 PyErr_SetString(PyExc_ValueError
,
3823 "invalid length of packed IP address string");
3828 PyErr_Format(PyExc_ValueError
,
3829 "unknown address family %d", af
);
3833 retval
= inet_ntop(af
, packed
, ip
, sizeof(ip
));
3835 PyErr_SetFromErrno(socket_error
);
3838 return PyString_FromString(retval
);
3842 PyErr_SetString(PyExc_RuntimeError
, "invalid handling of inet_ntop");
3846 #endif /* HAVE_INET_PTON */
3848 /* Python interface to getaddrinfo(host, port). */
3852 socket_getaddrinfo(PyObject
*self
, PyObject
*args
)
3854 struct addrinfo hints
, *res
;
3855 struct addrinfo
*res0
= NULL
;
3856 PyObject
*hobj
= NULL
;
3857 PyObject
*pobj
= (PyObject
*)NULL
;
3860 int family
, socktype
, protocol
, flags
;
3862 PyObject
*all
= (PyObject
*)NULL
;
3863 PyObject
*single
= (PyObject
*)NULL
;
3864 PyObject
*idna
= NULL
;
3866 family
= socktype
= protocol
= flags
= 0;
3868 if (!PyArg_ParseTuple(args
, "OO|iiii:getaddrinfo",
3869 &hobj
, &pobj
, &family
, &socktype
,
3870 &protocol
, &flags
)) {
3873 if (hobj
== Py_None
) {
3875 } else if (PyUnicode_Check(hobj
)) {
3876 idna
= PyObject_CallMethod(hobj
, "encode", "s", "idna");
3879 hptr
= PyString_AsString(idna
);
3880 } else if (PyString_Check(hobj
)) {
3881 hptr
= PyString_AsString(hobj
);
3883 PyErr_SetString(PyExc_TypeError
,
3884 "getaddrinfo() argument 1 must be string or None");
3887 if (PyInt_Check(pobj
)) {
3888 PyOS_snprintf(pbuf
, sizeof(pbuf
), "%ld", PyInt_AsLong(pobj
));
3890 } else if (PyString_Check(pobj
)) {
3891 pptr
= PyString_AsString(pobj
);
3892 } else if (pobj
== Py_None
) {
3893 pptr
= (char *)NULL
;
3895 PyErr_SetString(socket_error
, "Int or String expected");
3898 memset(&hints
, 0, sizeof(hints
));
3899 hints
.ai_family
= family
;
3900 hints
.ai_socktype
= socktype
;
3901 hints
.ai_protocol
= protocol
;
3902 hints
.ai_flags
= flags
;
3903 Py_BEGIN_ALLOW_THREADS
3904 ACQUIRE_GETADDRINFO_LOCK
3905 error
= getaddrinfo(hptr
, pptr
, &hints
, &res0
);
3906 Py_END_ALLOW_THREADS
3907 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
3909 set_gaierror(error
);
3913 if ((all
= PyList_New(0)) == NULL
)
3915 for (res
= res0
; res
; res
= res
->ai_next
) {
3917 makesockaddr(-1, res
->ai_addr
, res
->ai_addrlen
, protocol
);
3920 single
= Py_BuildValue("iiisO", res
->ai_family
,
3921 res
->ai_socktype
, res
->ai_protocol
,
3922 res
->ai_canonname
? res
->ai_canonname
: "",
3928 if (PyList_Append(all
, single
))
3942 return (PyObject
*)NULL
;
3945 PyDoc_STRVAR(getaddrinfo_doc
,
3946 "getaddrinfo(host, port [, family, socktype, proto, flags])\n\
3947 -> list of (family, socktype, proto, canonname, sockaddr)\n\
3949 Resolve host and port into addrinfo struct.");
3951 /* Python interface to getnameinfo(sa, flags). */
3955 socket_getnameinfo(PyObject
*self
, PyObject
*args
)
3957 PyObject
*sa
= (PyObject
*)NULL
;
3960 int port
, flowinfo
, scope_id
;
3961 char hbuf
[NI_MAXHOST
], pbuf
[NI_MAXSERV
];
3962 struct addrinfo hints
, *res
= NULL
;
3964 PyObject
*ret
= (PyObject
*)NULL
;
3966 flags
= flowinfo
= scope_id
= 0;
3967 if (!PyArg_ParseTuple(args
, "Oi:getnameinfo", &sa
, &flags
))
3969 if (!PyArg_ParseTuple(sa
, "si|ii",
3970 &hostp
, &port
, &flowinfo
, &scope_id
))
3972 PyOS_snprintf(pbuf
, sizeof(pbuf
), "%d", port
);
3973 memset(&hints
, 0, sizeof(hints
));
3974 hints
.ai_family
= AF_UNSPEC
;
3975 hints
.ai_socktype
= SOCK_DGRAM
; /* make numeric port happy */
3976 Py_BEGIN_ALLOW_THREADS
3977 ACQUIRE_GETADDRINFO_LOCK
3978 error
= getaddrinfo(hostp
, pbuf
, &hints
, &res
);
3979 Py_END_ALLOW_THREADS
3980 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
3982 set_gaierror(error
);
3986 PyErr_SetString(socket_error
,
3987 "sockaddr resolved to multiple addresses");
3990 switch (res
->ai_family
) {
3995 if (PyArg_ParseTuple(sa
, "si", &t1
, &t2
) == 0) {
3996 PyErr_SetString(socket_error
,
3997 "IPv4 sockaddr must be 2 tuple");
4005 struct sockaddr_in6
*sin6
;
4006 sin6
= (struct sockaddr_in6
*)res
->ai_addr
;
4007 sin6
->sin6_flowinfo
= flowinfo
;
4008 sin6
->sin6_scope_id
= scope_id
;
4013 error
= getnameinfo(res
->ai_addr
, res
->ai_addrlen
,
4014 hbuf
, sizeof(hbuf
), pbuf
, sizeof(pbuf
), flags
);
4016 set_gaierror(error
);
4019 ret
= Py_BuildValue("ss", hbuf
, pbuf
);
4027 PyDoc_STRVAR(getnameinfo_doc
,
4028 "getnameinfo(sockaddr, flags) --> (host, port)\n\
4030 Get host and port for a sockaddr.");
4033 /* Python API to getting and setting the default timeout value. */
4036 socket_getdefaulttimeout(PyObject
*self
)
4038 if (defaulttimeout
< 0.0) {
4043 return PyFloat_FromDouble(defaulttimeout
);
4046 PyDoc_STRVAR(getdefaulttimeout_doc
,
4047 "getdefaulttimeout() -> timeout\n\
4049 Returns the default timeout in floating seconds for new socket objects.\n\
4050 A value of None indicates that new socket objects have no timeout.\n\
4051 When the socket module is first imported, the default is None.");
4054 socket_setdefaulttimeout(PyObject
*self
, PyObject
*arg
)
4061 timeout
= PyFloat_AsDouble(arg
);
4062 if (timeout
< 0.0) {
4063 if (!PyErr_Occurred())
4064 PyErr_SetString(PyExc_ValueError
,
4065 "Timeout value out of range");
4070 defaulttimeout
= timeout
;
4076 PyDoc_STRVAR(setdefaulttimeout_doc
,
4077 "setdefaulttimeout(timeout)\n\
4079 Set the default timeout in floating seconds for new socket objects.\n\
4080 A value of None indicates that new socket objects have no timeout.\n\
4081 When the socket module is first imported, the default is None.");
4084 /* List of functions exported by this module. */
4086 static PyMethodDef socket_methods
[] = {
4087 {"gethostbyname", socket_gethostbyname
,
4088 METH_VARARGS
, gethostbyname_doc
},
4089 {"gethostbyname_ex", socket_gethostbyname_ex
,
4090 METH_VARARGS
, ghbn_ex_doc
},
4091 {"gethostbyaddr", socket_gethostbyaddr
,
4092 METH_VARARGS
, gethostbyaddr_doc
},
4093 {"gethostname", socket_gethostname
,
4094 METH_NOARGS
, gethostname_doc
},
4095 {"getservbyname", socket_getservbyname
,
4096 METH_VARARGS
, getservbyname_doc
},
4097 {"getservbyport", socket_getservbyport
,
4098 METH_VARARGS
, getservbyport_doc
},
4099 {"getprotobyname", socket_getprotobyname
,
4100 METH_VARARGS
, getprotobyname_doc
},
4102 {"fromfd", socket_fromfd
,
4103 METH_VARARGS
, fromfd_doc
},
4105 #ifdef HAVE_SOCKETPAIR
4106 {"socketpair", socket_socketpair
,
4107 METH_VARARGS
, socketpair_doc
},
4109 {"ntohs", socket_ntohs
,
4110 METH_VARARGS
, ntohs_doc
},
4111 {"ntohl", socket_ntohl
,
4113 {"htons", socket_htons
,
4114 METH_VARARGS
, htons_doc
},
4115 {"htonl", socket_htonl
,
4117 {"inet_aton", socket_inet_aton
,
4118 METH_VARARGS
, inet_aton_doc
},
4119 {"inet_ntoa", socket_inet_ntoa
,
4120 METH_VARARGS
, inet_ntoa_doc
},
4121 #ifdef HAVE_INET_PTON
4122 {"inet_pton", socket_inet_pton
,
4123 METH_VARARGS
, inet_pton_doc
},
4124 {"inet_ntop", socket_inet_ntop
,
4125 METH_VARARGS
, inet_ntop_doc
},
4127 {"getaddrinfo", socket_getaddrinfo
,
4128 METH_VARARGS
, getaddrinfo_doc
},
4129 {"getnameinfo", socket_getnameinfo
,
4130 METH_VARARGS
, getnameinfo_doc
},
4131 {"getdefaulttimeout", (PyCFunction
)socket_getdefaulttimeout
,
4132 METH_NOARGS
, getdefaulttimeout_doc
},
4133 {"setdefaulttimeout", socket_setdefaulttimeout
,
4134 METH_O
, setdefaulttimeout_doc
},
4135 {NULL
, NULL
} /* Sentinel */
4140 #define OS_INIT_DEFINED
4148 _kernel_swi(0x43380, &r
, &r
);
4149 taskwindow
= r
.r
[0];
4158 #define OS_INIT_DEFINED
4160 /* Additional initialization and cleanup for Windows */
4174 ret
= WSAStartup(0x0101, &WSAData
);
4176 case 0: /* No error */
4177 Py_AtExit(os_cleanup
);
4178 return 1; /* Success */
4179 case WSASYSNOTREADY
:
4180 PyErr_SetString(PyExc_ImportError
,
4181 "WSAStartup failed: network not ready");
4183 case WSAVERNOTSUPPORTED
:
4187 "WSAStartup failed: requested version not supported");
4190 PyOS_snprintf(buf
, sizeof(buf
),
4191 "WSAStartup failed: error code %d", ret
);
4192 PyErr_SetString(PyExc_ImportError
, buf
);
4195 return 0; /* Failure */
4198 #endif /* MS_WINDOWS */
4202 #define OS_INIT_DEFINED
4204 /* Additional initialization for OS/2 */
4211 int rc
= sock_init();
4214 return 1; /* Success */
4217 PyOS_snprintf(reason
, sizeof(reason
),
4218 "OS/2 TCP/IP Error# %d", sock_errno());
4219 PyErr_SetString(PyExc_ImportError
, reason
);
4221 return 0; /* Failure */
4223 /* No need to initialise sockets with GCC/EMX */
4224 return 1; /* Success */
4228 #endif /* PYOS_OS2 */
4231 #ifndef OS_INIT_DEFINED
4235 return 1; /* Success */
4240 /* C API table - always add new things to the end for binary
4243 PySocketModule_APIObject PySocketModuleAPI
=
4250 /* Initialize the _socket module.
4252 This module is actually called "_socket", and there's a wrapper
4253 "socket.py" which implements some additional functionality. On some
4254 platforms (e.g. Windows and OS/2), socket.py also implements a
4255 wrapper for the socket type that provides missing functionality such
4256 as makefile(), dup() and fromfd(). The import of "_socket" may fail
4257 with an ImportError exception if os-specific initialization fails.
4258 On Windows, this does WINSOCK initialization. When WINSOCK is
4259 initialized succesfully, a call to WSACleanup() is scheduled to be
4263 PyDoc_STRVAR(socket_doc
,
4264 "Implementation module for socket operations.\n\
4266 See the socket module for documentation.");
4271 PyObject
*m
, *has_ipv6
;
4276 Py_Type(&sock_type
) = &PyType_Type
;
4277 m
= Py_InitModule3(PySocket_MODULE_NAME
,
4283 socket_error
= PyErr_NewException("socket.error", NULL
, NULL
);
4284 if (socket_error
== NULL
)
4286 PySocketModuleAPI
.error
= socket_error
;
4287 Py_INCREF(socket_error
);
4288 PyModule_AddObject(m
, "error", socket_error
);
4289 socket_herror
= PyErr_NewException("socket.herror",
4290 socket_error
, NULL
);
4291 if (socket_herror
== NULL
)
4293 Py_INCREF(socket_herror
);
4294 PyModule_AddObject(m
, "herror", socket_herror
);
4295 socket_gaierror
= PyErr_NewException("socket.gaierror", socket_error
,
4297 if (socket_gaierror
== NULL
)
4299 Py_INCREF(socket_gaierror
);
4300 PyModule_AddObject(m
, "gaierror", socket_gaierror
);
4301 socket_timeout
= PyErr_NewException("socket.timeout",
4302 socket_error
, NULL
);
4303 if (socket_timeout
== NULL
)
4305 Py_INCREF(socket_timeout
);
4306 PyModule_AddObject(m
, "timeout", socket_timeout
);
4307 Py_INCREF((PyObject
*)&sock_type
);
4308 if (PyModule_AddObject(m
, "SocketType",
4309 (PyObject
*)&sock_type
) != 0)
4311 Py_INCREF((PyObject
*)&sock_type
);
4312 if (PyModule_AddObject(m
, "socket",
4313 (PyObject
*)&sock_type
) != 0)
4319 has_ipv6
= Py_False
;
4321 Py_INCREF(has_ipv6
);
4322 PyModule_AddObject(m
, "has_ipv6", has_ipv6
);
4325 if (PyModule_AddObject(m
, PySocket_CAPI_NAME
,
4326 PyCObject_FromVoidPtr((void *)&PySocketModuleAPI
, NULL
)
4330 /* Address families (we only support AF_INET and AF_UNIX) */
4332 PyModule_AddIntConstant(m
, "AF_UNSPEC", AF_UNSPEC
);
4334 PyModule_AddIntConstant(m
, "AF_INET", AF_INET
);
4336 PyModule_AddIntConstant(m
, "AF_INET6", AF_INET6
);
4337 #endif /* AF_INET6 */
4338 #if defined(AF_UNIX)
4339 PyModule_AddIntConstant(m
, "AF_UNIX", AF_UNIX
);
4340 #endif /* AF_UNIX */
4342 /* Amateur Radio AX.25 */
4343 PyModule_AddIntConstant(m
, "AF_AX25", AF_AX25
);
4346 PyModule_AddIntConstant(m
, "AF_IPX", AF_IPX
); /* Novell IPX */
4350 PyModule_AddIntConstant(m
, "AF_APPLETALK", AF_APPLETALK
);
4353 /* Amateur radio NetROM */
4354 PyModule_AddIntConstant(m
, "AF_NETROM", AF_NETROM
);
4357 /* Multiprotocol bridge */
4358 PyModule_AddIntConstant(m
, "AF_BRIDGE", AF_BRIDGE
);
4362 PyModule_AddIntConstant(m
, "AF_ATMPVC", AF_ATMPVC
);
4365 /* Reserved for Werner's ATM */
4366 PyModule_AddIntConstant(m
, "AF_AAL5", AF_AAL5
);
4369 /* Reserved for X.25 project */
4370 PyModule_AddIntConstant(m
, "AF_X25", AF_X25
);
4373 PyModule_AddIntConstant(m
, "AF_INET6", AF_INET6
); /* IP version 6 */
4376 /* Amateur Radio X.25 PLP */
4377 PyModule_AddIntConstant(m
, "AF_ROSE", AF_ROSE
);
4380 /* Reserved for DECnet project */
4381 PyModule_AddIntConstant(m
, "AF_DECnet", AF_DECnet
);
4384 /* Reserved for 802.2LLC project */
4385 PyModule_AddIntConstant(m
, "AF_NETBEUI", AF_NETBEUI
);
4388 /* Security callback pseudo AF */
4389 PyModule_AddIntConstant(m
, "AF_SECURITY", AF_SECURITY
);
4392 /* PF_KEY key management API */
4393 PyModule_AddIntConstant(m
, "AF_KEY", AF_KEY
);
4397 PyModule_AddIntConstant(m
, "AF_NETLINK", AF_NETLINK
);
4398 PyModule_AddIntConstant(m
, "NETLINK_ROUTE", NETLINK_ROUTE
);
4400 PyModule_AddIntConstant(m
, "NETLINK_SKIP", NETLINK_SKIP
);
4403 PyModule_AddIntConstant(m
, "NETLINK_W1", NETLINK_W1
);
4405 PyModule_AddIntConstant(m
, "NETLINK_USERSOCK", NETLINK_USERSOCK
);
4406 PyModule_AddIntConstant(m
, "NETLINK_FIREWALL", NETLINK_FIREWALL
);
4407 #ifdef NETLINK_TCPDIAG
4408 PyModule_AddIntConstant(m
, "NETLINK_TCPDIAG", NETLINK_TCPDIAG
);
4410 #ifdef NETLINK_NFLOG
4411 PyModule_AddIntConstant(m
, "NETLINK_NFLOG", NETLINK_NFLOG
);
4414 PyModule_AddIntConstant(m
, "NETLINK_XFRM", NETLINK_XFRM
);
4417 PyModule_AddIntConstant(m
, "NETLINK_ARPD", NETLINK_ARPD
);
4419 #ifdef NETLINK_ROUTE6
4420 PyModule_AddIntConstant(m
, "NETLINK_ROUTE6", NETLINK_ROUTE6
);
4422 PyModule_AddIntConstant(m
, "NETLINK_IP6_FW", NETLINK_IP6_FW
);
4423 #ifdef NETLINK_DNRTMSG
4424 PyModule_AddIntConstant(m
, "NETLINK_DNRTMSG", NETLINK_DNRTMSG
);
4426 #ifdef NETLINK_TAPBASE
4427 PyModule_AddIntConstant(m
, "NETLINK_TAPBASE", NETLINK_TAPBASE
);
4429 #endif /* AF_NETLINK */
4431 /* Alias to emulate 4.4BSD */
4432 PyModule_AddIntConstant(m
, "AF_ROUTE", AF_ROUTE
);
4436 PyModule_AddIntConstant(m
, "AF_ASH", AF_ASH
);
4440 PyModule_AddIntConstant(m
, "AF_ECONET", AF_ECONET
);
4444 PyModule_AddIntConstant(m
, "AF_ATMSVC", AF_ATMSVC
);
4447 /* Linux SNA Project (nutters!) */
4448 PyModule_AddIntConstant(m
, "AF_SNA", AF_SNA
);
4452 PyModule_AddIntConstant(m
, "AF_IRDA", AF_IRDA
);
4456 PyModule_AddIntConstant(m
, "AF_PPPOX", AF_PPPOX
);
4459 /* Wanpipe API Sockets */
4460 PyModule_AddIntConstant(m
, "AF_WANPIPE", AF_WANPIPE
);
4464 PyModule_AddIntConstant(m
, "AF_LLC", AF_LLC
);
4467 #ifdef USE_BLUETOOTH
4468 PyModule_AddIntConstant(m
, "AF_BLUETOOTH", AF_BLUETOOTH
);
4469 PyModule_AddIntConstant(m
, "BTPROTO_L2CAP", BTPROTO_L2CAP
);
4470 PyModule_AddIntConstant(m
, "BTPROTO_HCI", BTPROTO_HCI
);
4471 PyModule_AddIntConstant(m
, "SOL_HCI", SOL_HCI
);
4472 PyModule_AddIntConstant(m
, "HCI_FILTER", HCI_FILTER
);
4473 #if !defined(__FreeBSD__)
4474 PyModule_AddIntConstant(m
, "HCI_TIME_STAMP", HCI_TIME_STAMP
);
4475 PyModule_AddIntConstant(m
, "HCI_DATA_DIR", HCI_DATA_DIR
);
4476 PyModule_AddIntConstant(m
, "BTPROTO_SCO", BTPROTO_SCO
);
4478 PyModule_AddIntConstant(m
, "BTPROTO_RFCOMM", BTPROTO_RFCOMM
);
4479 PyModule_AddStringConstant(m
, "BDADDR_ANY", "00:00:00:00:00:00");
4480 PyModule_AddStringConstant(m
, "BDADDR_LOCAL", "00:00:00:FF:FF:FF");
4483 #ifdef HAVE_NETPACKET_PACKET_H
4484 PyModule_AddIntConstant(m
, "AF_PACKET", AF_PACKET
);
4485 PyModule_AddIntConstant(m
, "PF_PACKET", PF_PACKET
);
4486 PyModule_AddIntConstant(m
, "PACKET_HOST", PACKET_HOST
);
4487 PyModule_AddIntConstant(m
, "PACKET_BROADCAST", PACKET_BROADCAST
);
4488 PyModule_AddIntConstant(m
, "PACKET_MULTICAST", PACKET_MULTICAST
);
4489 PyModule_AddIntConstant(m
, "PACKET_OTHERHOST", PACKET_OTHERHOST
);
4490 PyModule_AddIntConstant(m
, "PACKET_OUTGOING", PACKET_OUTGOING
);
4491 PyModule_AddIntConstant(m
, "PACKET_LOOPBACK", PACKET_LOOPBACK
);
4492 PyModule_AddIntConstant(m
, "PACKET_FASTROUTE", PACKET_FASTROUTE
);
4496 PyModule_AddIntConstant(m
, "SOCK_STREAM", SOCK_STREAM
);
4497 PyModule_AddIntConstant(m
, "SOCK_DGRAM", SOCK_DGRAM
);
4499 /* We have incomplete socket support. */
4500 PyModule_AddIntConstant(m
, "SOCK_RAW", SOCK_RAW
);
4501 PyModule_AddIntConstant(m
, "SOCK_SEQPACKET", SOCK_SEQPACKET
);
4502 #if defined(SOCK_RDM)
4503 PyModule_AddIntConstant(m
, "SOCK_RDM", SOCK_RDM
);
4508 PyModule_AddIntConstant(m
, "SO_DEBUG", SO_DEBUG
);
4510 #ifdef SO_ACCEPTCONN
4511 PyModule_AddIntConstant(m
, "SO_ACCEPTCONN", SO_ACCEPTCONN
);
4514 PyModule_AddIntConstant(m
, "SO_REUSEADDR", SO_REUSEADDR
);
4516 #ifdef SO_EXCLUSIVEADDRUSE
4517 PyModule_AddIntConstant(m
, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE
);
4521 PyModule_AddIntConstant(m
, "SO_KEEPALIVE", SO_KEEPALIVE
);
4524 PyModule_AddIntConstant(m
, "SO_DONTROUTE", SO_DONTROUTE
);
4527 PyModule_AddIntConstant(m
, "SO_BROADCAST", SO_BROADCAST
);
4529 #ifdef SO_USELOOPBACK
4530 PyModule_AddIntConstant(m
, "SO_USELOOPBACK", SO_USELOOPBACK
);
4533 PyModule_AddIntConstant(m
, "SO_LINGER", SO_LINGER
);
4536 PyModule_AddIntConstant(m
, "SO_OOBINLINE", SO_OOBINLINE
);
4539 PyModule_AddIntConstant(m
, "SO_REUSEPORT", SO_REUSEPORT
);
4542 PyModule_AddIntConstant(m
, "SO_SNDBUF", SO_SNDBUF
);
4545 PyModule_AddIntConstant(m
, "SO_RCVBUF", SO_RCVBUF
);
4548 PyModule_AddIntConstant(m
, "SO_SNDLOWAT", SO_SNDLOWAT
);
4551 PyModule_AddIntConstant(m
, "SO_RCVLOWAT", SO_RCVLOWAT
);
4554 PyModule_AddIntConstant(m
, "SO_SNDTIMEO", SO_SNDTIMEO
);
4557 PyModule_AddIntConstant(m
, "SO_RCVTIMEO", SO_RCVTIMEO
);
4560 PyModule_AddIntConstant(m
, "SO_ERROR", SO_ERROR
);
4563 PyModule_AddIntConstant(m
, "SO_TYPE", SO_TYPE
);
4566 /* Maximum number of connections for "listen" */
4568 PyModule_AddIntConstant(m
, "SOMAXCONN", SOMAXCONN
);
4570 PyModule_AddIntConstant(m
, "SOMAXCONN", 5); /* Common value */
4573 /* Flags for send, recv */
4575 PyModule_AddIntConstant(m
, "MSG_OOB", MSG_OOB
);
4578 PyModule_AddIntConstant(m
, "MSG_PEEK", MSG_PEEK
);
4580 #ifdef MSG_DONTROUTE
4581 PyModule_AddIntConstant(m
, "MSG_DONTROUTE", MSG_DONTROUTE
);
4584 PyModule_AddIntConstant(m
, "MSG_DONTWAIT", MSG_DONTWAIT
);
4587 PyModule_AddIntConstant(m
, "MSG_EOR", MSG_EOR
);
4590 PyModule_AddIntConstant(m
, "MSG_TRUNC", MSG_TRUNC
);
4593 PyModule_AddIntConstant(m
, "MSG_CTRUNC", MSG_CTRUNC
);
4596 PyModule_AddIntConstant(m
, "MSG_WAITALL", MSG_WAITALL
);
4599 PyModule_AddIntConstant(m
, "MSG_BTAG", MSG_BTAG
);
4602 PyModule_AddIntConstant(m
, "MSG_ETAG", MSG_ETAG
);
4605 /* Protocol level and numbers, usable for [gs]etsockopt */
4607 PyModule_AddIntConstant(m
, "SOL_SOCKET", SOL_SOCKET
);
4610 PyModule_AddIntConstant(m
, "SOL_IP", SOL_IP
);
4612 PyModule_AddIntConstant(m
, "SOL_IP", 0);
4615 PyModule_AddIntConstant(m
, "SOL_IPX", SOL_IPX
);
4618 PyModule_AddIntConstant(m
, "SOL_AX25", SOL_AX25
);
4621 PyModule_AddIntConstant(m
, "SOL_ATALK", SOL_ATALK
);
4624 PyModule_AddIntConstant(m
, "SOL_NETROM", SOL_NETROM
);
4627 PyModule_AddIntConstant(m
, "SOL_ROSE", SOL_ROSE
);
4630 PyModule_AddIntConstant(m
, "SOL_TCP", SOL_TCP
);
4632 PyModule_AddIntConstant(m
, "SOL_TCP", 6);
4635 PyModule_AddIntConstant(m
, "SOL_UDP", SOL_UDP
);
4637 PyModule_AddIntConstant(m
, "SOL_UDP", 17);
4640 PyModule_AddIntConstant(m
, "IPPROTO_IP", IPPROTO_IP
);
4642 PyModule_AddIntConstant(m
, "IPPROTO_IP", 0);
4644 #ifdef IPPROTO_HOPOPTS
4645 PyModule_AddIntConstant(m
, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS
);
4648 PyModule_AddIntConstant(m
, "IPPROTO_ICMP", IPPROTO_ICMP
);
4650 PyModule_AddIntConstant(m
, "IPPROTO_ICMP", 1);
4653 PyModule_AddIntConstant(m
, "IPPROTO_IGMP", IPPROTO_IGMP
);
4656 PyModule_AddIntConstant(m
, "IPPROTO_GGP", IPPROTO_GGP
);
4659 PyModule_AddIntConstant(m
, "IPPROTO_IPV4", IPPROTO_IPV4
);
4662 PyModule_AddIntConstant(m
, "IPPROTO_IPV6", IPPROTO_IPV6
);
4665 PyModule_AddIntConstant(m
, "IPPROTO_IPIP", IPPROTO_IPIP
);
4668 PyModule_AddIntConstant(m
, "IPPROTO_TCP", IPPROTO_TCP
);
4670 PyModule_AddIntConstant(m
, "IPPROTO_TCP", 6);
4673 PyModule_AddIntConstant(m
, "IPPROTO_EGP", IPPROTO_EGP
);
4676 PyModule_AddIntConstant(m
, "IPPROTO_PUP", IPPROTO_PUP
);
4679 PyModule_AddIntConstant(m
, "IPPROTO_UDP", IPPROTO_UDP
);
4681 PyModule_AddIntConstant(m
, "IPPROTO_UDP", 17);
4684 PyModule_AddIntConstant(m
, "IPPROTO_IDP", IPPROTO_IDP
);
4686 #ifdef IPPROTO_HELLO
4687 PyModule_AddIntConstant(m
, "IPPROTO_HELLO", IPPROTO_HELLO
);
4690 PyModule_AddIntConstant(m
, "IPPROTO_ND", IPPROTO_ND
);
4693 PyModule_AddIntConstant(m
, "IPPROTO_TP", IPPROTO_TP
);
4696 PyModule_AddIntConstant(m
, "IPPROTO_IPV6", IPPROTO_IPV6
);
4698 #ifdef IPPROTO_ROUTING
4699 PyModule_AddIntConstant(m
, "IPPROTO_ROUTING", IPPROTO_ROUTING
);
4701 #ifdef IPPROTO_FRAGMENT
4702 PyModule_AddIntConstant(m
, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT
);
4705 PyModule_AddIntConstant(m
, "IPPROTO_RSVP", IPPROTO_RSVP
);
4708 PyModule_AddIntConstant(m
, "IPPROTO_GRE", IPPROTO_GRE
);
4711 PyModule_AddIntConstant(m
, "IPPROTO_ESP", IPPROTO_ESP
);
4714 PyModule_AddIntConstant(m
, "IPPROTO_AH", IPPROTO_AH
);
4716 #ifdef IPPROTO_MOBILE
4717 PyModule_AddIntConstant(m
, "IPPROTO_MOBILE", IPPROTO_MOBILE
);
4719 #ifdef IPPROTO_ICMPV6
4720 PyModule_AddIntConstant(m
, "IPPROTO_ICMPV6", IPPROTO_ICMPV6
);
4723 PyModule_AddIntConstant(m
, "IPPROTO_NONE", IPPROTO_NONE
);
4725 #ifdef IPPROTO_DSTOPTS
4726 PyModule_AddIntConstant(m
, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS
);
4729 PyModule_AddIntConstant(m
, "IPPROTO_XTP", IPPROTO_XTP
);
4732 PyModule_AddIntConstant(m
, "IPPROTO_EON", IPPROTO_EON
);
4735 PyModule_AddIntConstant(m
, "IPPROTO_PIM", IPPROTO_PIM
);
4737 #ifdef IPPROTO_IPCOMP
4738 PyModule_AddIntConstant(m
, "IPPROTO_IPCOMP", IPPROTO_IPCOMP
);
4741 PyModule_AddIntConstant(m
, "IPPROTO_VRRP", IPPROTO_VRRP
);
4744 PyModule_AddIntConstant(m
, "IPPROTO_BIP", IPPROTO_BIP
);
4748 PyModule_AddIntConstant(m
, "IPPROTO_RAW", IPPROTO_RAW
);
4750 PyModule_AddIntConstant(m
, "IPPROTO_RAW", 255);
4753 PyModule_AddIntConstant(m
, "IPPROTO_MAX", IPPROTO_MAX
);
4756 /* Some port configuration */
4757 #ifdef IPPORT_RESERVED
4758 PyModule_AddIntConstant(m
, "IPPORT_RESERVED", IPPORT_RESERVED
);
4760 PyModule_AddIntConstant(m
, "IPPORT_RESERVED", 1024);
4762 #ifdef IPPORT_USERRESERVED
4763 PyModule_AddIntConstant(m
, "IPPORT_USERRESERVED", IPPORT_USERRESERVED
);
4765 PyModule_AddIntConstant(m
, "IPPORT_USERRESERVED", 5000);
4768 /* Some reserved IP v.4 addresses */
4770 PyModule_AddIntConstant(m
, "INADDR_ANY", INADDR_ANY
);
4772 PyModule_AddIntConstant(m
, "INADDR_ANY", 0x00000000);
4774 #ifdef INADDR_BROADCAST
4775 PyModule_AddIntConstant(m
, "INADDR_BROADCAST", INADDR_BROADCAST
);
4777 PyModule_AddIntConstant(m
, "INADDR_BROADCAST", 0xffffffff);
4779 #ifdef INADDR_LOOPBACK
4780 PyModule_AddIntConstant(m
, "INADDR_LOOPBACK", INADDR_LOOPBACK
);
4782 PyModule_AddIntConstant(m
, "INADDR_LOOPBACK", 0x7F000001);
4784 #ifdef INADDR_UNSPEC_GROUP
4785 PyModule_AddIntConstant(m
, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP
);
4787 PyModule_AddIntConstant(m
, "INADDR_UNSPEC_GROUP", 0xe0000000);
4789 #ifdef INADDR_ALLHOSTS_GROUP
4790 PyModule_AddIntConstant(m
, "INADDR_ALLHOSTS_GROUP",
4791 INADDR_ALLHOSTS_GROUP
);
4793 PyModule_AddIntConstant(m
, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
4795 #ifdef INADDR_MAX_LOCAL_GROUP
4796 PyModule_AddIntConstant(m
, "INADDR_MAX_LOCAL_GROUP",
4797 INADDR_MAX_LOCAL_GROUP
);
4799 PyModule_AddIntConstant(m
, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
4802 PyModule_AddIntConstant(m
, "INADDR_NONE", INADDR_NONE
);
4804 PyModule_AddIntConstant(m
, "INADDR_NONE", 0xffffffff);
4807 /* IPv4 [gs]etsockopt options */
4809 PyModule_AddIntConstant(m
, "IP_OPTIONS", IP_OPTIONS
);
4812 PyModule_AddIntConstant(m
, "IP_HDRINCL", IP_HDRINCL
);
4815 PyModule_AddIntConstant(m
, "IP_TOS", IP_TOS
);
4818 PyModule_AddIntConstant(m
, "IP_TTL", IP_TTL
);
4821 PyModule_AddIntConstant(m
, "IP_RECVOPTS", IP_RECVOPTS
);
4823 #ifdef IP_RECVRETOPTS
4824 PyModule_AddIntConstant(m
, "IP_RECVRETOPTS", IP_RECVRETOPTS
);
4826 #ifdef IP_RECVDSTADDR
4827 PyModule_AddIntConstant(m
, "IP_RECVDSTADDR", IP_RECVDSTADDR
);
4830 PyModule_AddIntConstant(m
, "IP_RETOPTS", IP_RETOPTS
);
4832 #ifdef IP_MULTICAST_IF
4833 PyModule_AddIntConstant(m
, "IP_MULTICAST_IF", IP_MULTICAST_IF
);
4835 #ifdef IP_MULTICAST_TTL
4836 PyModule_AddIntConstant(m
, "IP_MULTICAST_TTL", IP_MULTICAST_TTL
);
4838 #ifdef IP_MULTICAST_LOOP
4839 PyModule_AddIntConstant(m
, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP
);
4841 #ifdef IP_ADD_MEMBERSHIP
4842 PyModule_AddIntConstant(m
, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP
);
4844 #ifdef IP_DROP_MEMBERSHIP
4845 PyModule_AddIntConstant(m
, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP
);
4847 #ifdef IP_DEFAULT_MULTICAST_TTL
4848 PyModule_AddIntConstant(m
, "IP_DEFAULT_MULTICAST_TTL",
4849 IP_DEFAULT_MULTICAST_TTL
);
4851 #ifdef IP_DEFAULT_MULTICAST_LOOP
4852 PyModule_AddIntConstant(m
, "IP_DEFAULT_MULTICAST_LOOP",
4853 IP_DEFAULT_MULTICAST_LOOP
);
4855 #ifdef IP_MAX_MEMBERSHIPS
4856 PyModule_AddIntConstant(m
, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS
);
4859 /* IPv6 [gs]etsockopt options, defined in RFC2553 */
4860 #ifdef IPV6_JOIN_GROUP
4861 PyModule_AddIntConstant(m
, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP
);
4863 #ifdef IPV6_LEAVE_GROUP
4864 PyModule_AddIntConstant(m
, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP
);
4866 #ifdef IPV6_MULTICAST_HOPS
4867 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS
);
4869 #ifdef IPV6_MULTICAST_IF
4870 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF
);
4872 #ifdef IPV6_MULTICAST_LOOP
4873 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP
);
4875 #ifdef IPV6_UNICAST_HOPS
4876 PyModule_AddIntConstant(m
, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS
);
4878 /* Additional IPV6 socket options, defined in RFC 3493 */
4880 PyModule_AddIntConstant(m
, "IPV6_V6ONLY", IPV6_V6ONLY
);
4882 /* Advanced IPV6 socket options, from RFC 3542 */
4883 #ifdef IPV6_CHECKSUM
4884 PyModule_AddIntConstant(m
, "IPV6_CHECKSUM", IPV6_CHECKSUM
);
4886 #ifdef IPV6_DONTFRAG
4887 PyModule_AddIntConstant(m
, "IPV6_DONTFRAG", IPV6_DONTFRAG
);
4890 PyModule_AddIntConstant(m
, "IPV6_DSTOPTS", IPV6_DSTOPTS
);
4892 #ifdef IPV6_HOPLIMIT
4893 PyModule_AddIntConstant(m
, "IPV6_HOPLIMIT", IPV6_HOPLIMIT
);
4896 PyModule_AddIntConstant(m
, "IPV6_HOPOPTS", IPV6_HOPOPTS
);
4899 PyModule_AddIntConstant(m
, "IPV6_NEXTHOP", IPV6_NEXTHOP
);
4902 PyModule_AddIntConstant(m
, "IPV6_PATHMTU", IPV6_PATHMTU
);
4905 PyModule_AddIntConstant(m
, "IPV6_PKTINFO", IPV6_PKTINFO
);
4907 #ifdef IPV6_RECVDSTOPTS
4908 PyModule_AddIntConstant(m
, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS
);
4910 #ifdef IPV6_RECVHOPLIMIT
4911 PyModule_AddIntConstant(m
, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT
);
4913 #ifdef IPV6_RECVHOPOPTS
4914 PyModule_AddIntConstant(m
, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS
);
4916 #ifdef IPV6_RECVPKTINFO
4917 PyModule_AddIntConstant(m
, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO
);
4919 #ifdef IPV6_RECVRTHDR
4920 PyModule_AddIntConstant(m
, "IPV6_RECVRTHDR", IPV6_RECVRTHDR
);
4922 #ifdef IPV6_RECVTCLASS
4923 PyModule_AddIntConstant(m
, "IPV6_RECVTCLASS", IPV6_RECVTCLASS
);
4926 PyModule_AddIntConstant(m
, "IPV6_RTHDR", IPV6_RTHDR
);
4928 #ifdef IPV6_RTHDRDSTOPTS
4929 PyModule_AddIntConstant(m
, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS
);
4931 #ifdef IPV6_RTHDR_TYPE_0
4932 PyModule_AddIntConstant(m
, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0
);
4934 #ifdef IPV6_RECVPATHMTU
4935 PyModule_AddIntConstant(m
, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU
);
4938 PyModule_AddIntConstant(m
, "IPV6_TCLASS", IPV6_TCLASS
);
4940 #ifdef IPV6_USE_MIN_MTU
4941 PyModule_AddIntConstant(m
, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU
);
4946 PyModule_AddIntConstant(m
, "TCP_NODELAY", TCP_NODELAY
);
4949 PyModule_AddIntConstant(m
, "TCP_MAXSEG", TCP_MAXSEG
);
4952 PyModule_AddIntConstant(m
, "TCP_CORK", TCP_CORK
);
4955 PyModule_AddIntConstant(m
, "TCP_KEEPIDLE", TCP_KEEPIDLE
);
4957 #ifdef TCP_KEEPINTVL
4958 PyModule_AddIntConstant(m
, "TCP_KEEPINTVL", TCP_KEEPINTVL
);
4961 PyModule_AddIntConstant(m
, "TCP_KEEPCNT", TCP_KEEPCNT
);
4964 PyModule_AddIntConstant(m
, "TCP_SYNCNT", TCP_SYNCNT
);
4967 PyModule_AddIntConstant(m
, "TCP_LINGER2", TCP_LINGER2
);
4969 #ifdef TCP_DEFER_ACCEPT
4970 PyModule_AddIntConstant(m
, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT
);
4972 #ifdef TCP_WINDOW_CLAMP
4973 PyModule_AddIntConstant(m
, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP
);
4976 PyModule_AddIntConstant(m
, "TCP_INFO", TCP_INFO
);
4979 PyModule_AddIntConstant(m
, "TCP_QUICKACK", TCP_QUICKACK
);
4985 PyModule_AddIntConstant(m
, "IPX_TYPE", IPX_TYPE
);
4988 /* get{addr,name}info parameters */
4989 #ifdef EAI_ADDRFAMILY
4990 PyModule_AddIntConstant(m
, "EAI_ADDRFAMILY", EAI_ADDRFAMILY
);
4993 PyModule_AddIntConstant(m
, "EAI_AGAIN", EAI_AGAIN
);
4996 PyModule_AddIntConstant(m
, "EAI_BADFLAGS", EAI_BADFLAGS
);
4999 PyModule_AddIntConstant(m
, "EAI_FAIL", EAI_FAIL
);
5002 PyModule_AddIntConstant(m
, "EAI_FAMILY", EAI_FAMILY
);
5005 PyModule_AddIntConstant(m
, "EAI_MEMORY", EAI_MEMORY
);
5008 PyModule_AddIntConstant(m
, "EAI_NODATA", EAI_NODATA
);
5011 PyModule_AddIntConstant(m
, "EAI_NONAME", EAI_NONAME
);
5014 PyModule_AddIntConstant(m
, "EAI_OVERFLOW", EAI_OVERFLOW
);
5017 PyModule_AddIntConstant(m
, "EAI_SERVICE", EAI_SERVICE
);
5020 PyModule_AddIntConstant(m
, "EAI_SOCKTYPE", EAI_SOCKTYPE
);
5023 PyModule_AddIntConstant(m
, "EAI_SYSTEM", EAI_SYSTEM
);
5026 PyModule_AddIntConstant(m
, "EAI_BADHINTS", EAI_BADHINTS
);
5029 PyModule_AddIntConstant(m
, "EAI_PROTOCOL", EAI_PROTOCOL
);
5032 PyModule_AddIntConstant(m
, "EAI_MAX", EAI_MAX
);
5035 PyModule_AddIntConstant(m
, "AI_PASSIVE", AI_PASSIVE
);
5038 PyModule_AddIntConstant(m
, "AI_CANONNAME", AI_CANONNAME
);
5040 #ifdef AI_NUMERICHOST
5041 PyModule_AddIntConstant(m
, "AI_NUMERICHOST", AI_NUMERICHOST
);
5043 #ifdef AI_NUMERICSERV
5044 PyModule_AddIntConstant(m
, "AI_NUMERICSERV", AI_NUMERICSERV
);
5047 PyModule_AddIntConstant(m
, "AI_MASK", AI_MASK
);
5050 PyModule_AddIntConstant(m
, "AI_ALL", AI_ALL
);
5052 #ifdef AI_V4MAPPED_CFG
5053 PyModule_AddIntConstant(m
, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG
);
5055 #ifdef AI_ADDRCONFIG
5056 PyModule_AddIntConstant(m
, "AI_ADDRCONFIG", AI_ADDRCONFIG
);
5059 PyModule_AddIntConstant(m
, "AI_V4MAPPED", AI_V4MAPPED
);
5062 PyModule_AddIntConstant(m
, "AI_DEFAULT", AI_DEFAULT
);
5065 PyModule_AddIntConstant(m
, "NI_MAXHOST", NI_MAXHOST
);
5068 PyModule_AddIntConstant(m
, "NI_MAXSERV", NI_MAXSERV
);
5071 PyModule_AddIntConstant(m
, "NI_NOFQDN", NI_NOFQDN
);
5073 #ifdef NI_NUMERICHOST
5074 PyModule_AddIntConstant(m
, "NI_NUMERICHOST", NI_NUMERICHOST
);
5077 PyModule_AddIntConstant(m
, "NI_NAMEREQD", NI_NAMEREQD
);
5079 #ifdef NI_NUMERICSERV
5080 PyModule_AddIntConstant(m
, "NI_NUMERICSERV", NI_NUMERICSERV
);
5083 PyModule_AddIntConstant(m
, "NI_DGRAM", NI_DGRAM
);
5086 /* shutdown() parameters */
5088 PyModule_AddIntConstant(m
, "SHUT_RD", SHUT_RD
);
5089 #elif defined(SD_RECEIVE)
5090 PyModule_AddIntConstant(m
, "SHUT_RD", SD_RECEIVE
);
5092 PyModule_AddIntConstant(m
, "SHUT_RD", 0);
5095 PyModule_AddIntConstant(m
, "SHUT_WR", SHUT_WR
);
5096 #elif defined(SD_SEND)
5097 PyModule_AddIntConstant(m
, "SHUT_WR", SD_SEND
);
5099 PyModule_AddIntConstant(m
, "SHUT_WR", 1);
5102 PyModule_AddIntConstant(m
, "SHUT_RDWR", SHUT_RDWR
);
5103 #elif defined(SD_BOTH)
5104 PyModule_AddIntConstant(m
, "SHUT_RDWR", SD_BOTH
);
5106 PyModule_AddIntConstant(m
, "SHUT_RDWR", 2);
5109 /* Initialize gethostbyname lock */
5110 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
5111 netdb_lock
= PyThread_allocate_lock();
5116 #ifndef HAVE_INET_PTON
5118 /* Simplistic emulation code for inet_pton that only works for IPv4 */
5119 /* These are not exposed because they do not set errno properly */
5122 inet_pton(int af
, const char *src
, void *dst
)
5124 if (af
== AF_INET
) {
5126 packed_addr
= inet_addr(src
);
5127 if (packed_addr
== INADDR_NONE
)
5129 memcpy(dst
, &packed_addr
, 4);
5132 /* Should set errno to EAFNOSUPPORT */
5137 inet_ntop(int af
, const void *src
, char *dst
, socklen_t size
)
5139 if (af
== AF_INET
) {
5140 struct in_addr packed_addr
;
5142 /* Should set errno to ENOSPC. */
5144 memcpy(&packed_addr
, src
, sizeof(packed_addr
));
5145 return strncpy(dst
, inet_ntoa(packed_addr
), size
);
5147 /* Should set errno to EAFNOSUPPORT */