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
65 #include "structmember.h"
68 #define MAX(x, y) ((x) < (y) ? (y) : (x))
70 /* Socket object documentation */
71 PyDoc_STRVAR(sock_doc
,
72 "socket([family[, type[, proto]]]) -> socket object\n\
74 Open a socket of the given type. The family argument specifies the\n\
75 address family; it defaults to AF_INET. The type argument specifies\n\
76 whether this is a stream (SOCK_STREAM, this is the default)\n\
77 or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0,\n\
78 specifying the default protocol. Keyword arguments are accepted.\n\
80 A socket object represents one endpoint of a network connection.\n\
82 Methods of socket objects (keyword arguments not allowed):\n\
84 accept() -- accept a connection, returning new socket and client address\n\
85 bind(addr) -- bind the socket to a local address\n\
86 close() -- close the socket\n\
87 connect(addr) -- connect the socket to a remote address\n\
88 connect_ex(addr) -- connect, return an error code instead of an exception\n\
89 dup() -- return a new socket object identical to the current one [*]\n\
90 fileno() -- return underlying file descriptor\n\
91 getpeername() -- return remote address [*]\n\
92 getsockname() -- return local address\n\
93 getsockopt(level, optname[, buflen]) -- get socket options\n\
94 gettimeout() -- return timeout or None\n\
95 listen(n) -- start listening for incoming connections\n\
96 makefile([mode, [bufsize]]) -- return a file object for the socket [*]\n\
97 recv(buflen[, flags]) -- receive data\n\
98 recvfrom(buflen[, flags]) -- receive data and sender's address\n\
99 sendall(data[, flags]) -- send all data\n\
100 send(data[, flags]) -- send data, may not send all of it\n\
101 sendto(data[, flags], addr) -- send data to a given address\n\
102 setblocking(0 | 1) -- set or clear the blocking I/O flag\n\
103 setsockopt(level, optname, value) -- set socket options\n\
104 settimeout(None | float) -- set or clear the timeout\n\
105 shutdown(how) -- shut down traffic in one or both directions\n\
107 [*] not available on all platforms!");
109 /* XXX This is a terrible mess of platform-dependent preprocessor hacks.
110 I hope some day someone can clean this up please... */
112 /* Hacks for gethostbyname_r(). On some non-Linux platforms, the configure
113 script doesn't get this right, so we hardcode some platform checks below.
114 On the other hand, not all Linux versions agree, so there the settings
115 computed by the configure script are needed! */
118 # undef HAVE_GETHOSTBYNAME_R_3_ARG
119 # undef HAVE_GETHOSTBYNAME_R_5_ARG
120 # undef HAVE_GETHOSTBYNAME_R_6_ARG
124 # undef HAVE_GETHOSTBYNAME_R
127 #ifdef HAVE_GETHOSTBYNAME_R
128 # if defined(_AIX) || defined(__osf__)
129 # define HAVE_GETHOSTBYNAME_R_3_ARG
130 # elif defined(__sun) || defined(__sgi)
131 # define HAVE_GETHOSTBYNAME_R_5_ARG
132 # elif defined(linux)
133 /* Rely on the configure script */
135 # undef HAVE_GETHOSTBYNAME_R
139 #if !defined(HAVE_GETHOSTBYNAME_R) && defined(WITH_THREAD) && \
141 # define USE_GETHOSTBYNAME_LOCK
144 /* To use __FreeBSD_version */
145 #ifdef HAVE_SYS_PARAM_H
146 #include <sys/param.h>
148 /* On systems on which getaddrinfo() is believed to not be thread-safe,
149 (this includes the getaddrinfo emulation) protect access with a lock. */
150 #if defined(WITH_THREAD) && (defined(__APPLE__) || \
151 (defined(__FreeBSD__) && __FreeBSD_version+0 < 503000) || \
152 defined(__OpenBSD__) || defined(__NetBSD__) || !defined(HAVE_GETADDRINFO))
153 #define USE_GETADDRINFO_LOCK
156 #ifdef USE_GETADDRINFO_LOCK
157 #define ACQUIRE_GETADDRINFO_LOCK PyThread_acquire_lock(netdb_lock, 1);
158 #define RELEASE_GETADDRINFO_LOCK PyThread_release_lock(netdb_lock);
160 #define ACQUIRE_GETADDRINFO_LOCK
161 #define RELEASE_GETADDRINFO_LOCK
164 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
165 # include "pythread.h"
168 #if defined(PYCC_VACPP)
171 # include <sys/ioctl.h>
177 #if ! defined(_SOCKADDR_LEN)
181 # include "TCPIP_IOCTL_ROUTINE"
187 #if defined(PYOS_OS2)
189 # define INCL_DOSERRORS
190 # define INCL_NOPMAPI
194 #if defined(__sgi) && _COMPILER_VERSION>700 && !_SGIAPI
195 /* make sure that the reentrant (gethostbyaddr_r etc)
196 functions are declared correctly if compiling with
197 MIPSPro 7.x in ANSI C mode (default) */
199 /* XXX Using _SGIAPI is the wrong thing,
200 but I don't know what the right thing is. */
201 #undef _SGIAPI /* to avoid warning */
205 #include <sys/socket.h>
206 #include <sys/types.h>
207 #include <netinet/in.h>
209 #define HAVE_GETADDRINFO 1
210 #define HAVE_GETNAMEINFO 1
213 #define HAVE_INET_PTON
217 /* Irix 6.5 fails to define this variable at all. This is needed
218 for both GCC and SGI's compiler. I'd say that the SGI headers
219 are just busted. Same thing for Solaris. */
220 #if (defined(__sgi) || defined(sun)) && !defined(INET_ADDRSTRLEN)
221 #define INET_ADDRSTRLEN 16
224 /* Generic includes */
225 #include <sys/types.h>
227 /* Generic socket object definitions and includes */
228 #define PySocket_BUILDING_SOCKET
229 #include "socketmodule.h"
231 /* Addressing includes */
235 /* Non-MS WINDOWS includes */
238 /* Headers needed for inet_ntoa() and inet_addr() */
240 # include <net/netdb.h>
241 # elif defined(PYOS_OS2) && defined(PYCC_VACPP)
243 typedef size_t socklen_t
;
245 # include <arpa/inet.h>
251 # include <sys/ioctl.h>
252 # include <socklib.h>
254 int h_errno
; /* not used */
255 # define INET_ADDRSTRLEN 16
260 /* MS_WINDOWS includes */
268 # define offsetof(type, member) ((size_t)(&((type *)0)->member))
272 # define O_NONBLOCK O_NDELAY
275 /* include Python's addrinfo.h unless it causes trouble */
276 #if defined(__sgi) && _COMPILER_VERSION>700 && defined(_SS_ALIGNSIZE)
277 /* Do not include addinfo.h on some newer IRIX versions.
278 * _SS_ALIGNSIZE is defined in sys/socket.h by 6.5.21,
279 * for example, but not by 6.5.10.
281 #elif defined(_MSC_VER) && _MSC_VER>1200
282 /* Do not include addrinfo.h for MSVC7 or greater. 'addrinfo' and
283 * EAI_* constants are defined in (the already included) ws2tcpip.h.
286 # include "addrinfo.h"
289 #ifndef HAVE_INET_PTON
290 int inet_pton(int af
, const char *src
, void *dst
);
291 const char *inet_ntop(int af
, const void *src
, char *dst
, socklen_t size
);
295 /* On OS X, getaddrinfo returns no error indication of lookup
296 failure, so we must use the emulation instead of the libinfo
297 implementation. Unfortunately, performing an autoconf test
298 for this bug would require DNS access for the machine performing
299 the configuration, which is not acceptable. Therefore, we
300 determine the bug just by checking for __APPLE__. If this bug
301 gets ever fixed, perhaps checking for sys/version.h would be
302 appropriate, which is 10/0 on the system with the bug. */
303 #ifndef HAVE_GETNAMEINFO
304 /* This bug seems to be fixed in Jaguar. Ths easiest way I could
305 Find to check for Jaguar is that it has getnameinfo(), which
306 older releases don't have */
307 #undef HAVE_GETADDRINFO
311 /* I know this is a bad practice, but it is the easiest... */
312 #if !defined(HAVE_GETADDRINFO)
313 /* avoid clashes with the C library definition of the symbol. */
314 #define getaddrinfo fake_getaddrinfo
315 #define gai_strerror fake_gai_strerror
316 #define freeaddrinfo fake_freeaddrinfo
317 #include "getaddrinfo.c"
319 #if !defined(HAVE_GETNAMEINFO)
320 #define getnameinfo fake_getnameinfo
321 #include "getnameinfo.c"
324 #if defined(MS_WINDOWS) || defined(__BEOS__)
325 /* BeOS suffers from the same socket dichotomy as Win32... - [cjh] */
326 /* seem to be a few differences in the API */
327 #define SOCKETCLOSE closesocket
328 #define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */
332 #define EAFNOSUPPORT WSAEAFNOSUPPORT
333 #define snprintf _snprintf
336 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
337 #define SOCKETCLOSE soclose
338 #define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
342 #define SOCKETCLOSE close
346 /* TCP/IP Services for VMS uses a maximum send/revc buffer length of 65535 */
347 #define SEGMENT_SIZE 65535
350 #if defined(HAVE_BLUETOOTH_H) || defined(HAVE_BLUETOOTH_BLUETOOTH_H)
351 #define USE_BLUETOOTH 1
352 #if defined(__FreeBSD__)
353 #define BTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP
354 #define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM
355 #define sockaddr_l2 sockaddr_l2cap
356 #define sockaddr_rc sockaddr_rfcomm
357 #define _BT_SOCKADDR_MEMB(s, proto) &((s)->sock_addr)
358 #define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb)
359 #define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)
361 #define _BT_SOCKADDR_MEMB(s, proto) (&((s)->sock_addr).bt_##proto)
362 #define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb)
363 #define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb)
364 #define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)
369 * Constants for getnameinfo()
371 #if !defined(NI_MAXHOST)
372 #define NI_MAXHOST 1025
374 #if !defined(NI_MAXSERV)
375 #define NI_MAXSERV 32
378 /* XXX There's a problem here: *static* functions are not supposed to have
379 a Py prefix (or use CapitalizedWords). Later... */
381 /* Global variable holding the exception type for errors detected
382 by this module (but not argument type or memory errors, etc.). */
383 static PyObject
*socket_error
;
384 static PyObject
*socket_herror
;
385 static PyObject
*socket_gaierror
;
386 static PyObject
*socket_timeout
;
389 /* Global variable which is !=0 if Python is running in a RISC OS taskwindow */
390 static int taskwindow
;
393 /* A forward reference to the socket type object.
394 The sock_type variable contains pointers to various functions,
395 some of which call new_sockobject(), which uses sock_type, so
396 there has to be a circular reference. */
397 static PyTypeObject sock_type
;
399 /* Can we call select() with this socket without a buffer overrun? */
400 #ifdef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
401 /* Platform can select file descriptors beyond FD_SETSIZE */
402 #define IS_SELECTABLE(s) 1
404 /* POSIX says selecting file descriptors beyond FD_SETSIZE
405 has undefined behaviour. */
406 #define IS_SELECTABLE(s) ((s)->sock_fd < FD_SETSIZE)
412 PyErr_SetString(socket_error
, "unable to select on socket");
416 /* Convenience function to raise an error according to errno
417 and return a NULL pointer from a function. */
423 int err_no
= WSAGetLastError();
428 {WSAEINTR
, "Interrupted system call"},
429 {WSAEBADF
, "Bad file descriptor"},
430 {WSAEACCES
, "Permission denied"},
431 {WSAEFAULT
, "Bad address"},
432 {WSAEINVAL
, "Invalid argument"},
433 {WSAEMFILE
, "Too many open files"},
435 "The socket operation could not complete "
437 {WSAEINPROGRESS
, "Operation now in progress"},
438 {WSAEALREADY
, "Operation already in progress"},
439 {WSAENOTSOCK
, "Socket operation on non-socket"},
440 {WSAEDESTADDRREQ
, "Destination address required"},
441 {WSAEMSGSIZE
, "Message too long"},
442 {WSAEPROTOTYPE
, "Protocol wrong type for socket"},
443 {WSAENOPROTOOPT
, "Protocol not available"},
444 {WSAEPROTONOSUPPORT
, "Protocol not supported"},
445 {WSAESOCKTNOSUPPORT
, "Socket type not supported"},
446 {WSAEOPNOTSUPP
, "Operation not supported"},
447 {WSAEPFNOSUPPORT
, "Protocol family not supported"},
448 {WSAEAFNOSUPPORT
, "Address family not supported"},
449 {WSAEADDRINUSE
, "Address already in use"},
450 {WSAEADDRNOTAVAIL
, "Can't assign requested address"},
451 {WSAENETDOWN
, "Network is down"},
452 {WSAENETUNREACH
, "Network is unreachable"},
453 {WSAENETRESET
, "Network dropped connection on reset"},
454 {WSAECONNABORTED
, "Software caused connection abort"},
455 {WSAECONNRESET
, "Connection reset by peer"},
456 {WSAENOBUFS
, "No buffer space available"},
457 {WSAEISCONN
, "Socket is already connected"},
458 {WSAENOTCONN
, "Socket is not connected"},
459 {WSAESHUTDOWN
, "Can't send after socket shutdown"},
460 {WSAETOOMANYREFS
, "Too many references: can't splice"},
461 {WSAETIMEDOUT
, "Operation timed out"},
462 {WSAECONNREFUSED
, "Connection refused"},
463 {WSAELOOP
, "Too many levels of symbolic links"},
464 {WSAENAMETOOLONG
, "File name too long"},
465 {WSAEHOSTDOWN
, "Host is down"},
466 {WSAEHOSTUNREACH
, "No route to host"},
467 {WSAENOTEMPTY
, "Directory not empty"},
468 {WSAEPROCLIM
, "Too many processes"},
469 {WSAEUSERS
, "Too many users"},
470 {WSAEDQUOT
, "Disc quota exceeded"},
471 {WSAESTALE
, "Stale NFS file handle"},
472 {WSAEREMOTE
, "Too many levels of remote in path"},
473 {WSASYSNOTREADY
, "Network subsystem is unvailable"},
474 {WSAVERNOTSUPPORTED
, "WinSock version is not supported"},
476 "Successful WSAStartup() not yet performed"},
477 {WSAEDISCON
, "Graceful shutdown in progress"},
478 /* Resolver errors */
479 {WSAHOST_NOT_FOUND
, "No such host is known"},
480 {WSATRY_AGAIN
, "Host not found, or server failed"},
481 {WSANO_RECOVERY
, "Unexpected server error encountered"},
482 {WSANO_DATA
, "Valid name without requested data"},
483 {WSANO_ADDRESS
, "No address, look for MX record"},
488 const char *msg
= "winsock error";
490 for (msgp
= msgs
; msgp
->msg
; msgp
++) {
491 if (err_no
== msgp
->no
) {
497 v
= Py_BuildValue("(is)", err_no
, msg
);
499 PyErr_SetObject(socket_error
, v
);
507 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
508 if (sock_errno() != NO_ERROR
) {
512 int myerrorcode
= sock_errno();
514 /* Retrieve socket-related error message from MPTN.MSG file */
515 rc
= DosGetMessage(NULL
, 0, outbuf
, sizeof(outbuf
),
516 myerrorcode
- SOCBASEERR
+ 26,
519 if (rc
== NO_ERROR
) {
522 /* OS/2 doesn't guarantee a terminator */
523 outbuf
[msglen
] = '\0';
524 if (strlen(outbuf
) > 0) {
525 /* If non-empty msg, trim CRLF */
526 char *lastc
= &outbuf
[ strlen(outbuf
)-1 ];
527 while (lastc
> outbuf
&&
528 isspace(Py_CHARMASK(*lastc
))) {
529 /* Trim trailing whitespace (CRLF) */
533 v
= Py_BuildValue("(is)", myerrorcode
, outbuf
);
535 PyErr_SetObject(socket_error
, v
);
544 if (_inet_error
.errnum
!= NULL
) {
546 v
= Py_BuildValue("(is)", errno
, _inet_err());
548 PyErr_SetObject(socket_error
, v
);
555 return PyErr_SetFromErrno(socket_error
);
560 set_herror(int h_error
)
564 #ifdef HAVE_HSTRERROR
565 v
= Py_BuildValue("(is)", h_error
, (char *)hstrerror(h_error
));
567 v
= Py_BuildValue("(is)", h_error
, "host not found");
570 PyErr_SetObject(socket_herror
, v
);
579 set_gaierror(int error
)
584 /* EAI_SYSTEM is not available on Windows XP. */
585 if (error
== EAI_SYSTEM
)
589 #ifdef HAVE_GAI_STRERROR
590 v
= Py_BuildValue("(is)", error
, gai_strerror(error
));
592 v
= Py_BuildValue("(is)", error
, "getaddrinfo failed");
595 PyErr_SetObject(socket_gaierror
, v
);
602 /* Function to perform the setting of socket blocking mode
603 internally. block = (1 | 0). */
605 internal_setblocking(PySocketSockObject
*s
, int block
)
613 Py_BEGIN_ALLOW_THREADS
616 setsockopt(s
->sock_fd
, SOL_SOCKET
, SO_NONBLOCK
,
617 (void *)(&block
), sizeof(int));
621 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
623 ioctl(s
->sock_fd
, FIONBIO
, (caddr_t
)&block
, sizeof(block
));
626 ioctl(s
->sock_fd
, FIONBIO
, (char *)&block
);
627 #else /* !PYOS_OS2 && !_VMS */
628 delay_flag
= fcntl(s
->sock_fd
, F_GETFL
, 0);
630 delay_flag
&= (~O_NONBLOCK
);
632 delay_flag
|= O_NONBLOCK
;
633 fcntl(s
->sock_fd
, F_SETFL
, delay_flag
);
634 #endif /* !PYOS_OS2 */
635 #else /* MS_WINDOWS */
637 ioctlsocket(s
->sock_fd
, FIONBIO
, (u_long
*)&block
);
638 #endif /* MS_WINDOWS */
641 socketioctl(s
->sock_fd
, FIONBIO
, (u_long
*)&block
);
643 #endif /* __BEOS__ */
646 /* Since these don't return anything */
650 /* Do a select() on the socket, if necessary (sock_timeout > 0).
651 The argument writing indicates the direction.
652 This does not raise an exception; we'll let our caller do that
653 after they've reacquired the interpreter lock.
654 Returns 1 on timeout, 0 otherwise. */
656 internal_select(PySocketSockObject
*s
, int writing
)
662 /* Nothing to do unless we're in timeout mode (not non-blocking) */
663 if (s
->sock_timeout
<= 0.0)
666 /* Guard against closed socket */
670 /* Construct the arguments to select */
671 tv
.tv_sec
= (int)s
->sock_timeout
;
672 tv
.tv_usec
= (int)((s
->sock_timeout
- tv
.tv_sec
) * 1e6
);
674 FD_SET(s
->sock_fd
, &fds
);
676 /* See if the socket is ready */
678 n
= select(s
->sock_fd
+1, NULL
, &fds
, NULL
, &tv
);
680 n
= select(s
->sock_fd
+1, &fds
, NULL
, NULL
, &tv
);
686 /* Initialize a new socket object. */
688 static double defaulttimeout
= -1.0; /* Default timeout for new sockets */
691 init_sockobject(PySocketSockObject
*s
,
692 SOCKET_T fd
, int family
, int type
, int proto
)
698 s
->sock_family
= family
;
700 s
->sock_proto
= proto
;
701 s
->sock_timeout
= defaulttimeout
;
703 s
->errorhandler
= &set_error
;
705 if (defaulttimeout
>= 0.0)
706 internal_setblocking(s
, 0);
710 socketioctl(s
->sock_fd
, 0x80046679, (u_long
*)&block
);
715 /* Create a new socket object.
716 This just creates the object and initializes it.
717 If the creation fails, return NULL and set an exception (implicit
720 static PySocketSockObject
*
721 new_sockobject(SOCKET_T fd
, int family
, int type
, int proto
)
723 PySocketSockObject
*s
;
724 s
= (PySocketSockObject
*)
725 PyType_GenericNew(&sock_type
, NULL
, NULL
);
727 init_sockobject(s
, fd
, family
, type
, proto
);
732 /* Lock to allow python interpreter to continue, but only allow one
733 thread to be in gethostbyname or getaddrinfo */
734 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
735 PyThread_type_lock netdb_lock
;
739 /* Convert a string specifying a host name or one of a few symbolic
740 names to a numeric IP address. This usually calls gethostbyname()
741 to do the work; the names "" and "<broadcast>" are special.
742 Return the length (IPv4 should be 4 bytes), or negative if
743 an error occurred; then an exception is raised. */
746 setipaddr(char *name
, struct sockaddr
*addr_ret
, size_t addr_ret_size
, int af
)
748 struct addrinfo hints
, *res
;
753 memset((void *) addr_ret
, '\0', sizeof(*addr_ret
));
754 if (name
[0] == '\0') {
756 memset(&hints
, 0, sizeof(hints
));
757 hints
.ai_family
= af
;
758 hints
.ai_socktype
= SOCK_DGRAM
; /*dummy*/
759 hints
.ai_flags
= AI_PASSIVE
;
760 Py_BEGIN_ALLOW_THREADS
761 ACQUIRE_GETADDRINFO_LOCK
762 error
= getaddrinfo(NULL
, "0", &hints
, &res
);
764 /* We assume that those thread-unsafe getaddrinfo() versions
765 *are* safe regarding their return value, ie. that a
766 subsequent call to getaddrinfo() does not destroy the
767 outcome of the first call. */
768 RELEASE_GETADDRINFO_LOCK
773 switch (res
->ai_family
) {
784 PyErr_SetString(socket_error
,
785 "unsupported address family");
790 PyErr_SetString(socket_error
,
791 "wildcard resolved to multiple address");
794 if (res
->ai_addrlen
< addr_ret_size
)
795 addr_ret_size
= res
->ai_addrlen
;
796 memcpy(addr_ret
, res
->ai_addr
, addr_ret_size
);
800 if (name
[0] == '<' && strcmp(name
, "<broadcast>") == 0) {
801 struct sockaddr_in
*sin
;
802 if (af
!= AF_INET
&& af
!= AF_UNSPEC
) {
803 PyErr_SetString(socket_error
,
804 "address family mismatched");
807 sin
= (struct sockaddr_in
*)addr_ret
;
808 memset((void *) sin
, '\0', sizeof(*sin
));
809 sin
->sin_family
= AF_INET
;
810 #ifdef HAVE_SOCKADDR_SA_LEN
811 sin
->sin_len
= sizeof(*sin
);
813 sin
->sin_addr
.s_addr
= INADDR_BROADCAST
;
814 return sizeof(sin
->sin_addr
);
816 if (sscanf(name
, "%d.%d.%d.%d%c", &d1
, &d2
, &d3
, &d4
, &ch
) == 4 &&
817 0 <= d1
&& d1
<= 255 && 0 <= d2
&& d2
<= 255 &&
818 0 <= d3
&& d3
<= 255 && 0 <= d4
&& d4
<= 255) {
819 struct sockaddr_in
*sin
;
820 sin
= (struct sockaddr_in
*)addr_ret
;
821 sin
->sin_addr
.s_addr
= htonl(
822 ((long) d1
<< 24) | ((long) d2
<< 16) |
823 ((long) d3
<< 8) | ((long) d4
<< 0));
824 sin
->sin_family
= AF_INET
;
825 #ifdef HAVE_SOCKADDR_SA_LEN
826 sin
->sin_len
= sizeof(*sin
);
830 memset(&hints
, 0, sizeof(hints
));
831 hints
.ai_family
= af
;
832 Py_BEGIN_ALLOW_THREADS
833 ACQUIRE_GETADDRINFO_LOCK
834 error
= getaddrinfo(name
, NULL
, &hints
, &res
);
835 #if defined(__digital__) && defined(__unix__)
836 if (error
== EAI_NONAME
&& af
== AF_UNSPEC
) {
837 /* On Tru64 V5.1, numeric-to-addr conversion fails
838 if no address family is given. Assume IPv4 for now.*/
839 hints
.ai_family
= AF_INET
;
840 error
= getaddrinfo(name
, NULL
, &hints
, &res
);
844 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
849 if (res
->ai_addrlen
< addr_ret_size
)
850 addr_ret_size
= res
->ai_addrlen
;
851 memcpy((char *) addr_ret
, res
->ai_addr
, addr_ret_size
);
853 switch (addr_ret
->sa_family
) {
861 PyErr_SetString(socket_error
, "unknown address family");
867 /* Create a string object representing an IP address.
868 This is always a string of the form 'dd.dd.dd.dd' (with variable
872 makeipaddr(struct sockaddr
*addr
, int addrlen
)
874 char buf
[NI_MAXHOST
];
877 error
= getnameinfo(addr
, addrlen
, buf
, sizeof(buf
), NULL
, 0,
883 return PyString_FromString(buf
);
888 /* Convert a string representation of a Bluetooth address into a numeric
889 address. Returns the length (6), or raises an exception and returns -1 if
890 an error occurred. */
893 setbdaddr(char *name
, bdaddr_t
*bdaddr
)
895 unsigned int b0
, b1
, b2
, b3
, b4
, b5
;
899 n
= sscanf(name
, "%X:%X:%X:%X:%X:%X%c",
900 &b5
, &b4
, &b3
, &b2
, &b1
, &b0
, &ch
);
901 if (n
== 6 && (b0
| b1
| b2
| b3
| b4
| b5
) < 256) {
910 PyErr_SetString(socket_error
, "bad bluetooth address");
915 /* Create a string representation of the Bluetooth address. This is always a
916 string of the form 'XX:XX:XX:XX:XX:XX' where XX is a two digit hexadecimal
917 value (zero padded if necessary). */
920 makebdaddr(bdaddr_t
*bdaddr
)
922 char buf
[(6 * 2) + 5 + 1];
924 sprintf(buf
, "%02X:%02X:%02X:%02X:%02X:%02X",
925 bdaddr
->b
[5], bdaddr
->b
[4], bdaddr
->b
[3],
926 bdaddr
->b
[2], bdaddr
->b
[1], bdaddr
->b
[0]);
927 return PyString_FromString(buf
);
932 /* Create an object representing the given socket address,
933 suitable for passing it back to bind(), connect() etc.
934 The family field of the sockaddr structure is inspected
935 to determine what kind of address it really is. */
939 makesockaddr(int sockfd
, struct sockaddr
*addr
, int addrlen
, int proto
)
942 /* No address -- may be recvfrom() from known socket */
948 /* XXX: BeOS version of accept() doesn't set family correctly */
949 addr
->sa_family
= AF_INET
;
952 switch (addr
->sa_family
) {
956 struct sockaddr_in
*a
;
957 PyObject
*addrobj
= makeipaddr(addr
, sizeof(*a
));
958 PyObject
*ret
= NULL
;
960 a
= (struct sockaddr_in
*)addr
;
961 ret
= Py_BuildValue("Oi", addrobj
, ntohs(a
->sin_port
));
970 struct sockaddr_un
*a
= (struct sockaddr_un
*) addr
;
971 return PyString_FromString(a
->sun_path
);
975 #if defined(AF_NETLINK)
978 struct sockaddr_nl
*a
= (struct sockaddr_nl
*) addr
;
979 return Py_BuildValue("II", a
->nl_pid
, a
->nl_groups
);
981 #endif /* AF_NETLINK */
986 struct sockaddr_in6
*a
;
987 PyObject
*addrobj
= makeipaddr(addr
, sizeof(*a
));
988 PyObject
*ret
= NULL
;
990 a
= (struct sockaddr_in6
*)addr
;
991 ret
= Py_BuildValue("Oiii",
1002 #ifdef USE_BLUETOOTH
1008 struct sockaddr_l2
*a
= (struct sockaddr_l2
*) addr
;
1009 PyObject
*addrobj
= makebdaddr(&_BT_L2_MEMB(a
, bdaddr
));
1010 PyObject
*ret
= NULL
;
1012 ret
= Py_BuildValue("Oi",
1014 _BT_L2_MEMB(a
, psm
));
1020 case BTPROTO_RFCOMM
:
1022 struct sockaddr_rc
*a
= (struct sockaddr_rc
*) addr
;
1023 PyObject
*addrobj
= makebdaddr(&_BT_RC_MEMB(a
, bdaddr
));
1024 PyObject
*ret
= NULL
;
1026 ret
= Py_BuildValue("Oi",
1028 _BT_RC_MEMB(a
, channel
));
1034 #if !defined(__FreeBSD__)
1037 struct sockaddr_sco
*a
= (struct sockaddr_sco
*) addr
;
1038 return makebdaddr(&_BT_SCO_MEMB(a
, bdaddr
));
1045 #ifdef HAVE_NETPACKET_PACKET_H
1048 struct sockaddr_ll
*a
= (struct sockaddr_ll
*)addr
;
1051 /* need to look up interface name give index */
1052 if (a
->sll_ifindex
) {
1053 ifr
.ifr_ifindex
= a
->sll_ifindex
;
1054 if (ioctl(sockfd
, SIOCGIFNAME
, &ifr
) == 0)
1055 ifname
= ifr
.ifr_name
;
1057 return Py_BuildValue("shbhs#",
1059 ntohs(a
->sll_protocol
),
1067 /* More cases here... */
1070 /* If we don't know the address family, don't raise an
1071 exception -- return it as a tuple. */
1072 return Py_BuildValue("is#",
1075 sizeof(addr
->sa_data
));
1081 /* Parse a socket address argument according to the socket object's
1082 address family. Return 1 if the address was in the proper format,
1083 0 of not. The address is returned through addr_ret, its length
1087 getsockaddrarg(PySocketSockObject
*s
, PyObject
*args
,
1088 struct sockaddr
**addr_ret
, int *len_ret
)
1090 switch (s
->sock_family
) {
1092 #if defined(AF_UNIX)
1095 struct sockaddr_un
* addr
;
1098 addr
= (struct sockaddr_un
*)&(s
->sock_addr
).un
;
1099 if (!PyArg_Parse(args
, "t#", &path
, &len
))
1101 if (len
> sizeof addr
->sun_path
) {
1102 PyErr_SetString(socket_error
,
1103 "AF_UNIX path too long");
1106 addr
->sun_family
= s
->sock_family
;
1107 memcpy(addr
->sun_path
, path
, len
);
1108 addr
->sun_path
[len
] = 0;
1109 *addr_ret
= (struct sockaddr
*) addr
;
1110 #if defined(PYOS_OS2)
1111 *len_ret
= sizeof(*addr
);
1113 *len_ret
= len
+ sizeof(*addr
) - sizeof(addr
->sun_path
);
1117 #endif /* AF_UNIX */
1119 #if defined(AF_NETLINK)
1122 struct sockaddr_nl
* addr
;
1124 addr
= (struct sockaddr_nl
*)&(s
->sock_addr
).nl
;
1125 if (!PyTuple_Check(args
)) {
1129 "AF_NETLINK address must be tuple, not %.500s",
1130 args
->ob_type
->tp_name
);
1133 if (!PyArg_ParseTuple(args
, "II:getsockaddrarg", &pid
, &groups
))
1135 addr
->nl_family
= AF_NETLINK
;
1137 addr
->nl_groups
= groups
;
1138 *addr_ret
= (struct sockaddr
*) addr
;
1139 *len_ret
= sizeof(*addr
);
1146 struct sockaddr_in
* addr
;
1149 addr
=(struct sockaddr_in
*)&(s
->sock_addr
).in
;
1150 if (!PyTuple_Check(args
)) {
1154 "AF_INET address must be tuple, not %.500s",
1155 args
->ob_type
->tp_name
);
1158 if (!PyArg_ParseTuple(args
, "eti:getsockaddrarg",
1159 "idna", &host
, &port
))
1161 result
= setipaddr(host
, (struct sockaddr
*)addr
,
1162 sizeof(*addr
), AF_INET
);
1166 addr
->sin_family
= AF_INET
;
1167 addr
->sin_port
= htons((short)port
);
1168 *addr_ret
= (struct sockaddr
*) addr
;
1169 *len_ret
= sizeof *addr
;
1176 struct sockaddr_in6
* addr
;
1178 int port
, flowinfo
, scope_id
, result
;
1179 addr
= (struct sockaddr_in6
*)&(s
->sock_addr
).in6
;
1180 flowinfo
= scope_id
= 0;
1181 if (!PyArg_ParseTuple(args
, "eti|ii",
1182 "idna", &host
, &port
, &flowinfo
,
1186 result
= setipaddr(host
, (struct sockaddr
*)addr
,
1187 sizeof(*addr
), AF_INET6
);
1191 addr
->sin6_family
= s
->sock_family
;
1192 addr
->sin6_port
= htons((short)port
);
1193 addr
->sin6_flowinfo
= flowinfo
;
1194 addr
->sin6_scope_id
= scope_id
;
1195 *addr_ret
= (struct sockaddr
*) addr
;
1196 *len_ret
= sizeof *addr
;
1201 #ifdef USE_BLUETOOTH
1204 switch (s
->sock_proto
) {
1207 struct sockaddr_l2
*addr
= (struct sockaddr_l2
*) _BT_SOCKADDR_MEMB(s
, l2
);
1210 _BT_L2_MEMB(addr
, family
) = AF_BLUETOOTH
;
1211 if (!PyArg_ParseTuple(args
, "si", &straddr
,
1212 &_BT_L2_MEMB(addr
, psm
))) {
1213 PyErr_SetString(socket_error
, "getsockaddrarg: "
1217 if (setbdaddr(straddr
, &_BT_L2_MEMB(addr
, bdaddr
)) < 0)
1220 *addr_ret
= (struct sockaddr
*) addr
;
1221 *len_ret
= sizeof *addr
;
1224 case BTPROTO_RFCOMM
:
1226 struct sockaddr_rc
*addr
= (struct sockaddr_rc
*) _BT_SOCKADDR_MEMB(s
, rc
);
1229 _BT_RC_MEMB(addr
, family
) = AF_BLUETOOTH
;
1230 if (!PyArg_ParseTuple(args
, "si", &straddr
,
1231 &_BT_RC_MEMB(addr
, channel
))) {
1232 PyErr_SetString(socket_error
, "getsockaddrarg: "
1236 if (setbdaddr(straddr
, &_BT_RC_MEMB(addr
, bdaddr
)) < 0)
1239 *addr_ret
= (struct sockaddr
*) addr
;
1240 *len_ret
= sizeof *addr
;
1243 #if !defined(__FreeBSD__)
1246 struct sockaddr_sco
*addr
= (struct sockaddr_sco
*) _BT_SOCKADDR_MEMB(s
, sco
);
1249 _BT_SCO_MEMB(addr
, family
) = AF_BLUETOOTH
;
1250 straddr
= PyString_AsString(args
);
1251 if (straddr
== NULL
) {
1252 PyErr_SetString(socket_error
, "getsockaddrarg: "
1256 if (setbdaddr(straddr
, &_BT_SCO_MEMB(addr
, bdaddr
)) < 0)
1259 *addr_ret
= (struct sockaddr
*) addr
;
1260 *len_ret
= sizeof *addr
;
1265 PyErr_SetString(socket_error
, "getsockaddrarg: unknown Bluetooth protocol");
1271 #ifdef HAVE_NETPACKET_PACKET_H
1274 struct sockaddr_ll
* addr
;
1276 char *interfaceName
;
1281 unsigned int halen
= 0;
1283 if (!PyArg_ParseTuple(args
, "si|iis#", &interfaceName
,
1284 &protoNumber
, &pkttype
, &hatype
,
1287 strncpy(ifr
.ifr_name
, interfaceName
, sizeof(ifr
.ifr_name
));
1288 ifr
.ifr_name
[(sizeof(ifr
.ifr_name
))-1] = '\0';
1289 if (ioctl(s
->sock_fd
, SIOCGIFINDEX
, &ifr
) < 0) {
1293 addr
= &(s
->sock_addr
.ll
);
1294 addr
->sll_family
= AF_PACKET
;
1295 addr
->sll_protocol
= htons((short)protoNumber
);
1296 addr
->sll_ifindex
= ifr
.ifr_ifindex
;
1297 addr
->sll_pkttype
= pkttype
;
1298 addr
->sll_hatype
= hatype
;
1300 PyErr_SetString(PyExc_ValueError
,
1301 "Hardware address must be 8 bytes or less");
1305 memcpy(&addr
->sll_addr
, haddr
, halen
);
1307 addr
->sll_halen
= halen
;
1308 *addr_ret
= (struct sockaddr
*) addr
;
1309 *len_ret
= sizeof *addr
;
1314 /* More cases here... */
1317 PyErr_SetString(socket_error
, "getsockaddrarg: bad family");
1324 /* Get the address length according to the socket object's address family.
1325 Return 1 if the family is known, 0 otherwise. The length is returned
1329 getsockaddrlen(PySocketSockObject
*s
, socklen_t
*len_ret
)
1331 switch (s
->sock_family
) {
1333 #if defined(AF_UNIX)
1336 *len_ret
= sizeof (struct sockaddr_un
);
1339 #endif /* AF_UNIX */
1340 #if defined(AF_NETLINK)
1343 *len_ret
= sizeof (struct sockaddr_nl
);
1350 *len_ret
= sizeof (struct sockaddr_in
);
1357 *len_ret
= sizeof (struct sockaddr_in6
);
1362 #ifdef USE_BLUETOOTH
1365 switch(s
->sock_proto
)
1369 *len_ret
= sizeof (struct sockaddr_l2
);
1371 case BTPROTO_RFCOMM
:
1372 *len_ret
= sizeof (struct sockaddr_rc
);
1374 #if !defined(__FreeBSD__)
1376 *len_ret
= sizeof (struct sockaddr_sco
);
1380 PyErr_SetString(socket_error
, "getsockaddrlen: "
1381 "unknown BT protocol");
1388 #ifdef HAVE_NETPACKET_PACKET_H
1391 *len_ret
= sizeof (struct sockaddr_ll
);
1396 /* More cases here... */
1399 PyErr_SetString(socket_error
, "getsockaddrlen: bad family");
1406 /* s.accept() method */
1409 sock_accept(PySocketSockObject
*s
)
1411 sock_addr_t addrbuf
;
1414 PyObject
*sock
= NULL
;
1415 PyObject
*addr
= NULL
;
1416 PyObject
*res
= NULL
;
1419 if (!getsockaddrlen(s
, &addrlen
))
1421 memset(&addrbuf
, 0, addrlen
);
1424 newfd
= INVALID_SOCKET
;
1429 if (!IS_SELECTABLE(s
))
1430 return select_error();
1432 Py_BEGIN_ALLOW_THREADS
1433 timeout
= internal_select(s
, 0);
1435 newfd
= accept(s
->sock_fd
, (struct sockaddr
*) &addrbuf
,
1437 Py_END_ALLOW_THREADS
1440 PyErr_SetString(socket_timeout
, "timed out");
1445 if (newfd
== INVALID_SOCKET
)
1449 return s
->errorhandler();
1451 /* Create the new object with unspecified family,
1452 to avoid calls to bind() etc. on it. */
1453 sock
= (PyObject
*) new_sockobject(newfd
,
1462 addr
= makesockaddr(s
->sock_fd
, (struct sockaddr
*) &addrbuf
,
1463 addrlen
, s
->sock_proto
);
1467 res
= PyTuple_Pack(2, sock
, addr
);
1475 PyDoc_STRVAR(accept_doc
,
1476 "accept() -> (socket object, address info)\n\
1478 Wait for an incoming connection. Return a new socket representing the\n\
1479 connection, and the address of the client. For IP sockets, the address\n\
1480 info is a pair (hostaddr, port).");
1482 /* s.setblocking(flag) method. Argument:
1483 False -- non-blocking mode; same as settimeout(0)
1484 True -- blocking mode; same as settimeout(None)
1488 sock_setblocking(PySocketSockObject
*s
, PyObject
*arg
)
1492 block
= PyInt_AsLong(arg
);
1493 if (block
== -1 && PyErr_Occurred())
1496 s
->sock_timeout
= block
? -1.0 : 0.0;
1497 internal_setblocking(s
, block
);
1503 PyDoc_STRVAR(setblocking_doc
,
1504 "setblocking(flag)\n\
1506 Set the socket to blocking (flag is true) or non-blocking (false).\n\
1507 setblocking(True) is equivalent to settimeout(None);\n\
1508 setblocking(False) is equivalent to settimeout(0.0).");
1510 /* s.settimeout(timeout) method. Argument:
1511 None -- no timeout, blocking mode; same as setblocking(True)
1512 0.0 -- non-blocking mode; same as setblocking(False)
1513 > 0 -- timeout mode; operations time out after timeout seconds
1514 < 0 -- illegal; raises an exception
1517 sock_settimeout(PySocketSockObject
*s
, PyObject
*arg
)
1524 timeout
= PyFloat_AsDouble(arg
);
1525 if (timeout
< 0.0) {
1526 if (!PyErr_Occurred())
1527 PyErr_SetString(PyExc_ValueError
,
1528 "Timeout value out of range");
1533 s
->sock_timeout
= timeout
;
1534 internal_setblocking(s
, timeout
< 0.0);
1540 PyDoc_STRVAR(settimeout_doc
,
1541 "settimeout(timeout)\n\
1543 Set a timeout on socket operations. 'timeout' can be a float,\n\
1544 giving in seconds, or None. Setting a timeout of None disables\n\
1545 the timeout feature and is equivalent to setblocking(1).\n\
1546 Setting a timeout of zero is the same as setblocking(0).");
1548 /* s.gettimeout() method.
1549 Returns the timeout associated with a socket. */
1551 sock_gettimeout(PySocketSockObject
*s
)
1553 if (s
->sock_timeout
< 0.0) {
1558 return PyFloat_FromDouble(s
->sock_timeout
);
1561 PyDoc_STRVAR(gettimeout_doc
,
1562 "gettimeout() -> timeout\n\
1564 Returns the timeout in floating seconds associated with socket \n\
1565 operations. A timeout of None indicates that timeouts on socket \n\
1566 operations are disabled.");
1569 /* s.sleeptaskw(1 | 0) method */
1572 sock_sleeptaskw(PySocketSockObject
*s
,PyObject
*arg
)
1575 block
= PyInt_AsLong(arg
);
1576 if (block
== -1 && PyErr_Occurred())
1578 Py_BEGIN_ALLOW_THREADS
1579 socketioctl(s
->sock_fd
, 0x80046679, (u_long
*)&block
);
1580 Py_END_ALLOW_THREADS
1585 PyDoc_STRVAR(sleeptaskw_doc
,
1586 "sleeptaskw(flag)\n\
1588 Allow sleeps in taskwindows.");
1592 /* s.setsockopt() method.
1593 With an integer third argument, sets an integer option.
1594 With a string third argument, sets an option from a buffer;
1595 use optional built-in module 'struct' to encode the string. */
1598 sock_setsockopt(PySocketSockObject
*s
, PyObject
*args
)
1607 if (PyArg_ParseTuple(args
, "iii:setsockopt",
1608 &level
, &optname
, &flag
)) {
1609 buf
= (char *) &flag
;
1610 buflen
= sizeof flag
;
1614 if (!PyArg_ParseTuple(args
, "iis#:setsockopt",
1615 &level
, &optname
, &buf
, &buflen
))
1618 res
= setsockopt(s
->sock_fd
, level
, optname
, (void *)buf
, buflen
);
1620 return s
->errorhandler();
1625 PyDoc_STRVAR(setsockopt_doc
,
1626 "setsockopt(level, option, value)\n\
1628 Set a socket option. See the Unix manual for level and option.\n\
1629 The value argument can either be an integer or a string.");
1632 /* s.getsockopt() method.
1633 With two arguments, retrieves an integer option.
1634 With a third integer argument, retrieves a string buffer of that size;
1635 use optional built-in module 'struct' to decode the string. */
1638 sock_getsockopt(PySocketSockObject
*s
, PyObject
*args
)
1644 socklen_t buflen
= 0;
1647 /* We have incomplete socket support. */
1648 PyErr_SetString(socket_error
, "getsockopt not supported");
1652 if (!PyArg_ParseTuple(args
, "ii|i:getsockopt",
1653 &level
, &optname
, &buflen
))
1658 socklen_t flagsize
= sizeof flag
;
1659 res
= getsockopt(s
->sock_fd
, level
, optname
,
1660 (void *)&flag
, &flagsize
);
1662 return s
->errorhandler();
1663 return PyInt_FromLong(flag
);
1666 if (buflen
> 1024) {
1668 if (buflen
<= 0 || buflen
> 1024) {
1670 PyErr_SetString(socket_error
,
1671 "getsockopt buflen out of range");
1674 buf
= PyString_FromStringAndSize((char *)NULL
, buflen
);
1677 res
= getsockopt(s
->sock_fd
, level
, optname
,
1678 (void *)PyString_AS_STRING(buf
), &buflen
);
1681 return s
->errorhandler();
1683 _PyString_Resize(&buf
, buflen
);
1685 #endif /* __BEOS__ */
1688 PyDoc_STRVAR(getsockopt_doc
,
1689 "getsockopt(level, option[, buffersize]) -> value\n\
1691 Get a socket option. See the Unix manual for level and option.\n\
1692 If a nonzero buffersize argument is given, the return value is a\n\
1693 string of that length; otherwise it is an integer.");
1696 /* s.bind(sockaddr) method */
1699 sock_bind(PySocketSockObject
*s
, PyObject
*addro
)
1701 struct sockaddr
*addr
;
1705 if (!getsockaddrarg(s
, addro
, &addr
, &addrlen
))
1707 Py_BEGIN_ALLOW_THREADS
1708 res
= bind(s
->sock_fd
, addr
, addrlen
);
1709 Py_END_ALLOW_THREADS
1711 return s
->errorhandler();
1716 PyDoc_STRVAR(bind_doc
,
1719 Bind the socket to a local address. For IP sockets, the address is a\n\
1720 pair (host, port); the host must refer to the local host. For raw packet\n\
1721 sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");
1724 /* s.close() method.
1725 Set the file descriptor to -1 so operations tried subsequently
1726 will surely fail. */
1729 sock_close(PySocketSockObject
*s
)
1733 if ((fd
= s
->sock_fd
) != -1) {
1735 Py_BEGIN_ALLOW_THREADS
1736 (void) SOCKETCLOSE(fd
);
1737 Py_END_ALLOW_THREADS
1743 PyDoc_STRVAR(close_doc
,
1746 Close the socket. It cannot be used after this call.");
1749 internal_connect(PySocketSockObject
*s
, struct sockaddr
*addr
, int addrlen
,
1755 res
= connect(s
->sock_fd
, addr
, addrlen
);
1759 if (s
->sock_timeout
> 0.0) {
1760 if (res
< 0 && WSAGetLastError() == WSAEWOULDBLOCK
&&
1762 /* This is a mess. Best solution: trust select */
1766 tv
.tv_sec
= (int)s
->sock_timeout
;
1767 tv
.tv_usec
= (int)((s
->sock_timeout
- tv
.tv_sec
) * 1e6
);
1769 FD_SET(s
->sock_fd
, &fds
);
1771 FD_SET(s
->sock_fd
, &fds_exc
);
1772 res
= select(s
->sock_fd
+1, NULL
, &fds
, &fds_exc
, &tv
);
1774 res
= WSAEWOULDBLOCK
;
1776 } else if (res
> 0) {
1777 if (FD_ISSET(s
->sock_fd
, &fds
))
1778 /* The socket is in the writeable set - this
1782 /* As per MS docs, we need to call getsockopt()
1783 to get the underlying error */
1784 int res_size
= sizeof res
;
1785 /* It must be in the exception set */
1786 assert(FD_ISSET(s
->sock_fd
, &fds_exc
));
1787 if (0 == getsockopt(s
->sock_fd
, SOL_SOCKET
, SO_ERROR
,
1788 (char *)&res
, &res_size
))
1789 /* getsockopt also clears WSAGetLastError,
1790 so reset it back. */
1791 WSASetLastError(res
);
1793 res
= WSAGetLastError();
1796 /* else if (res < 0) an error occurred */
1801 res
= WSAGetLastError();
1805 if (s
->sock_timeout
> 0.0) {
1806 if (res
< 0 && errno
== EINPROGRESS
&& IS_SELECTABLE(s
)) {
1807 timeout
= internal_select(s
, 1);
1808 res
= connect(s
->sock_fd
, addr
, addrlen
);
1809 if (res
< 0 && errno
== EISCONN
)
1818 *timeoutp
= timeout
;
1823 /* s.connect(sockaddr) method */
1826 sock_connect(PySocketSockObject
*s
, PyObject
*addro
)
1828 struct sockaddr
*addr
;
1833 if (!getsockaddrarg(s
, addro
, &addr
, &addrlen
))
1836 Py_BEGIN_ALLOW_THREADS
1837 res
= internal_connect(s
, addr
, addrlen
, &timeout
);
1838 Py_END_ALLOW_THREADS
1841 PyErr_SetString(socket_timeout
, "timed out");
1845 return s
->errorhandler();
1850 PyDoc_STRVAR(connect_doc
,
1851 "connect(address)\n\
1853 Connect the socket to a remote address. For IP sockets, the address\n\
1854 is a pair (host, port).");
1857 /* s.connect_ex(sockaddr) method */
1860 sock_connect_ex(PySocketSockObject
*s
, PyObject
*addro
)
1862 struct sockaddr
*addr
;
1867 if (!getsockaddrarg(s
, addro
, &addr
, &addrlen
))
1870 Py_BEGIN_ALLOW_THREADS
1871 res
= internal_connect(s
, addr
, addrlen
, &timeout
);
1872 Py_END_ALLOW_THREADS
1874 return PyInt_FromLong((long) res
);
1877 PyDoc_STRVAR(connect_ex_doc
,
1878 "connect_ex(address) -> errno\n\
1880 This is like connect(address), but returns an error code (the errno value)\n\
1881 instead of raising an exception when an error occurs.");
1884 /* s.fileno() method */
1887 sock_fileno(PySocketSockObject
*s
)
1889 #if SIZEOF_SOCKET_T <= SIZEOF_LONG
1890 return PyInt_FromLong((long) s
->sock_fd
);
1892 return PyLong_FromLongLong((PY_LONG_LONG
)s
->sock_fd
);
1896 PyDoc_STRVAR(fileno_doc
,
1897 "fileno() -> integer\n\
1899 Return the integer file descriptor of the socket.");
1903 /* s.dup() method */
1906 sock_dup(PySocketSockObject
*s
)
1911 newfd
= dup(s
->sock_fd
);
1913 return s
->errorhandler();
1914 sock
= (PyObject
*) new_sockobject(newfd
,
1923 PyDoc_STRVAR(dup_doc
,
1924 "dup() -> socket object\n\
1926 Return a new socket object connected to the same system resource.");
1931 /* s.getsockname() method */
1934 sock_getsockname(PySocketSockObject
*s
)
1936 sock_addr_t addrbuf
;
1940 if (!getsockaddrlen(s
, &addrlen
))
1942 memset(&addrbuf
, 0, addrlen
);
1943 Py_BEGIN_ALLOW_THREADS
1944 res
= getsockname(s
->sock_fd
, (struct sockaddr
*) &addrbuf
, &addrlen
);
1945 Py_END_ALLOW_THREADS
1947 return s
->errorhandler();
1948 return makesockaddr(s
->sock_fd
, (struct sockaddr
*) &addrbuf
, addrlen
,
1952 PyDoc_STRVAR(getsockname_doc
,
1953 "getsockname() -> address info\n\
1955 Return the address of the local endpoint. For IP sockets, the address\n\
1956 info is a pair (hostaddr, port).");
1959 #ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
1960 /* s.getpeername() method */
1963 sock_getpeername(PySocketSockObject
*s
)
1965 sock_addr_t addrbuf
;
1969 if (!getsockaddrlen(s
, &addrlen
))
1971 memset(&addrbuf
, 0, addrlen
);
1972 Py_BEGIN_ALLOW_THREADS
1973 res
= getpeername(s
->sock_fd
, (struct sockaddr
*) &addrbuf
, &addrlen
);
1974 Py_END_ALLOW_THREADS
1976 return s
->errorhandler();
1977 return makesockaddr(s
->sock_fd
, (struct sockaddr
*) &addrbuf
, addrlen
,
1981 PyDoc_STRVAR(getpeername_doc
,
1982 "getpeername() -> address info\n\
1984 Return the address of the remote endpoint. For IP sockets, the address\n\
1985 info is a pair (hostaddr, port).");
1987 #endif /* HAVE_GETPEERNAME */
1990 /* s.listen(n) method */
1993 sock_listen(PySocketSockObject
*s
, PyObject
*arg
)
1998 backlog
= PyInt_AsLong(arg
);
1999 if (backlog
== -1 && PyErr_Occurred())
2001 Py_BEGIN_ALLOW_THREADS
2004 res
= listen(s
->sock_fd
, backlog
);
2005 Py_END_ALLOW_THREADS
2007 return s
->errorhandler();
2012 PyDoc_STRVAR(listen_doc
,
2015 Enable a server to accept connections. The backlog argument must be at\n\
2016 least 1; it specifies the number of unaccepted connection that the system\n\
2017 will allow before refusing new connections.");
2021 /* s.makefile(mode) method.
2022 Create a new open file object referring to a dupped version of
2023 the socket's file descriptor. (The dup() call is necessary so
2024 that the open file and socket objects may be closed independent
2026 The mode argument specifies 'r' or 'w' passed to fdopen(). */
2029 sock_makefile(PySocketSockObject
*s
, PyObject
*args
)
2031 extern int fclose(FILE *);
2046 if (!PyArg_ParseTuple(args
, "|si:makefile", &mode
, &bufsize
))
2049 if (strcmp(mode
,"rb") == 0) {
2053 if (strcmp(mode
,"wb") == 0) {
2059 if (((fd
= _open_osfhandle(s
->sock_fd
, _O_BINARY
)) < 0) ||
2060 ((fd
= dup(fd
)) < 0) || ((fp
= fdopen(fd
, mode
)) == NULL
))
2062 if ((fd
= dup(s
->sock_fd
)) < 0 || (fp
= fdopen(fd
, mode
)) == NULL
)
2067 return s
->errorhandler();
2069 f
= PyFile_FromFile(fp
, "<socket>", mode
, fclose
);
2071 PyFile_SetBufSize(f
, bufsize
);
2075 PyDoc_STRVAR(makefile_doc
,
2076 "makefile([mode[, buffersize]]) -> file object\n\
2078 Return a regular file object corresponding to the socket.\n\
2079 The mode and buffersize arguments are as for the built-in open() function.");
2084 /* s.recv(nbytes [,flags]) method */
2087 sock_recv(PySocketSockObject
*s
, PyObject
*args
)
2089 int len
, n
= 0, flags
= 0, timeout
;
2096 if (!PyArg_ParseTuple(args
, "i|i:recv", &len
, &flags
))
2100 PyErr_SetString(PyExc_ValueError
,
2101 "negative buffersize in recv");
2105 buf
= PyString_FromStringAndSize((char *) 0, len
);
2109 if (!IS_SELECTABLE(s
))
2110 return select_error();
2113 Py_BEGIN_ALLOW_THREADS
2114 timeout
= internal_select(s
, 0);
2116 n
= recv(s
->sock_fd
, PyString_AS_STRING(buf
), len
, flags
);
2117 Py_END_ALLOW_THREADS
2121 PyErr_SetString(socket_timeout
, "timed out");
2126 return s
->errorhandler();
2129 _PyString_Resize(&buf
, n
);
2131 read_buf
= PyString_AsString(buf
);
2133 while (read_length
!= 0) {
2134 unsigned int segment
;
2136 segment
= read_length
/SEGMENT_SIZE
;
2138 segment
= SEGMENT_SIZE
;
2141 segment
= read_length
;
2144 Py_BEGIN_ALLOW_THREADS
2145 timeout
= internal_select(s
, 0);
2147 n
= recv(s
->sock_fd
, read_buf
, segment
, flags
);
2148 Py_END_ALLOW_THREADS
2152 PyErr_SetString(socket_timeout
, "timed out");
2157 return s
->errorhandler();
2159 if (n
!= read_length
) {
2164 read_length
-= segment
;
2165 read_buf
+= segment
;
2167 if (_PyString_Resize(&buf
, (read_buf
- PyString_AsString(buf
))) < 0)
2175 PyDoc_STRVAR(recv_doc
,
2176 "recv(buffersize[, flags]) -> data\n\
2178 Receive up to buffersize bytes from the socket. For the optional flags\n\
2179 argument, see the Unix manual. When no data is available, block until\n\
2180 at least one byte is available or until the remote end is closed. When\n\
2181 the remote end is closed and all data is read, return the empty string.");
2184 /* s.recvfrom(nbytes [,flags]) method */
2187 sock_recvfrom(PySocketSockObject
*s
, PyObject
*args
)
2189 sock_addr_t addrbuf
;
2190 PyObject
*buf
= NULL
;
2191 PyObject
*addr
= NULL
;
2192 PyObject
*ret
= NULL
;
2193 int len
, n
= 0, flags
= 0, timeout
;
2196 if (!PyArg_ParseTuple(args
, "i|i:recvfrom", &len
, &flags
))
2199 if (!getsockaddrlen(s
, &addrlen
))
2201 buf
= PyString_FromStringAndSize((char *) 0, len
);
2205 if (!IS_SELECTABLE(s
))
2206 return select_error();
2208 Py_BEGIN_ALLOW_THREADS
2209 memset(&addrbuf
, 0, addrlen
);
2210 timeout
= internal_select(s
, 0);
2212 n
= recvfrom(s
->sock_fd
, PyString_AS_STRING(buf
), len
, flags
,
2214 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
2215 (struct sockaddr
*) &addrbuf
, &addrlen
2217 (void *) &addrbuf
, &addrlen
2220 (struct sockaddr
*) &addrbuf
, &addrlen
2223 Py_END_ALLOW_THREADS
2227 PyErr_SetString(socket_timeout
, "timed out");
2232 return s
->errorhandler();
2235 if (n
!= len
&& _PyString_Resize(&buf
, n
) < 0)
2238 if (!(addr
= makesockaddr(s
->sock_fd
, (struct sockaddr
*) &addrbuf
,
2239 addrlen
, s
->sock_proto
)))
2242 ret
= PyTuple_Pack(2, buf
, addr
);
2250 PyDoc_STRVAR(recvfrom_doc
,
2251 "recvfrom(buffersize[, flags]) -> (data, address info)\n\
2253 Like recv(buffersize, flags) but also return the sender's address info.");
2255 /* s.send(data [,flags]) method */
2258 sock_send(PySocketSockObject
*s
, PyObject
*args
)
2261 int len
, n
= 0, flags
= 0, timeout
;
2266 if (!PyArg_ParseTuple(args
, "s#|i:send", &buf
, &len
, &flags
))
2269 if (!IS_SELECTABLE(s
))
2270 return select_error();
2273 Py_BEGIN_ALLOW_THREADS
2274 timeout
= internal_select(s
, 1);
2276 n
= send(s
->sock_fd
, buf
, len
, flags
);
2277 Py_END_ALLOW_THREADS
2280 PyErr_SetString(socket_timeout
, "timed out");
2284 return s
->errorhandler();
2286 /* Divide packet into smaller segments for */
2287 /* TCP/IP Services for OpenVMS */
2289 while (send_length
!= 0) {
2290 unsigned int segment
;
2292 segment
= send_length
/ SEGMENT_SIZE
;
2294 segment
= SEGMENT_SIZE
;
2297 segment
= send_length
;
2299 Py_BEGIN_ALLOW_THREADS
2300 timeout
= internal_select(s
, 1);
2302 n
= send(s
->sock_fd
, buf
, segment
, flags
);
2303 Py_END_ALLOW_THREADS
2305 PyErr_SetString(socket_timeout
, "timed out");
2309 return s
->errorhandler();
2311 send_length
-= segment
;
2315 return PyInt_FromLong((long)n
);
2318 PyDoc_STRVAR(send_doc
,
2319 "send(data[, flags]) -> count\n\
2321 Send a data string to the socket. For the optional flags\n\
2322 argument, see the Unix manual. Return the number of bytes\n\
2323 sent; this may be less than len(data) if the network is busy.");
2326 /* s.sendall(data [,flags]) method */
2329 sock_sendall(PySocketSockObject
*s
, PyObject
*args
)
2332 int len
, n
= 0, flags
= 0, timeout
;
2334 if (!PyArg_ParseTuple(args
, "s#|i:sendall", &buf
, &len
, &flags
))
2337 if (!IS_SELECTABLE(s
))
2338 return select_error();
2340 Py_BEGIN_ALLOW_THREADS
2342 timeout
= internal_select(s
, 1);
2345 n
= send(s
->sock_fd
, buf
, len
, flags
);
2351 Py_END_ALLOW_THREADS
2354 PyErr_SetString(socket_timeout
, "timed out");
2358 return s
->errorhandler();
2364 PyDoc_STRVAR(sendall_doc
,
2365 "sendall(data[, flags])\n\
2367 Send a data string to the socket. For the optional flags\n\
2368 argument, see the Unix manual. This calls send() repeatedly\n\
2369 until all data is sent. If an error occurs, it's impossible\n\
2370 to tell how much data has been sent.");
2373 /* s.sendto(data, [flags,] sockaddr) method */
2376 sock_sendto(PySocketSockObject
*s
, PyObject
*args
)
2380 struct sockaddr
*addr
;
2381 int addrlen
, len
, n
= 0, flags
, timeout
;
2384 if (!PyArg_ParseTuple(args
, "s#O:sendto", &buf
, &len
, &addro
)) {
2386 if (!PyArg_ParseTuple(args
, "s#iO:sendto",
2387 &buf
, &len
, &flags
, &addro
))
2391 if (!getsockaddrarg(s
, addro
, &addr
, &addrlen
))
2394 if (!IS_SELECTABLE(s
))
2395 return select_error();
2397 Py_BEGIN_ALLOW_THREADS
2398 timeout
= internal_select(s
, 1);
2400 n
= sendto(s
->sock_fd
, buf
, len
, flags
, addr
, addrlen
);
2401 Py_END_ALLOW_THREADS
2404 PyErr_SetString(socket_timeout
, "timed out");
2408 return s
->errorhandler();
2409 return PyInt_FromLong((long)n
);
2412 PyDoc_STRVAR(sendto_doc
,
2413 "sendto(data[, flags], address) -> count\n\
2415 Like send(data, flags) but allows specifying the destination address.\n\
2416 For IP sockets, the address is a pair (hostaddr, port).");
2419 /* s.shutdown(how) method */
2422 sock_shutdown(PySocketSockObject
*s
, PyObject
*arg
)
2427 how
= PyInt_AsLong(arg
);
2428 if (how
== -1 && PyErr_Occurred())
2430 Py_BEGIN_ALLOW_THREADS
2431 res
= shutdown(s
->sock_fd
, how
);
2432 Py_END_ALLOW_THREADS
2434 return s
->errorhandler();
2439 PyDoc_STRVAR(shutdown_doc
,
2442 Shut down the reading side of the socket (flag == SHUT_RD), the writing side\n\
2443 of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).");
2446 /* List of methods for socket objects */
2448 static PyMethodDef sock_methods
[] = {
2449 {"accept", (PyCFunction
)sock_accept
, METH_NOARGS
,
2451 {"bind", (PyCFunction
)sock_bind
, METH_O
,
2453 {"close", (PyCFunction
)sock_close
, METH_NOARGS
,
2455 {"connect", (PyCFunction
)sock_connect
, METH_O
,
2457 {"connect_ex", (PyCFunction
)sock_connect_ex
, METH_O
,
2460 {"dup", (PyCFunction
)sock_dup
, METH_NOARGS
,
2463 {"fileno", (PyCFunction
)sock_fileno
, METH_NOARGS
,
2465 #ifdef HAVE_GETPEERNAME
2466 {"getpeername", (PyCFunction
)sock_getpeername
,
2467 METH_NOARGS
, getpeername_doc
},
2469 {"getsockname", (PyCFunction
)sock_getsockname
,
2470 METH_NOARGS
, getsockname_doc
},
2471 {"getsockopt", (PyCFunction
)sock_getsockopt
, METH_VARARGS
,
2473 {"listen", (PyCFunction
)sock_listen
, METH_O
,
2476 {"makefile", (PyCFunction
)sock_makefile
, METH_VARARGS
,
2479 {"recv", (PyCFunction
)sock_recv
, METH_VARARGS
,
2481 {"recvfrom", (PyCFunction
)sock_recvfrom
, METH_VARARGS
,
2483 {"send", (PyCFunction
)sock_send
, METH_VARARGS
,
2485 {"sendall", (PyCFunction
)sock_sendall
, METH_VARARGS
,
2487 {"sendto", (PyCFunction
)sock_sendto
, METH_VARARGS
,
2489 {"setblocking", (PyCFunction
)sock_setblocking
, METH_O
,
2491 {"settimeout", (PyCFunction
)sock_settimeout
, METH_O
,
2493 {"gettimeout", (PyCFunction
)sock_gettimeout
, METH_NOARGS
,
2495 {"setsockopt", (PyCFunction
)sock_setsockopt
, METH_VARARGS
,
2497 {"shutdown", (PyCFunction
)sock_shutdown
, METH_O
,
2500 {"sleeptaskw", (PyCFunction
)sock_sleeptaskw
, METH_O
,
2503 {NULL
, NULL
} /* sentinel */
2506 /* SockObject members */
2507 static PyMemberDef sock_memberlist
[] = {
2508 {"family", T_INT
, offsetof(PySocketSockObject
, sock_family
), READONLY
, "the socket family"},
2509 {"type", T_INT
, offsetof(PySocketSockObject
, sock_type
), READONLY
, "the socket type"},
2510 {"proto", T_INT
, offsetof(PySocketSockObject
, sock_proto
), READONLY
, "the socket protocol"},
2511 {"timeout", T_DOUBLE
, offsetof(PySocketSockObject
, sock_timeout
), READONLY
, "the socket timeout"},
2515 /* Deallocate a socket object in response to the last Py_DECREF().
2516 First close the file description. */
2519 sock_dealloc(PySocketSockObject
*s
)
2521 if (s
->sock_fd
!= -1)
2522 (void) SOCKETCLOSE(s
->sock_fd
);
2523 s
->ob_type
->tp_free((PyObject
*)s
);
2528 sock_repr(PySocketSockObject
*s
)
2531 #if SIZEOF_SOCKET_T > SIZEOF_LONG
2532 if (s
->sock_fd
> LONG_MAX
) {
2533 /* this can occur on Win64, and actually there is a special
2534 ugly printf formatter for decimal pointer length integer
2535 printing, only bother if necessary*/
2536 PyErr_SetString(PyExc_OverflowError
,
2537 "no printf formatter to display "
2538 "the socket descriptor in decimal");
2544 "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
2545 (long)s
->sock_fd
, s
->sock_family
,
2548 return PyString_FromString(buf
);
2552 /* Create a new, uninitialized socket object. */
2555 sock_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
2559 new = type
->tp_alloc(type
, 0);
2561 ((PySocketSockObject
*)new)->sock_fd
= -1;
2562 ((PySocketSockObject
*)new)->sock_timeout
= -1.0;
2563 ((PySocketSockObject
*)new)->errorhandler
= &set_error
;
2569 /* Initialize a new socket object. */
2573 sock_initobj(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
2575 PySocketSockObject
*s
= (PySocketSockObject
*)self
;
2577 int family
= AF_INET
, type
= SOCK_STREAM
, proto
= 0;
2578 static char *keywords
[] = {"family", "type", "proto", 0};
2580 if (!PyArg_ParseTupleAndKeywords(args
, kwds
,
2581 "|iii:socket", keywords
,
2582 &family
, &type
, &proto
))
2585 Py_BEGIN_ALLOW_THREADS
2586 fd
= socket(family
, type
, proto
);
2587 Py_END_ALLOW_THREADS
2590 if (fd
== INVALID_SOCKET
)
2598 init_sockobject(s
, fd
, family
, type
, proto
);
2605 /* Type object for socket objects. */
2607 static PyTypeObject sock_type
= {
2608 PyObject_HEAD_INIT(0) /* Must fill in type value later */
2610 "_socket.socket", /* tp_name */
2611 sizeof(PySocketSockObject
), /* tp_basicsize */
2612 0, /* tp_itemsize */
2613 (destructor
)sock_dealloc
, /* tp_dealloc */
2618 (reprfunc
)sock_repr
, /* tp_repr */
2619 0, /* tp_as_number */
2620 0, /* tp_as_sequence */
2621 0, /* tp_as_mapping */
2625 PyObject_GenericGetAttr
, /* tp_getattro */
2626 0, /* tp_setattro */
2627 0, /* tp_as_buffer */
2628 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
2629 sock_doc
, /* tp_doc */
2630 0, /* tp_traverse */
2632 0, /* tp_richcompare */
2633 0, /* tp_weaklistoffset */
2635 0, /* tp_iternext */
2636 sock_methods
, /* tp_methods */
2637 sock_memberlist
, /* tp_members */
2641 0, /* tp_descr_get */
2642 0, /* tp_descr_set */
2643 0, /* tp_dictoffset */
2644 sock_initobj
, /* tp_init */
2645 PyType_GenericAlloc
, /* tp_alloc */
2646 sock_new
, /* tp_new */
2647 PyObject_Del
, /* tp_free */
2651 /* Python interface to gethostname(). */
2655 socket_gethostname(PyObject
*self
, PyObject
*args
)
2659 if (!PyArg_ParseTuple(args
, ":gethostname"))
2661 Py_BEGIN_ALLOW_THREADS
2662 res
= gethostname(buf
, (int) sizeof buf
- 1);
2663 Py_END_ALLOW_THREADS
2666 buf
[sizeof buf
- 1] = '\0';
2667 return PyString_FromString(buf
);
2670 PyDoc_STRVAR(gethostname_doc
,
2671 "gethostname() -> string\n\
2673 Return the current host name.");
2676 /* Python interface to gethostbyname(name). */
2680 socket_gethostbyname(PyObject
*self
, PyObject
*args
)
2683 sock_addr_t addrbuf
;
2685 if (!PyArg_ParseTuple(args
, "s:gethostbyname", &name
))
2687 if (setipaddr(name
, (struct sockaddr
*)&addrbuf
, sizeof(addrbuf
), AF_INET
) < 0)
2689 return makeipaddr((struct sockaddr
*)&addrbuf
,
2690 sizeof(struct sockaddr_in
));
2693 PyDoc_STRVAR(gethostbyname_doc
,
2694 "gethostbyname(host) -> address\n\
2696 Return the IP address (a string of the form '255.255.255.255') for a host.");
2699 /* Convenience function common to gethostbyname_ex and gethostbyaddr */
2702 gethost_common(struct hostent
*h
, struct sockaddr
*addr
, int alen
, int af
)
2705 PyObject
*rtn_tuple
= (PyObject
*)NULL
;
2706 PyObject
*name_list
= (PyObject
*)NULL
;
2707 PyObject
*addr_list
= (PyObject
*)NULL
;
2711 /* Let's get real error message to return */
2713 set_herror(h_errno
);
2715 PyErr_SetString(socket_error
, "host not found");
2720 if (h
->h_addrtype
!= af
) {
2721 #ifdef HAVE_STRERROR
2722 /* Let's get real error message to return */
2723 PyErr_SetString(socket_error
,
2724 (char *)strerror(EAFNOSUPPORT
));
2728 "Address family not supported by protocol family");
2736 if (alen
< sizeof(struct sockaddr_in
))
2742 if (alen
< sizeof(struct sockaddr_in6
))
2749 if ((name_list
= PyList_New(0)) == NULL
)
2752 if ((addr_list
= PyList_New(0)) == NULL
)
2755 for (pch
= h
->h_aliases
; *pch
!= NULL
; pch
++) {
2757 tmp
= PyString_FromString(*pch
);
2761 status
= PyList_Append(name_list
, tmp
);
2768 for (pch
= h
->h_addr_list
; *pch
!= NULL
; pch
++) {
2775 struct sockaddr_in sin
;
2776 memset(&sin
, 0, sizeof(sin
));
2777 sin
.sin_family
= af
;
2778 #ifdef HAVE_SOCKADDR_SA_LEN
2779 sin
.sin_len
= sizeof(sin
);
2781 memcpy(&sin
.sin_addr
, *pch
, sizeof(sin
.sin_addr
));
2782 tmp
= makeipaddr((struct sockaddr
*)&sin
, sizeof(sin
));
2784 if (pch
== h
->h_addr_list
&& alen
>= sizeof(sin
))
2785 memcpy((char *) addr
, &sin
, sizeof(sin
));
2792 struct sockaddr_in6 sin6
;
2793 memset(&sin6
, 0, sizeof(sin6
));
2794 sin6
.sin6_family
= af
;
2795 #ifdef HAVE_SOCKADDR_SA_LEN
2796 sin6
.sin6_len
= sizeof(sin6
);
2798 memcpy(&sin6
.sin6_addr
, *pch
, sizeof(sin6
.sin6_addr
));
2799 tmp
= makeipaddr((struct sockaddr
*)&sin6
,
2802 if (pch
== h
->h_addr_list
&& alen
>= sizeof(sin6
))
2803 memcpy((char *) addr
, &sin6
, sizeof(sin6
));
2808 default: /* can't happen */
2809 PyErr_SetString(socket_error
,
2810 "unsupported address family");
2817 status
= PyList_Append(addr_list
, tmp
);
2824 rtn_tuple
= Py_BuildValue("sOO", h
->h_name
, name_list
, addr_list
);
2827 Py_XDECREF(name_list
);
2828 Py_XDECREF(addr_list
);
2833 /* Python interface to gethostbyname_ex(name). */
2837 socket_gethostbyname_ex(PyObject
*self
, PyObject
*args
)
2842 struct sockaddr_storage addr
;
2844 struct sockaddr_in addr
;
2846 struct sockaddr
*sa
;
2848 #ifdef HAVE_GETHOSTBYNAME_R
2849 struct hostent hp_allocated
;
2850 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
2851 struct hostent_data data
;
2854 int buf_len
= (sizeof buf
) - 1;
2857 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2860 #endif /* HAVE_GETHOSTBYNAME_R */
2862 if (!PyArg_ParseTuple(args
, "s:gethostbyname_ex", &name
))
2864 if (setipaddr(name
, (struct sockaddr
*)&addr
, sizeof(addr
), AF_INET
) < 0)
2866 Py_BEGIN_ALLOW_THREADS
2867 #ifdef HAVE_GETHOSTBYNAME_R
2868 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2869 result
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
,
2871 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
2872 h
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
, &errnop
);
2873 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
2874 memset((void *) &data
, '\0', sizeof(data
));
2875 result
= gethostbyname_r(name
, &hp_allocated
, &data
);
2876 h
= (result
!= 0) ? NULL
: &hp_allocated
;
2878 #else /* not HAVE_GETHOSTBYNAME_R */
2879 #ifdef USE_GETHOSTBYNAME_LOCK
2880 PyThread_acquire_lock(netdb_lock
, 1);
2882 h
= gethostbyname(name
);
2883 #endif /* HAVE_GETHOSTBYNAME_R */
2884 Py_END_ALLOW_THREADS
2885 /* Some C libraries would require addr.__ss_family instead of
2887 Therefore, we cast the sockaddr_storage into sockaddr to
2888 access sa_family. */
2889 sa
= (struct sockaddr
*)&addr
;
2890 ret
= gethost_common(h
, (struct sockaddr
*)&addr
, sizeof(addr
),
2892 #ifdef USE_GETHOSTBYNAME_LOCK
2893 PyThread_release_lock(netdb_lock
);
2898 PyDoc_STRVAR(ghbn_ex_doc
,
2899 "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
2901 Return the true host name, a list of aliases, and a list of IP addresses,\n\
2902 for a host. The host argument is a string giving a host name or IP number.");
2905 /* Python interface to gethostbyaddr(IP). */
2909 socket_gethostbyaddr(PyObject
*self
, PyObject
*args
)
2912 struct sockaddr_storage addr
;
2914 struct sockaddr_in addr
;
2916 struct sockaddr
*sa
= (struct sockaddr
*)&addr
;
2920 #ifdef HAVE_GETHOSTBYNAME_R
2921 struct hostent hp_allocated
;
2922 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
2923 struct hostent_data data
;
2926 int buf_len
= (sizeof buf
) - 1;
2929 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2932 #endif /* HAVE_GETHOSTBYNAME_R */
2937 if (!PyArg_ParseTuple(args
, "s:gethostbyaddr", &ip_num
))
2940 if (setipaddr(ip_num
, sa
, sizeof(addr
), af
) < 0)
2947 ap
= (char *)&((struct sockaddr_in
*)sa
)->sin_addr
;
2948 al
= sizeof(((struct sockaddr_in
*)sa
)->sin_addr
);
2952 ap
= (char *)&((struct sockaddr_in6
*)sa
)->sin6_addr
;
2953 al
= sizeof(((struct sockaddr_in6
*)sa
)->sin6_addr
);
2957 PyErr_SetString(socket_error
, "unsupported address family");
2960 Py_BEGIN_ALLOW_THREADS
2961 #ifdef HAVE_GETHOSTBYNAME_R
2962 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2963 result
= gethostbyaddr_r(ap
, al
, af
,
2964 &hp_allocated
, buf
, buf_len
,
2966 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
2967 h
= gethostbyaddr_r(ap
, al
, af
,
2968 &hp_allocated
, buf
, buf_len
, &errnop
);
2969 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
2970 memset((void *) &data
, '\0', sizeof(data
));
2971 result
= gethostbyaddr_r(ap
, al
, af
, &hp_allocated
, &data
);
2972 h
= (result
!= 0) ? NULL
: &hp_allocated
;
2974 #else /* not HAVE_GETHOSTBYNAME_R */
2975 #ifdef USE_GETHOSTBYNAME_LOCK
2976 PyThread_acquire_lock(netdb_lock
, 1);
2978 h
= gethostbyaddr(ap
, al
, af
);
2979 #endif /* HAVE_GETHOSTBYNAME_R */
2980 Py_END_ALLOW_THREADS
2981 ret
= gethost_common(h
, (struct sockaddr
*)&addr
, sizeof(addr
), af
);
2982 #ifdef USE_GETHOSTBYNAME_LOCK
2983 PyThread_release_lock(netdb_lock
);
2988 PyDoc_STRVAR(gethostbyaddr_doc
,
2989 "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
2991 Return the true host name, a list of aliases, and a list of IP addresses,\n\
2992 for a host. The host argument is a string giving a host name or IP number.");
2995 /* Python interface to getservbyname(name).
2996 This only returns the port number, since the other info is already
2997 known or not useful (like the list of aliases). */
3001 socket_getservbyname(PyObject
*self
, PyObject
*args
)
3003 char *name
, *proto
=NULL
;
3005 if (!PyArg_ParseTuple(args
, "s|s:getservbyname", &name
, &proto
))
3007 Py_BEGIN_ALLOW_THREADS
3008 sp
= getservbyname(name
, proto
);
3009 Py_END_ALLOW_THREADS
3011 PyErr_SetString(socket_error
, "service/proto not found");
3014 return PyInt_FromLong((long) ntohs(sp
->s_port
));
3017 PyDoc_STRVAR(getservbyname_doc
,
3018 "getservbyname(servicename[, protocolname]) -> integer\n\
3020 Return a port number from a service name and protocol name.\n\
3021 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3022 otherwise any protocol will match.");
3025 /* Python interface to getservbyport(port).
3026 This only returns the service name, since the other info is already
3027 known or not useful (like the list of aliases). */
3031 socket_getservbyport(PyObject
*self
, PyObject
*args
)
3033 unsigned short port
;
3036 if (!PyArg_ParseTuple(args
, "H|s:getservbyport", &port
, &proto
))
3038 Py_BEGIN_ALLOW_THREADS
3039 sp
= getservbyport(htons(port
), proto
);
3040 Py_END_ALLOW_THREADS
3042 PyErr_SetString(socket_error
, "port/proto not found");
3045 return PyString_FromString(sp
->s_name
);
3048 PyDoc_STRVAR(getservbyport_doc
,
3049 "getservbyport(port[, protocolname]) -> string\n\
3051 Return the service name from a port number and protocol name.\n\
3052 The optional protocol name, if given, should be 'tcp' or 'udp',\n\
3053 otherwise any protocol will match.");
3055 /* Python interface to getprotobyname(name).
3056 This only returns the protocol number, since the other info is
3057 already known or not useful (like the list of aliases). */
3061 socket_getprotobyname(PyObject
*self
, PyObject
*args
)
3064 struct protoent
*sp
;
3066 /* Not available in BeOS yet. - [cjh] */
3067 PyErr_SetString(socket_error
, "getprotobyname not supported");
3070 if (!PyArg_ParseTuple(args
, "s:getprotobyname", &name
))
3072 Py_BEGIN_ALLOW_THREADS
3073 sp
= getprotobyname(name
);
3074 Py_END_ALLOW_THREADS
3076 PyErr_SetString(socket_error
, "protocol not found");
3079 return PyInt_FromLong((long) sp
->p_proto
);
3083 PyDoc_STRVAR(getprotobyname_doc
,
3084 "getprotobyname(name) -> integer\n\
3086 Return the protocol number for the named protocol. (Rarely used.)");
3089 #ifdef HAVE_SOCKETPAIR
3090 /* Create a pair of sockets using the socketpair() function.
3091 Arguments as for socket() except the default family is AF_UNIX if
3092 defined on the platform; otherwise, the default is AF_INET. */
3096 socket_socketpair(PyObject
*self
, PyObject
*args
)
3098 PySocketSockObject
*s0
= NULL
, *s1
= NULL
;
3100 int family
, type
= SOCK_STREAM
, proto
= 0;
3101 PyObject
*res
= NULL
;
3103 #if defined(AF_UNIX)
3108 if (!PyArg_ParseTuple(args
, "|iii:socketpair",
3109 &family
, &type
, &proto
))
3111 /* Create a pair of socket fds */
3112 if (socketpair(family
, type
, proto
, sv
) < 0)
3114 s0
= new_sockobject(sv
[0], family
, type
, proto
);
3117 s1
= new_sockobject(sv
[1], family
, type
, proto
);
3120 res
= PyTuple_Pack(2, s0
, s1
);
3134 PyDoc_STRVAR(socketpair_doc
,
3135 "socketpair([family[, type[, proto]]]) -> (socket object, socket object)\n\
3137 Create a pair of socket objects from the sockets returned by the platform\n\
3138 socketpair() function.\n\
3139 The arguments are the same as for socket() except the default family is\n\
3140 AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");
3142 #endif /* HAVE_SOCKETPAIR */
3146 /* Create a socket object from a numeric file description.
3147 Useful e.g. if stdin is a socket.
3148 Additional arguments as for socket(). */
3152 socket_fromfd(PyObject
*self
, PyObject
*args
)
3154 PySocketSockObject
*s
;
3156 int family
, type
, proto
= 0;
3157 if (!PyArg_ParseTuple(args
, "iii|i:fromfd",
3158 &fd
, &family
, &type
, &proto
))
3160 /* Dup the fd so it and the socket can be closed independently */
3164 s
= new_sockobject(fd
, family
, type
, proto
);
3165 return (PyObject
*) s
;
3168 PyDoc_STRVAR(fromfd_doc
,
3169 "fromfd(fd, family, type[, proto]) -> socket object\n\
3171 Create a socket object from a duplicate of the given\n\
3173 The remaining arguments are the same as for socket().");
3179 socket_ntohs(PyObject
*self
, PyObject
*args
)
3183 if (!PyArg_ParseTuple(args
, "i:ntohs", &x1
)) {
3186 x2
= (int)ntohs((short)x1
);
3187 return PyInt_FromLong(x2
);
3190 PyDoc_STRVAR(ntohs_doc
,
3191 "ntohs(integer) -> integer\n\
3193 Convert a 16-bit integer from network to host byte order.");
3197 socket_ntohl(PyObject
*self
, PyObject
*arg
)
3201 if (PyInt_Check(arg
)) {
3202 x
= PyInt_AS_LONG(arg
);
3203 if (x
== (unsigned long) -1 && PyErr_Occurred())
3206 else if (PyLong_Check(arg
)) {
3207 x
= PyLong_AsUnsignedLong(arg
);
3208 if (x
== (unsigned long) -1 && PyErr_Occurred())
3213 /* only want the trailing 32 bits */
3214 y
= x
& 0xFFFFFFFFUL
;
3216 return PyErr_Format(PyExc_OverflowError
,
3217 "long int larger than 32 bits");
3223 return PyErr_Format(PyExc_TypeError
,
3224 "expected int/long, %s found",
3225 arg
->ob_type
->tp_name
);
3226 if (x
== (unsigned long) -1 && PyErr_Occurred())
3228 return PyInt_FromLong(ntohl(x
));
3231 PyDoc_STRVAR(ntohl_doc
,
3232 "ntohl(integer) -> integer\n\
3234 Convert a 32-bit integer from network to host byte order.");
3238 socket_htons(PyObject
*self
, PyObject
*args
)
3242 if (!PyArg_ParseTuple(args
, "i:htons", &x1
)) {
3245 x2
= (int)htons((short)x1
);
3246 return PyInt_FromLong(x2
);
3249 PyDoc_STRVAR(htons_doc
,
3250 "htons(integer) -> integer\n\
3252 Convert a 16-bit integer from host to network byte order.");
3256 socket_htonl(PyObject
*self
, PyObject
*arg
)
3260 if (PyInt_Check(arg
)) {
3261 x
= PyInt_AS_LONG(arg
);
3262 if (x
== (unsigned long) -1 && PyErr_Occurred())
3265 else if (PyLong_Check(arg
)) {
3266 x
= PyLong_AsUnsignedLong(arg
);
3267 if (x
== (unsigned long) -1 && PyErr_Occurred())
3272 /* only want the trailing 32 bits */
3273 y
= x
& 0xFFFFFFFFUL
;
3275 return PyErr_Format(PyExc_OverflowError
,
3276 "long int larger than 32 bits");
3282 return PyErr_Format(PyExc_TypeError
,
3283 "expected int/long, %s found",
3284 arg
->ob_type
->tp_name
);
3285 return PyInt_FromLong(htonl(x
));
3288 PyDoc_STRVAR(htonl_doc
,
3289 "htonl(integer) -> integer\n\
3291 Convert a 32-bit integer from host to network byte order.");
3293 /* socket.inet_aton() and socket.inet_ntoa() functions. */
3295 PyDoc_STRVAR(inet_aton_doc
,
3296 "inet_aton(string) -> packed 32-bit IP representation\n\
3298 Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
3299 binary format used in low-level network functions.");
3302 socket_inet_aton(PyObject
*self
, PyObject
*args
)
3305 #define INADDR_NONE (-1)
3307 #ifdef HAVE_INET_ATON
3310 /* Have to use inet_addr() instead */
3311 unsigned long packed_addr
;
3315 if (!PyArg_ParseTuple(args
, "s:inet_aton", &ip_addr
))
3319 #ifdef HAVE_INET_ATON
3320 if (inet_aton(ip_addr
, &buf
))
3321 return PyString_FromStringAndSize((char *)(&buf
),
3324 PyErr_SetString(socket_error
,
3325 "illegal IP address string passed to inet_aton");
3328 #else /* ! HAVE_INET_ATON */
3329 /* special-case this address as inet_addr might return INADDR_NONE
3331 if (strcmp(ip_addr
, "255.255.255.255") == 0) {
3332 packed_addr
= 0xFFFFFFFF;
3335 packed_addr
= inet_addr(ip_addr
);
3337 if (packed_addr
== INADDR_NONE
) { /* invalid address */
3338 PyErr_SetString(socket_error
,
3339 "illegal IP address string passed to inet_aton");
3343 return PyString_FromStringAndSize((char *) &packed_addr
,
3344 sizeof(packed_addr
));
3348 PyDoc_STRVAR(inet_ntoa_doc
,
3349 "inet_ntoa(packed_ip) -> ip_address_string\n\
3351 Convert an IP address from 32-bit packed binary format to string format");
3354 socket_inet_ntoa(PyObject
*self
, PyObject
*args
)
3358 struct in_addr packed_addr
;
3360 if (!PyArg_ParseTuple(args
, "s#:inet_ntoa", &packed_str
, &addr_len
)) {
3364 if (addr_len
!= sizeof(packed_addr
)) {
3365 PyErr_SetString(socket_error
,
3366 "packed IP wrong length for inet_ntoa");
3370 memcpy(&packed_addr
, packed_str
, addr_len
);
3372 return PyString_FromString(inet_ntoa(packed_addr
));
3375 #ifdef HAVE_INET_PTON
3377 PyDoc_STRVAR(inet_pton_doc
,
3378 "inet_pton(af, ip) -> packed IP address string\n\
3380 Convert an IP address from string format to a packed string suitable\n\
3381 for use with low-level network functions.");
3384 socket_inet_pton(PyObject
*self
, PyObject
*args
)
3390 char packed
[MAX(sizeof(struct in_addr
), sizeof(struct in6_addr
))];
3392 char packed
[sizeof(struct in_addr
)];
3394 if (!PyArg_ParseTuple(args
, "is:inet_pton", &af
, &ip
)) {
3398 #if !defined(ENABLE_IPV6) && defined(AF_INET6)
3399 if(af
== AF_INET6
) {
3400 PyErr_SetString(socket_error
,
3401 "can't use AF_INET6, IPv6 is disabled");
3406 retval
= inet_pton(af
, ip
, packed
);
3408 PyErr_SetFromErrno(socket_error
);
3410 } else if (retval
== 0) {
3411 PyErr_SetString(socket_error
,
3412 "illegal IP address string passed to inet_pton");
3414 } else if (af
== AF_INET
) {
3415 return PyString_FromStringAndSize(packed
,
3416 sizeof(struct in_addr
));
3418 } else if (af
== AF_INET6
) {
3419 return PyString_FromStringAndSize(packed
,
3420 sizeof(struct in6_addr
));
3423 PyErr_SetString(socket_error
, "unknown address family");
3428 PyDoc_STRVAR(inet_ntop_doc
,
3429 "inet_ntop(af, packed_ip) -> string formatted IP address\n\
3431 Convert a packed IP address of the given family to string format.");
3434 socket_inet_ntop(PyObject
*self
, PyObject
*args
)
3441 char ip
[MAX(INET_ADDRSTRLEN
, INET6_ADDRSTRLEN
) + 1];
3443 char ip
[INET_ADDRSTRLEN
+ 1];
3446 /* Guarantee NUL-termination for PyString_FromString() below */
3447 memset((void *) &ip
[0], '\0', sizeof(ip
));
3449 if (!PyArg_ParseTuple(args
, "is#:inet_ntop", &af
, &packed
, &len
)) {
3453 if (af
== AF_INET
) {
3454 if (len
!= sizeof(struct in_addr
)) {
3455 PyErr_SetString(PyExc_ValueError
,
3456 "invalid length of packed IP address string");
3460 } else if (af
== AF_INET6
) {
3461 if (len
!= sizeof(struct in6_addr
)) {
3462 PyErr_SetString(PyExc_ValueError
,
3463 "invalid length of packed IP address string");
3468 PyErr_Format(PyExc_ValueError
,
3469 "unknown address family %d", af
);
3473 retval
= inet_ntop(af
, packed
, ip
, sizeof(ip
));
3475 PyErr_SetFromErrno(socket_error
);
3478 return PyString_FromString(retval
);
3482 PyErr_SetString(PyExc_RuntimeError
, "invalid handling of inet_ntop");
3486 #endif /* HAVE_INET_PTON */
3488 /* Python interface to getaddrinfo(host, port). */
3492 socket_getaddrinfo(PyObject
*self
, PyObject
*args
)
3494 struct addrinfo hints
, *res
;
3495 struct addrinfo
*res0
= NULL
;
3496 PyObject
*hobj
= NULL
;
3497 PyObject
*pobj
= (PyObject
*)NULL
;
3500 int family
, socktype
, protocol
, flags
;
3502 PyObject
*all
= (PyObject
*)NULL
;
3503 PyObject
*single
= (PyObject
*)NULL
;
3504 PyObject
*idna
= NULL
;
3506 family
= socktype
= protocol
= flags
= 0;
3508 if (!PyArg_ParseTuple(args
, "OO|iiii:getaddrinfo",
3509 &hobj
, &pobj
, &family
, &socktype
,
3510 &protocol
, &flags
)) {
3513 if (hobj
== Py_None
) {
3515 } else if (PyUnicode_Check(hobj
)) {
3516 idna
= PyObject_CallMethod(hobj
, "encode", "s", "idna");
3519 hptr
= PyString_AsString(idna
);
3520 } else if (PyString_Check(hobj
)) {
3521 hptr
= PyString_AsString(hobj
);
3523 PyErr_SetString(PyExc_TypeError
,
3524 "getaddrinfo() argument 1 must be string or None");
3527 if (PyInt_Check(pobj
)) {
3528 PyOS_snprintf(pbuf
, sizeof(pbuf
), "%ld", PyInt_AsLong(pobj
));
3530 } else if (PyString_Check(pobj
)) {
3531 pptr
= PyString_AsString(pobj
);
3532 } else if (pobj
== Py_None
) {
3533 pptr
= (char *)NULL
;
3535 PyErr_SetString(socket_error
, "Int or String expected");
3538 memset(&hints
, 0, sizeof(hints
));
3539 hints
.ai_family
= family
;
3540 hints
.ai_socktype
= socktype
;
3541 hints
.ai_protocol
= protocol
;
3542 hints
.ai_flags
= flags
;
3543 Py_BEGIN_ALLOW_THREADS
3544 ACQUIRE_GETADDRINFO_LOCK
3545 error
= getaddrinfo(hptr
, pptr
, &hints
, &res0
);
3546 Py_END_ALLOW_THREADS
3547 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
3549 set_gaierror(error
);
3553 if ((all
= PyList_New(0)) == NULL
)
3555 for (res
= res0
; res
; res
= res
->ai_next
) {
3557 makesockaddr(-1, res
->ai_addr
, res
->ai_addrlen
, protocol
);
3560 single
= Py_BuildValue("iiisO", res
->ai_family
,
3561 res
->ai_socktype
, res
->ai_protocol
,
3562 res
->ai_canonname
? res
->ai_canonname
: "",
3568 if (PyList_Append(all
, single
))
3582 return (PyObject
*)NULL
;
3585 PyDoc_STRVAR(getaddrinfo_doc
,
3586 "getaddrinfo(host, port [, family, socktype, proto, flags])\n\
3587 -> list of (family, socktype, proto, canonname, sockaddr)\n\
3589 Resolve host and port into addrinfo struct.");
3591 /* Python interface to getnameinfo(sa, flags). */
3595 socket_getnameinfo(PyObject
*self
, PyObject
*args
)
3597 PyObject
*sa
= (PyObject
*)NULL
;
3600 int port
, flowinfo
, scope_id
;
3601 char hbuf
[NI_MAXHOST
], pbuf
[NI_MAXSERV
];
3602 struct addrinfo hints
, *res
= NULL
;
3604 PyObject
*ret
= (PyObject
*)NULL
;
3606 flags
= flowinfo
= scope_id
= 0;
3607 if (!PyArg_ParseTuple(args
, "Oi:getnameinfo", &sa
, &flags
))
3609 if (!PyArg_ParseTuple(sa
, "si|ii",
3610 &hostp
, &port
, &flowinfo
, &scope_id
))
3612 PyOS_snprintf(pbuf
, sizeof(pbuf
), "%d", port
);
3613 memset(&hints
, 0, sizeof(hints
));
3614 hints
.ai_family
= AF_UNSPEC
;
3615 hints
.ai_socktype
= SOCK_DGRAM
; /* make numeric port happy */
3616 Py_BEGIN_ALLOW_THREADS
3617 ACQUIRE_GETADDRINFO_LOCK
3618 error
= getaddrinfo(hostp
, pbuf
, &hints
, &res
);
3619 Py_END_ALLOW_THREADS
3620 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
3622 set_gaierror(error
);
3626 PyErr_SetString(socket_error
,
3627 "sockaddr resolved to multiple addresses");
3630 switch (res
->ai_family
) {
3635 if (PyArg_ParseTuple(sa
, "si", &t1
, &t2
) == 0) {
3636 PyErr_SetString(socket_error
,
3637 "IPv4 sockaddr must be 2 tuple");
3645 struct sockaddr_in6
*sin6
;
3646 sin6
= (struct sockaddr_in6
*)res
->ai_addr
;
3647 sin6
->sin6_flowinfo
= flowinfo
;
3648 sin6
->sin6_scope_id
= scope_id
;
3653 error
= getnameinfo(res
->ai_addr
, res
->ai_addrlen
,
3654 hbuf
, sizeof(hbuf
), pbuf
, sizeof(pbuf
), flags
);
3656 set_gaierror(error
);
3659 ret
= Py_BuildValue("ss", hbuf
, pbuf
);
3667 PyDoc_STRVAR(getnameinfo_doc
,
3668 "getnameinfo(sockaddr, flags) --> (host, port)\n\
3670 Get host and port for a sockaddr.");
3673 /* Python API to getting and setting the default timeout value. */
3676 socket_getdefaulttimeout(PyObject
*self
)
3678 if (defaulttimeout
< 0.0) {
3683 return PyFloat_FromDouble(defaulttimeout
);
3686 PyDoc_STRVAR(getdefaulttimeout_doc
,
3687 "getdefaulttimeout() -> timeout\n\
3689 Returns the default timeout in floating seconds for new socket objects.\n\
3690 A value of None indicates that new socket objects have no timeout.\n\
3691 When the socket module is first imported, the default is None.");
3694 socket_setdefaulttimeout(PyObject
*self
, PyObject
*arg
)
3701 timeout
= PyFloat_AsDouble(arg
);
3702 if (timeout
< 0.0) {
3703 if (!PyErr_Occurred())
3704 PyErr_SetString(PyExc_ValueError
,
3705 "Timeout value out of range");
3710 defaulttimeout
= timeout
;
3716 PyDoc_STRVAR(setdefaulttimeout_doc
,
3717 "setdefaulttimeout(timeout)\n\
3719 Set the default timeout in floating seconds for new socket objects.\n\
3720 A value of None indicates that new socket objects have no timeout.\n\
3721 When the socket module is first imported, the default is None.");
3724 /* List of functions exported by this module. */
3726 static PyMethodDef socket_methods
[] = {
3727 {"gethostbyname", socket_gethostbyname
,
3728 METH_VARARGS
, gethostbyname_doc
},
3729 {"gethostbyname_ex", socket_gethostbyname_ex
,
3730 METH_VARARGS
, ghbn_ex_doc
},
3731 {"gethostbyaddr", socket_gethostbyaddr
,
3732 METH_VARARGS
, gethostbyaddr_doc
},
3733 {"gethostname", socket_gethostname
,
3734 METH_VARARGS
, gethostname_doc
},
3735 {"getservbyname", socket_getservbyname
,
3736 METH_VARARGS
, getservbyname_doc
},
3737 {"getservbyport", socket_getservbyport
,
3738 METH_VARARGS
, getservbyport_doc
},
3739 {"getprotobyname", socket_getprotobyname
,
3740 METH_VARARGS
,getprotobyname_doc
},
3742 {"fromfd", socket_fromfd
,
3743 METH_VARARGS
, fromfd_doc
},
3745 #ifdef HAVE_SOCKETPAIR
3746 {"socketpair", socket_socketpair
,
3747 METH_VARARGS
, socketpair_doc
},
3749 {"ntohs", socket_ntohs
,
3750 METH_VARARGS
, ntohs_doc
},
3751 {"ntohl", socket_ntohl
,
3753 {"htons", socket_htons
,
3754 METH_VARARGS
, htons_doc
},
3755 {"htonl", socket_htonl
,
3757 {"inet_aton", socket_inet_aton
,
3758 METH_VARARGS
, inet_aton_doc
},
3759 {"inet_ntoa", socket_inet_ntoa
,
3760 METH_VARARGS
, inet_ntoa_doc
},
3761 #ifdef HAVE_INET_PTON
3762 {"inet_pton", socket_inet_pton
,
3763 METH_VARARGS
, inet_pton_doc
},
3764 {"inet_ntop", socket_inet_ntop
,
3765 METH_VARARGS
, inet_ntop_doc
},
3767 {"getaddrinfo", socket_getaddrinfo
,
3768 METH_VARARGS
, getaddrinfo_doc
},
3769 {"getnameinfo", socket_getnameinfo
,
3770 METH_VARARGS
, getnameinfo_doc
},
3771 {"getdefaulttimeout", (PyCFunction
)socket_getdefaulttimeout
,
3772 METH_NOARGS
, getdefaulttimeout_doc
},
3773 {"setdefaulttimeout", socket_setdefaulttimeout
,
3774 METH_O
, setdefaulttimeout_doc
},
3775 {NULL
, NULL
} /* Sentinel */
3780 #define OS_INIT_DEFINED
3788 _kernel_swi(0x43380, &r
, &r
);
3789 taskwindow
= r
.r
[0];
3798 #define OS_INIT_DEFINED
3800 /* Additional initialization and cleanup for Windows */
3814 ret
= WSAStartup(0x0101, &WSAData
);
3816 case 0: /* No error */
3817 Py_AtExit(os_cleanup
);
3818 return 1; /* Success */
3819 case WSASYSNOTREADY
:
3820 PyErr_SetString(PyExc_ImportError
,
3821 "WSAStartup failed: network not ready");
3823 case WSAVERNOTSUPPORTED
:
3827 "WSAStartup failed: requested version not supported");
3830 PyOS_snprintf(buf
, sizeof(buf
),
3831 "WSAStartup failed: error code %d", ret
);
3832 PyErr_SetString(PyExc_ImportError
, buf
);
3835 return 0; /* Failure */
3838 #endif /* MS_WINDOWS */
3842 #define OS_INIT_DEFINED
3844 /* Additional initialization for OS/2 */
3851 int rc
= sock_init();
3854 return 1; /* Success */
3857 PyOS_snprintf(reason
, sizeof(reason
),
3858 "OS/2 TCP/IP Error# %d", sock_errno());
3859 PyErr_SetString(PyExc_ImportError
, reason
);
3861 return 0; /* Failure */
3863 /* No need to initialise sockets with GCC/EMX */
3864 return 1; /* Success */
3868 #endif /* PYOS_OS2 */
3871 #ifndef OS_INIT_DEFINED
3875 return 1; /* Success */
3880 /* C API table - always add new things to the end for binary
3883 PySocketModule_APIObject PySocketModuleAPI
=
3890 /* Initialize the _socket module.
3892 This module is actually called "_socket", and there's a wrapper
3893 "socket.py" which implements some additional functionality. On some
3894 platforms (e.g. Windows and OS/2), socket.py also implements a
3895 wrapper for the socket type that provides missing functionality such
3896 as makefile(), dup() and fromfd(). The import of "_socket" may fail
3897 with an ImportError exception if os-specific initialization fails.
3898 On Windows, this does WINSOCK initialization. When WINSOCK is
3899 initialized succesfully, a call to WSACleanup() is scheduled to be
3903 PyDoc_STRVAR(socket_doc
,
3904 "Implementation module for socket operations.\n\
3906 See the socket module for documentation.");
3911 PyObject
*m
, *has_ipv6
;
3916 sock_type
.ob_type
= &PyType_Type
;
3917 m
= Py_InitModule3(PySocket_MODULE_NAME
,
3923 socket_error
= PyErr_NewException("socket.error", NULL
, NULL
);
3924 if (socket_error
== NULL
)
3926 PySocketModuleAPI
.error
= socket_error
;
3927 Py_INCREF(socket_error
);
3928 PyModule_AddObject(m
, "error", socket_error
);
3929 socket_herror
= PyErr_NewException("socket.herror",
3930 socket_error
, NULL
);
3931 if (socket_herror
== NULL
)
3933 Py_INCREF(socket_herror
);
3934 PyModule_AddObject(m
, "herror", socket_herror
);
3935 socket_gaierror
= PyErr_NewException("socket.gaierror", socket_error
,
3937 if (socket_gaierror
== NULL
)
3939 Py_INCREF(socket_gaierror
);
3940 PyModule_AddObject(m
, "gaierror", socket_gaierror
);
3941 socket_timeout
= PyErr_NewException("socket.timeout",
3942 socket_error
, NULL
);
3943 if (socket_timeout
== NULL
)
3945 Py_INCREF(socket_timeout
);
3946 PyModule_AddObject(m
, "timeout", socket_timeout
);
3947 Py_INCREF((PyObject
*)&sock_type
);
3948 if (PyModule_AddObject(m
, "SocketType",
3949 (PyObject
*)&sock_type
) != 0)
3951 Py_INCREF((PyObject
*)&sock_type
);
3952 if (PyModule_AddObject(m
, "socket",
3953 (PyObject
*)&sock_type
) != 0)
3959 has_ipv6
= Py_False
;
3961 Py_INCREF(has_ipv6
);
3962 PyModule_AddObject(m
, "has_ipv6", has_ipv6
);
3965 if (PyModule_AddObject(m
, PySocket_CAPI_NAME
,
3966 PyCObject_FromVoidPtr((void *)&PySocketModuleAPI
, NULL
)
3970 /* Address families (we only support AF_INET and AF_UNIX) */
3972 PyModule_AddIntConstant(m
, "AF_UNSPEC", AF_UNSPEC
);
3974 PyModule_AddIntConstant(m
, "AF_INET", AF_INET
);
3976 PyModule_AddIntConstant(m
, "AF_INET6", AF_INET6
);
3977 #endif /* AF_INET6 */
3978 #if defined(AF_UNIX)
3979 PyModule_AddIntConstant(m
, "AF_UNIX", AF_UNIX
);
3980 #endif /* AF_UNIX */
3982 /* Amateur Radio AX.25 */
3983 PyModule_AddIntConstant(m
, "AF_AX25", AF_AX25
);
3986 PyModule_AddIntConstant(m
, "AF_IPX", AF_IPX
); /* Novell IPX */
3990 PyModule_AddIntConstant(m
, "AF_APPLETALK", AF_APPLETALK
);
3993 /* Amateur radio NetROM */
3994 PyModule_AddIntConstant(m
, "AF_NETROM", AF_NETROM
);
3997 /* Multiprotocol bridge */
3998 PyModule_AddIntConstant(m
, "AF_BRIDGE", AF_BRIDGE
);
4002 PyModule_AddIntConstant(m
, "AF_ATMPVC", AF_ATMPVC
);
4005 /* Reserved for Werner's ATM */
4006 PyModule_AddIntConstant(m
, "AF_AAL5", AF_AAL5
);
4009 /* Reserved for X.25 project */
4010 PyModule_AddIntConstant(m
, "AF_X25", AF_X25
);
4013 PyModule_AddIntConstant(m
, "AF_INET6", AF_INET6
); /* IP version 6 */
4016 /* Amateur Radio X.25 PLP */
4017 PyModule_AddIntConstant(m
, "AF_ROSE", AF_ROSE
);
4020 /* Reserved for DECnet project */
4021 PyModule_AddIntConstant(m
, "AF_DECnet", AF_DECnet
);
4024 /* Reserved for 802.2LLC project */
4025 PyModule_AddIntConstant(m
, "AF_NETBEUI", AF_NETBEUI
);
4028 /* Security callback pseudo AF */
4029 PyModule_AddIntConstant(m
, "AF_SECURITY", AF_SECURITY
);
4032 /* PF_KEY key management API */
4033 PyModule_AddIntConstant(m
, "AF_KEY", AF_KEY
);
4037 PyModule_AddIntConstant(m
, "AF_NETLINK", AF_NETLINK
);
4038 PyModule_AddIntConstant(m
, "NETLINK_ROUTE", NETLINK_ROUTE
);
4039 PyModule_AddIntConstant(m
, "NETLINK_SKIP", NETLINK_SKIP
);
4040 PyModule_AddIntConstant(m
, "NETLINK_USERSOCK", NETLINK_USERSOCK
);
4041 PyModule_AddIntConstant(m
, "NETLINK_FIREWALL", NETLINK_FIREWALL
);
4042 #ifdef NETLINK_TCPDIAG
4043 PyModule_AddIntConstant(m
, "NETLINK_TCPDIAG", NETLINK_TCPDIAG
);
4045 #ifdef NETLINK_NFLOG
4046 PyModule_AddIntConstant(m
, "NETLINK_NFLOG", NETLINK_NFLOG
);
4049 PyModule_AddIntConstant(m
, "NETLINK_XFRM", NETLINK_XFRM
);
4051 PyModule_AddIntConstant(m
, "NETLINK_ARPD", NETLINK_ARPD
);
4052 PyModule_AddIntConstant(m
, "NETLINK_ROUTE6", NETLINK_ROUTE6
);
4053 PyModule_AddIntConstant(m
, "NETLINK_IP6_FW", NETLINK_IP6_FW
);
4054 PyModule_AddIntConstant(m
, "NETLINK_DNRTMSG", NETLINK_DNRTMSG
);
4055 PyModule_AddIntConstant(m
, "NETLINK_TAPBASE", NETLINK_TAPBASE
);
4056 #endif /* AF_NETLINK */
4058 /* Alias to emulate 4.4BSD */
4059 PyModule_AddIntConstant(m
, "AF_ROUTE", AF_ROUTE
);
4063 PyModule_AddIntConstant(m
, "AF_ASH", AF_ASH
);
4067 PyModule_AddIntConstant(m
, "AF_ECONET", AF_ECONET
);
4071 PyModule_AddIntConstant(m
, "AF_ATMSVC", AF_ATMSVC
);
4074 /* Linux SNA Project (nutters!) */
4075 PyModule_AddIntConstant(m
, "AF_SNA", AF_SNA
);
4079 PyModule_AddIntConstant(m
, "AF_IRDA", AF_IRDA
);
4083 PyModule_AddIntConstant(m
, "AF_PPPOX", AF_PPPOX
);
4086 /* Wanpipe API Sockets */
4087 PyModule_AddIntConstant(m
, "AF_WANPIPE", AF_WANPIPE
);
4091 PyModule_AddIntConstant(m
, "AF_LLC", AF_LLC
);
4094 #ifdef USE_BLUETOOTH
4095 PyModule_AddIntConstant(m
, "AF_BLUETOOTH", AF_BLUETOOTH
);
4096 PyModule_AddIntConstant(m
, "BTPROTO_L2CAP", BTPROTO_L2CAP
);
4097 #if !defined(__FreeBSD__)
4098 PyModule_AddIntConstant(m
, "BTPROTO_SCO", BTPROTO_SCO
);
4100 PyModule_AddIntConstant(m
, "BTPROTO_RFCOMM", BTPROTO_RFCOMM
);
4101 PyModule_AddObject(m
, "BDADDR_ANY", Py_BuildValue("s", "00:00:00:00:00:00"));
4102 PyModule_AddObject(m
, "BDADDR_LOCAL", Py_BuildValue("s", "00:00:00:FF:FF:FF"));
4105 #ifdef HAVE_NETPACKET_PACKET_H
4106 PyModule_AddIntConstant(m
, "AF_PACKET", AF_PACKET
);
4107 PyModule_AddIntConstant(m
, "PF_PACKET", PF_PACKET
);
4108 PyModule_AddIntConstant(m
, "PACKET_HOST", PACKET_HOST
);
4109 PyModule_AddIntConstant(m
, "PACKET_BROADCAST", PACKET_BROADCAST
);
4110 PyModule_AddIntConstant(m
, "PACKET_MULTICAST", PACKET_MULTICAST
);
4111 PyModule_AddIntConstant(m
, "PACKET_OTHERHOST", PACKET_OTHERHOST
);
4112 PyModule_AddIntConstant(m
, "PACKET_OUTGOING", PACKET_OUTGOING
);
4113 PyModule_AddIntConstant(m
, "PACKET_LOOPBACK", PACKET_LOOPBACK
);
4114 PyModule_AddIntConstant(m
, "PACKET_FASTROUTE", PACKET_FASTROUTE
);
4118 PyModule_AddIntConstant(m
, "SOCK_STREAM", SOCK_STREAM
);
4119 PyModule_AddIntConstant(m
, "SOCK_DGRAM", SOCK_DGRAM
);
4121 /* We have incomplete socket support. */
4122 PyModule_AddIntConstant(m
, "SOCK_RAW", SOCK_RAW
);
4123 PyModule_AddIntConstant(m
, "SOCK_SEQPACKET", SOCK_SEQPACKET
);
4124 #if defined(SOCK_RDM)
4125 PyModule_AddIntConstant(m
, "SOCK_RDM", SOCK_RDM
);
4130 PyModule_AddIntConstant(m
, "SO_DEBUG", SO_DEBUG
);
4132 #ifdef SO_ACCEPTCONN
4133 PyModule_AddIntConstant(m
, "SO_ACCEPTCONN", SO_ACCEPTCONN
);
4136 PyModule_AddIntConstant(m
, "SO_REUSEADDR", SO_REUSEADDR
);
4138 #ifdef SO_EXCLUSIVEADDRUSE
4139 PyModule_AddIntConstant(m
, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE
);
4143 PyModule_AddIntConstant(m
, "SO_KEEPALIVE", SO_KEEPALIVE
);
4146 PyModule_AddIntConstant(m
, "SO_DONTROUTE", SO_DONTROUTE
);
4149 PyModule_AddIntConstant(m
, "SO_BROADCAST", SO_BROADCAST
);
4151 #ifdef SO_USELOOPBACK
4152 PyModule_AddIntConstant(m
, "SO_USELOOPBACK", SO_USELOOPBACK
);
4155 PyModule_AddIntConstant(m
, "SO_LINGER", SO_LINGER
);
4158 PyModule_AddIntConstant(m
, "SO_OOBINLINE", SO_OOBINLINE
);
4161 PyModule_AddIntConstant(m
, "SO_REUSEPORT", SO_REUSEPORT
);
4164 PyModule_AddIntConstant(m
, "SO_SNDBUF", SO_SNDBUF
);
4167 PyModule_AddIntConstant(m
, "SO_RCVBUF", SO_RCVBUF
);
4170 PyModule_AddIntConstant(m
, "SO_SNDLOWAT", SO_SNDLOWAT
);
4173 PyModule_AddIntConstant(m
, "SO_RCVLOWAT", SO_RCVLOWAT
);
4176 PyModule_AddIntConstant(m
, "SO_SNDTIMEO", SO_SNDTIMEO
);
4179 PyModule_AddIntConstant(m
, "SO_RCVTIMEO", SO_RCVTIMEO
);
4182 PyModule_AddIntConstant(m
, "SO_ERROR", SO_ERROR
);
4185 PyModule_AddIntConstant(m
, "SO_TYPE", SO_TYPE
);
4188 /* Maximum number of connections for "listen" */
4190 PyModule_AddIntConstant(m
, "SOMAXCONN", SOMAXCONN
);
4192 PyModule_AddIntConstant(m
, "SOMAXCONN", 5); /* Common value */
4195 /* Flags for send, recv */
4197 PyModule_AddIntConstant(m
, "MSG_OOB", MSG_OOB
);
4200 PyModule_AddIntConstant(m
, "MSG_PEEK", MSG_PEEK
);
4202 #ifdef MSG_DONTROUTE
4203 PyModule_AddIntConstant(m
, "MSG_DONTROUTE", MSG_DONTROUTE
);
4206 PyModule_AddIntConstant(m
, "MSG_DONTWAIT", MSG_DONTWAIT
);
4209 PyModule_AddIntConstant(m
, "MSG_EOR", MSG_EOR
);
4212 PyModule_AddIntConstant(m
, "MSG_TRUNC", MSG_TRUNC
);
4215 PyModule_AddIntConstant(m
, "MSG_CTRUNC", MSG_CTRUNC
);
4218 PyModule_AddIntConstant(m
, "MSG_WAITALL", MSG_WAITALL
);
4221 PyModule_AddIntConstant(m
, "MSG_BTAG", MSG_BTAG
);
4224 PyModule_AddIntConstant(m
, "MSG_ETAG", MSG_ETAG
);
4227 /* Protocol level and numbers, usable for [gs]etsockopt */
4229 PyModule_AddIntConstant(m
, "SOL_SOCKET", SOL_SOCKET
);
4232 PyModule_AddIntConstant(m
, "SOL_IP", SOL_IP
);
4234 PyModule_AddIntConstant(m
, "SOL_IP", 0);
4237 PyModule_AddIntConstant(m
, "SOL_IPX", SOL_IPX
);
4240 PyModule_AddIntConstant(m
, "SOL_AX25", SOL_AX25
);
4243 PyModule_AddIntConstant(m
, "SOL_ATALK", SOL_ATALK
);
4246 PyModule_AddIntConstant(m
, "SOL_NETROM", SOL_NETROM
);
4249 PyModule_AddIntConstant(m
, "SOL_ROSE", SOL_ROSE
);
4252 PyModule_AddIntConstant(m
, "SOL_TCP", SOL_TCP
);
4254 PyModule_AddIntConstant(m
, "SOL_TCP", 6);
4257 PyModule_AddIntConstant(m
, "SOL_UDP", SOL_UDP
);
4259 PyModule_AddIntConstant(m
, "SOL_UDP", 17);
4262 PyModule_AddIntConstant(m
, "IPPROTO_IP", IPPROTO_IP
);
4264 PyModule_AddIntConstant(m
, "IPPROTO_IP", 0);
4266 #ifdef IPPROTO_HOPOPTS
4267 PyModule_AddIntConstant(m
, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS
);
4270 PyModule_AddIntConstant(m
, "IPPROTO_ICMP", IPPROTO_ICMP
);
4272 PyModule_AddIntConstant(m
, "IPPROTO_ICMP", 1);
4275 PyModule_AddIntConstant(m
, "IPPROTO_IGMP", IPPROTO_IGMP
);
4278 PyModule_AddIntConstant(m
, "IPPROTO_GGP", IPPROTO_GGP
);
4281 PyModule_AddIntConstant(m
, "IPPROTO_IPV4", IPPROTO_IPV4
);
4284 PyModule_AddIntConstant(m
, "IPPROTO_IPV6", IPPROTO_IPV6
);
4287 PyModule_AddIntConstant(m
, "IPPROTO_IPIP", IPPROTO_IPIP
);
4290 PyModule_AddIntConstant(m
, "IPPROTO_TCP", IPPROTO_TCP
);
4292 PyModule_AddIntConstant(m
, "IPPROTO_TCP", 6);
4295 PyModule_AddIntConstant(m
, "IPPROTO_EGP", IPPROTO_EGP
);
4298 PyModule_AddIntConstant(m
, "IPPROTO_PUP", IPPROTO_PUP
);
4301 PyModule_AddIntConstant(m
, "IPPROTO_UDP", IPPROTO_UDP
);
4303 PyModule_AddIntConstant(m
, "IPPROTO_UDP", 17);
4306 PyModule_AddIntConstant(m
, "IPPROTO_IDP", IPPROTO_IDP
);
4308 #ifdef IPPROTO_HELLO
4309 PyModule_AddIntConstant(m
, "IPPROTO_HELLO", IPPROTO_HELLO
);
4312 PyModule_AddIntConstant(m
, "IPPROTO_ND", IPPROTO_ND
);
4315 PyModule_AddIntConstant(m
, "IPPROTO_TP", IPPROTO_TP
);
4318 PyModule_AddIntConstant(m
, "IPPROTO_IPV6", IPPROTO_IPV6
);
4320 #ifdef IPPROTO_ROUTING
4321 PyModule_AddIntConstant(m
, "IPPROTO_ROUTING", IPPROTO_ROUTING
);
4323 #ifdef IPPROTO_FRAGMENT
4324 PyModule_AddIntConstant(m
, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT
);
4327 PyModule_AddIntConstant(m
, "IPPROTO_RSVP", IPPROTO_RSVP
);
4330 PyModule_AddIntConstant(m
, "IPPROTO_GRE", IPPROTO_GRE
);
4333 PyModule_AddIntConstant(m
, "IPPROTO_ESP", IPPROTO_ESP
);
4336 PyModule_AddIntConstant(m
, "IPPROTO_AH", IPPROTO_AH
);
4338 #ifdef IPPROTO_MOBILE
4339 PyModule_AddIntConstant(m
, "IPPROTO_MOBILE", IPPROTO_MOBILE
);
4341 #ifdef IPPROTO_ICMPV6
4342 PyModule_AddIntConstant(m
, "IPPROTO_ICMPV6", IPPROTO_ICMPV6
);
4345 PyModule_AddIntConstant(m
, "IPPROTO_NONE", IPPROTO_NONE
);
4347 #ifdef IPPROTO_DSTOPTS
4348 PyModule_AddIntConstant(m
, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS
);
4351 PyModule_AddIntConstant(m
, "IPPROTO_XTP", IPPROTO_XTP
);
4354 PyModule_AddIntConstant(m
, "IPPROTO_EON", IPPROTO_EON
);
4357 PyModule_AddIntConstant(m
, "IPPROTO_PIM", IPPROTO_PIM
);
4359 #ifdef IPPROTO_IPCOMP
4360 PyModule_AddIntConstant(m
, "IPPROTO_IPCOMP", IPPROTO_IPCOMP
);
4363 PyModule_AddIntConstant(m
, "IPPROTO_VRRP", IPPROTO_VRRP
);
4366 PyModule_AddIntConstant(m
, "IPPROTO_BIP", IPPROTO_BIP
);
4370 PyModule_AddIntConstant(m
, "IPPROTO_RAW", IPPROTO_RAW
);
4372 PyModule_AddIntConstant(m
, "IPPROTO_RAW", 255);
4375 PyModule_AddIntConstant(m
, "IPPROTO_MAX", IPPROTO_MAX
);
4378 /* Some port configuration */
4379 #ifdef IPPORT_RESERVED
4380 PyModule_AddIntConstant(m
, "IPPORT_RESERVED", IPPORT_RESERVED
);
4382 PyModule_AddIntConstant(m
, "IPPORT_RESERVED", 1024);
4384 #ifdef IPPORT_USERRESERVED
4385 PyModule_AddIntConstant(m
, "IPPORT_USERRESERVED", IPPORT_USERRESERVED
);
4387 PyModule_AddIntConstant(m
, "IPPORT_USERRESERVED", 5000);
4390 /* Some reserved IP v.4 addresses */
4392 PyModule_AddIntConstant(m
, "INADDR_ANY", INADDR_ANY
);
4394 PyModule_AddIntConstant(m
, "INADDR_ANY", 0x00000000);
4396 #ifdef INADDR_BROADCAST
4397 PyModule_AddIntConstant(m
, "INADDR_BROADCAST", INADDR_BROADCAST
);
4399 PyModule_AddIntConstant(m
, "INADDR_BROADCAST", 0xffffffff);
4401 #ifdef INADDR_LOOPBACK
4402 PyModule_AddIntConstant(m
, "INADDR_LOOPBACK", INADDR_LOOPBACK
);
4404 PyModule_AddIntConstant(m
, "INADDR_LOOPBACK", 0x7F000001);
4406 #ifdef INADDR_UNSPEC_GROUP
4407 PyModule_AddIntConstant(m
, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP
);
4409 PyModule_AddIntConstant(m
, "INADDR_UNSPEC_GROUP", 0xe0000000);
4411 #ifdef INADDR_ALLHOSTS_GROUP
4412 PyModule_AddIntConstant(m
, "INADDR_ALLHOSTS_GROUP",
4413 INADDR_ALLHOSTS_GROUP
);
4415 PyModule_AddIntConstant(m
, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
4417 #ifdef INADDR_MAX_LOCAL_GROUP
4418 PyModule_AddIntConstant(m
, "INADDR_MAX_LOCAL_GROUP",
4419 INADDR_MAX_LOCAL_GROUP
);
4421 PyModule_AddIntConstant(m
, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
4424 PyModule_AddIntConstant(m
, "INADDR_NONE", INADDR_NONE
);
4426 PyModule_AddIntConstant(m
, "INADDR_NONE", 0xffffffff);
4429 /* IPv4 [gs]etsockopt options */
4431 PyModule_AddIntConstant(m
, "IP_OPTIONS", IP_OPTIONS
);
4434 PyModule_AddIntConstant(m
, "IP_HDRINCL", IP_HDRINCL
);
4437 PyModule_AddIntConstant(m
, "IP_TOS", IP_TOS
);
4440 PyModule_AddIntConstant(m
, "IP_TTL", IP_TTL
);
4443 PyModule_AddIntConstant(m
, "IP_RECVOPTS", IP_RECVOPTS
);
4445 #ifdef IP_RECVRETOPTS
4446 PyModule_AddIntConstant(m
, "IP_RECVRETOPTS", IP_RECVRETOPTS
);
4448 #ifdef IP_RECVDSTADDR
4449 PyModule_AddIntConstant(m
, "IP_RECVDSTADDR", IP_RECVDSTADDR
);
4452 PyModule_AddIntConstant(m
, "IP_RETOPTS", IP_RETOPTS
);
4454 #ifdef IP_MULTICAST_IF
4455 PyModule_AddIntConstant(m
, "IP_MULTICAST_IF", IP_MULTICAST_IF
);
4457 #ifdef IP_MULTICAST_TTL
4458 PyModule_AddIntConstant(m
, "IP_MULTICAST_TTL", IP_MULTICAST_TTL
);
4460 #ifdef IP_MULTICAST_LOOP
4461 PyModule_AddIntConstant(m
, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP
);
4463 #ifdef IP_ADD_MEMBERSHIP
4464 PyModule_AddIntConstant(m
, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP
);
4466 #ifdef IP_DROP_MEMBERSHIP
4467 PyModule_AddIntConstant(m
, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP
);
4469 #ifdef IP_DEFAULT_MULTICAST_TTL
4470 PyModule_AddIntConstant(m
, "IP_DEFAULT_MULTICAST_TTL",
4471 IP_DEFAULT_MULTICAST_TTL
);
4473 #ifdef IP_DEFAULT_MULTICAST_LOOP
4474 PyModule_AddIntConstant(m
, "IP_DEFAULT_MULTICAST_LOOP",
4475 IP_DEFAULT_MULTICAST_LOOP
);
4477 #ifdef IP_MAX_MEMBERSHIPS
4478 PyModule_AddIntConstant(m
, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS
);
4481 /* IPv6 [gs]etsockopt options, defined in RFC2553 */
4482 #ifdef IPV6_JOIN_GROUP
4483 PyModule_AddIntConstant(m
, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP
);
4485 #ifdef IPV6_LEAVE_GROUP
4486 PyModule_AddIntConstant(m
, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP
);
4488 #ifdef IPV6_MULTICAST_HOPS
4489 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS
);
4491 #ifdef IPV6_MULTICAST_IF
4492 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF
);
4494 #ifdef IPV6_MULTICAST_LOOP
4495 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP
);
4497 #ifdef IPV6_UNICAST_HOPS
4498 PyModule_AddIntConstant(m
, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS
);
4500 /* Additional IPV6 socket options, defined in RFC 3493 */
4502 PyModule_AddIntConstant(m
, "IPV6_V6ONLY", IPV6_V6ONLY
);
4504 /* Advanced IPV6 socket options, from RFC 3542 */
4505 #ifdef IPV6_CHECKSUM
4506 PyModule_AddIntConstant(m
, "IPV6_CHECKSUM", IPV6_CHECKSUM
);
4508 #ifdef IPV6_DONTFRAG
4509 PyModule_AddIntConstant(m
, "IPV6_DONTFRAG", IPV6_DONTFRAG
);
4512 PyModule_AddIntConstant(m
, "IPV6_DSTOPTS", IPV6_DSTOPTS
);
4514 #ifdef IPV6_HOPLIMIT
4515 PyModule_AddIntConstant(m
, "IPV6_HOPLIMIT", IPV6_HOPLIMIT
);
4518 PyModule_AddIntConstant(m
, "IPV6_HOPOPTS", IPV6_HOPOPTS
);
4521 PyModule_AddIntConstant(m
, "IPV6_NEXTHOP", IPV6_NEXTHOP
);
4524 PyModule_AddIntConstant(m
, "IPV6_PATHMTU", IPV6_PATHMTU
);
4527 PyModule_AddIntConstant(m
, "IPV6_PKTINFO", IPV6_PKTINFO
);
4529 #ifdef IPV6_RECVDSTOPTS
4530 PyModule_AddIntConstant(m
, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS
);
4532 #ifdef IPV6_RECVHOPLIMIT
4533 PyModule_AddIntConstant(m
, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT
);
4535 #ifdef IPV6_RECVHOPOPTS
4536 PyModule_AddIntConstant(m
, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS
);
4538 #ifdef IPV6_RECVPKTINFO
4539 PyModule_AddIntConstant(m
, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO
);
4541 #ifdef IPV6_RECVRTHDR
4542 PyModule_AddIntConstant(m
, "IPV6_RECVRTHDR", IPV6_RECVRTHDR
);
4544 #ifdef IPV6_RECVTCLASS
4545 PyModule_AddIntConstant(m
, "IPV6_RECVTCLASS", IPV6_RECVTCLASS
);
4548 PyModule_AddIntConstant(m
, "IPV6_RTHDR", IPV6_RTHDR
);
4550 #ifdef IPV6_RTHDRDSTOPTS
4551 PyModule_AddIntConstant(m
, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS
);
4553 #ifdef IPV6_RTHDR_TYPE_0
4554 PyModule_AddIntConstant(m
, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0
);
4556 #ifdef IPV6_RECVPATHMTU
4557 PyModule_AddIntConstant(m
, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU
);
4560 PyModule_AddIntConstant(m
, "IPV6_TCLASS", IPV6_TCLASS
);
4562 #ifdef IPV6_USE_MIN_MTU
4563 PyModule_AddIntConstant(m
, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU
);
4568 PyModule_AddIntConstant(m
, "TCP_NODELAY", TCP_NODELAY
);
4571 PyModule_AddIntConstant(m
, "TCP_MAXSEG", TCP_MAXSEG
);
4574 PyModule_AddIntConstant(m
, "TCP_CORK", TCP_CORK
);
4577 PyModule_AddIntConstant(m
, "TCP_KEEPIDLE", TCP_KEEPIDLE
);
4579 #ifdef TCP_KEEPINTVL
4580 PyModule_AddIntConstant(m
, "TCP_KEEPINTVL", TCP_KEEPINTVL
);
4583 PyModule_AddIntConstant(m
, "TCP_KEEPCNT", TCP_KEEPCNT
);
4586 PyModule_AddIntConstant(m
, "TCP_SYNCNT", TCP_SYNCNT
);
4589 PyModule_AddIntConstant(m
, "TCP_LINGER2", TCP_LINGER2
);
4591 #ifdef TCP_DEFER_ACCEPT
4592 PyModule_AddIntConstant(m
, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT
);
4594 #ifdef TCP_WINDOW_CLAMP
4595 PyModule_AddIntConstant(m
, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP
);
4598 PyModule_AddIntConstant(m
, "TCP_INFO", TCP_INFO
);
4601 PyModule_AddIntConstant(m
, "TCP_QUICKACK", TCP_QUICKACK
);
4607 PyModule_AddIntConstant(m
, "IPX_TYPE", IPX_TYPE
);
4610 /* get{addr,name}info parameters */
4611 #ifdef EAI_ADDRFAMILY
4612 PyModule_AddIntConstant(m
, "EAI_ADDRFAMILY", EAI_ADDRFAMILY
);
4615 PyModule_AddIntConstant(m
, "EAI_AGAIN", EAI_AGAIN
);
4618 PyModule_AddIntConstant(m
, "EAI_BADFLAGS", EAI_BADFLAGS
);
4621 PyModule_AddIntConstant(m
, "EAI_FAIL", EAI_FAIL
);
4624 PyModule_AddIntConstant(m
, "EAI_FAMILY", EAI_FAMILY
);
4627 PyModule_AddIntConstant(m
, "EAI_MEMORY", EAI_MEMORY
);
4630 PyModule_AddIntConstant(m
, "EAI_NODATA", EAI_NODATA
);
4633 PyModule_AddIntConstant(m
, "EAI_NONAME", EAI_NONAME
);
4636 PyModule_AddIntConstant(m
, "EAI_OVERFLOW", EAI_OVERFLOW
);
4639 PyModule_AddIntConstant(m
, "EAI_SERVICE", EAI_SERVICE
);
4642 PyModule_AddIntConstant(m
, "EAI_SOCKTYPE", EAI_SOCKTYPE
);
4645 PyModule_AddIntConstant(m
, "EAI_SYSTEM", EAI_SYSTEM
);
4648 PyModule_AddIntConstant(m
, "EAI_BADHINTS", EAI_BADHINTS
);
4651 PyModule_AddIntConstant(m
, "EAI_PROTOCOL", EAI_PROTOCOL
);
4654 PyModule_AddIntConstant(m
, "EAI_MAX", EAI_MAX
);
4657 PyModule_AddIntConstant(m
, "AI_PASSIVE", AI_PASSIVE
);
4660 PyModule_AddIntConstant(m
, "AI_CANONNAME", AI_CANONNAME
);
4662 #ifdef AI_NUMERICHOST
4663 PyModule_AddIntConstant(m
, "AI_NUMERICHOST", AI_NUMERICHOST
);
4665 #ifdef AI_NUMERICSERV
4666 PyModule_AddIntConstant(m
, "AI_NUMERICSERV", AI_NUMERICSERV
);
4669 PyModule_AddIntConstant(m
, "AI_MASK", AI_MASK
);
4672 PyModule_AddIntConstant(m
, "AI_ALL", AI_ALL
);
4674 #ifdef AI_V4MAPPED_CFG
4675 PyModule_AddIntConstant(m
, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG
);
4677 #ifdef AI_ADDRCONFIG
4678 PyModule_AddIntConstant(m
, "AI_ADDRCONFIG", AI_ADDRCONFIG
);
4681 PyModule_AddIntConstant(m
, "AI_V4MAPPED", AI_V4MAPPED
);
4684 PyModule_AddIntConstant(m
, "AI_DEFAULT", AI_DEFAULT
);
4687 PyModule_AddIntConstant(m
, "NI_MAXHOST", NI_MAXHOST
);
4690 PyModule_AddIntConstant(m
, "NI_MAXSERV", NI_MAXSERV
);
4693 PyModule_AddIntConstant(m
, "NI_NOFQDN", NI_NOFQDN
);
4695 #ifdef NI_NUMERICHOST
4696 PyModule_AddIntConstant(m
, "NI_NUMERICHOST", NI_NUMERICHOST
);
4699 PyModule_AddIntConstant(m
, "NI_NAMEREQD", NI_NAMEREQD
);
4701 #ifdef NI_NUMERICSERV
4702 PyModule_AddIntConstant(m
, "NI_NUMERICSERV", NI_NUMERICSERV
);
4705 PyModule_AddIntConstant(m
, "NI_DGRAM", NI_DGRAM
);
4708 /* shutdown() parameters */
4710 PyModule_AddIntConstant(m
, "SHUT_RD", SHUT_RD
);
4711 #elif defined(SD_RECEIVE)
4712 PyModule_AddIntConstant(m
, "SHUT_RD", SD_RECEIVE
);
4714 PyModule_AddIntConstant(m
, "SHUT_RD", 0);
4717 PyModule_AddIntConstant(m
, "SHUT_WR", SHUT_WR
);
4718 #elif defined(SD_SEND)
4719 PyModule_AddIntConstant(m
, "SHUT_WR", SD_SEND
);
4721 PyModule_AddIntConstant(m
, "SHUT_WR", 1);
4724 PyModule_AddIntConstant(m
, "SHUT_RDWR", SHUT_RDWR
);
4725 #elif defined(SD_BOTH)
4726 PyModule_AddIntConstant(m
, "SHUT_RDWR", SD_BOTH
);
4728 PyModule_AddIntConstant(m
, "SHUT_RDWR", 2);
4731 /* Initialize gethostbyname lock */
4732 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
4733 netdb_lock
= PyThread_allocate_lock();
4738 #ifndef HAVE_INET_PTON
4740 /* Simplistic emulation code for inet_pton that only works for IPv4 */
4741 /* These are not exposed because they do not set errno properly */
4744 inet_pton(int af
, const char *src
, void *dst
)
4746 if (af
== AF_INET
) {
4748 packed_addr
= inet_addr(src
);
4749 if (packed_addr
== INADDR_NONE
)
4751 memcpy(dst
, &packed_addr
, 4);
4754 /* Should set errno to EAFNOSUPPORT */
4759 inet_ntop(int af
, const void *src
, char *dst
, socklen_t size
)
4761 if (af
== AF_INET
) {
4762 struct in_addr packed_addr
;
4764 /* Should set errno to ENOSPC. */
4766 memcpy(&packed_addr
, src
, sizeof(packed_addr
));
4767 return strncpy(dst
, inet_ntoa(packed_addr
), size
);
4769 /* Should set errno to EAFNOSUPPORT */