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 is 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.socket([family[, type [, proto]]]) --> new socket object
30 - socket.ntohs(16 bit value) --> new int object
31 - socket.ntohl(32 bit value) --> new int object
32 - socket.htons(16 bit value) --> new int object
33 - socket.htonl(32 bit value) --> new int object
34 - socket.getaddrinfo(host, port [, family, socktype, proto, flags])
35 --> List of (family, socktype, proto, canonname, sockaddr)
36 - socket.getnameinfo(sockaddr, flags) --> (host, port)
37 - socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
38 - socket.has_ipv6: boolean value indicating if IPv6 is supported
39 - socket.inet_aton(IP address) -> 32-bit packed IP representation
40 - socket.inet_ntoa(packed IP) -> IP address string
41 - socket.getdefaulttimeout() -> None | float
42 - socket.setdefaulttimeout(None | float)
43 - an Internet socket address is a pair (hostname, port)
44 where hostname can be anything recognized by gethostbyname()
45 (including the dd.dd.dd.dd notation) and port is in host byte order
46 - where a hostname is returned, the dd.dd.dd.dd notation is used
47 - a UNIX domain socket address is a string specifying the pathname
48 - an AF_PACKET socket address is a tuple containing a string
49 specifying the ethernet interface and an integer specifying
50 the Ethernet protocol number to be received. For example:
51 ("eth0",0x1234). Optional 3rd,4th,5th elements in the tuple
52 specify packet-type and ha-type/addr -- these are ignored by
53 networking code, but accepted since they are returned by the
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
67 #define MAX(x, y) ((x) < (y) ? (y) : (x))
69 /* Socket object documentation */
70 PyDoc_STRVAR(sock_doc
,
71 "socket([family[, type[, proto]]]) -> socket object\n\
73 Open a socket of the given type. The family argument specifies the\n\
74 address family; it defaults to AF_INET. The type argument specifies\n\
75 whether this is a stream (SOCK_STREAM, this is the default)\n\
76 or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0,\n\
77 specifying the default protocol. Keyword arguments are accepted.\n\
79 A socket object represents one endpoint of a network connection.\n\
81 Methods of socket objects (keyword arguments not allowed):\n\
83 accept() -- accept a connection, returning new socket and client address\n\
84 bind(addr) -- bind the socket to a local address\n\
85 close() -- close the socket\n\
86 connect(addr) -- connect the socket to a remote address\n\
87 connect_ex(addr) -- connect, return an error code instead of an exception\n\
88 dup() -- return a new socket object identical to the current one [*]\n\
89 fileno() -- return underlying file descriptor\n\
90 getpeername() -- return remote address [*]\n\
91 getsockname() -- return local address\n\
92 getsockopt(level, optname[, buflen]) -- get socket options\n\
93 gettimeout() -- return timeout or None\n\
94 listen(n) -- start listening for incoming connections\n\
95 makefile([mode, [bufsize]]) -- return a file object for the socket [*]\n\
96 recv(buflen[, flags]) -- receive data\n\
97 recvfrom(buflen[, flags]) -- receive data and sender's address\n\
98 sendall(data[, flags]) -- send all data\n\
99 send(data[, flags]) -- send data, may not send all of it\n\
100 sendto(data[, flags], addr) -- send data to a given address\n\
101 setblocking(0 | 1) -- set or clear the blocking I/O flag\n\
102 setsockopt(level, optname, value) -- set socket options\n\
103 settimeout(None | float) -- set or clear the timeout\n\
104 shutdown(how) -- shut down traffic in one or both directions\n\
106 [*] not available on all platforms!");
108 /* XXX This is a terrible mess of of platform-dependent preprocessor hacks.
109 I hope some day someone can clean this up please... */
111 /* Hacks for gethostbyname_r(). On some non-Linux platforms, the configure
112 script doesn't get this right, so we hardcode some platform checks below.
113 On the other hand, not all Linux versions agree, so there the settings
114 computed by the configure script are needed! */
117 # undef HAVE_GETHOSTBYNAME_R_3_ARG
118 # undef HAVE_GETHOSTBYNAME_R_5_ARG
119 # undef HAVE_GETHOSTBYNAME_R_6_ARG
123 # undef HAVE_GETHOSTBYNAME_R
126 #ifdef HAVE_GETHOSTBYNAME_R
127 # if defined(_AIX) || defined(__osf__)
128 # define HAVE_GETHOSTBYNAME_R_3_ARG
129 # elif defined(__sun) || defined(__sgi)
130 # define HAVE_GETHOSTBYNAME_R_5_ARG
131 # elif defined(linux)
132 /* Rely on the configure script */
134 # undef HAVE_GETHOSTBYNAME_R
138 #if !defined(HAVE_GETHOSTBYNAME_R) && defined(WITH_THREAD) && \
140 # define USE_GETHOSTBYNAME_LOCK
143 /* On systems on which getaddrinfo() is believed to not be thread-safe,
144 (this includes the getaddrinfo emulation) protect access with a lock. */
145 #if defined(WITH_THREAD) && (defined(__APPLE__) || defined(__FreeBSD__) || \
146 defined(__OpenBSD__) || defined(__NetBSD__) || !defined(HAVE_GETADDRINFO))
147 #define USE_GETADDRINFO_LOCK
150 #ifdef USE_GETADDRINFO_LOCK
151 #define ACQUIRE_GETADDRINFO_LOCK PyThread_acquire_lock(netdb_lock, 1);
152 #define RELEASE_GETADDRINFO_LOCK PyThread_release_lock(netdb_lock);
154 #define ACQUIRE_GETADDRINFO_LOCK
155 #define RELEASE_GETADDRINFO_LOCK
158 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
159 # include "pythread.h"
162 #if defined(PYCC_VACPP)
165 # include <sys/ioctl.h>
171 #if ! defined(_SOCKADDR_LEN)
175 # include "TCPIP_IOCTL_ROUTINE"
181 #if defined(PYOS_OS2)
183 # define INCL_DOSERRORS
184 # define INCL_NOPMAPI
188 #if defined(__sgi)&&_COMPILER_VERSION>700 && !_SGIAPI
189 /* make sure that the reentrant (gethostbyaddr_r etc)
190 functions are declared correctly if compiling with
191 MIPSPro 7.x in ANSI C mode (default) */
196 /* Generic includes */
197 #include <sys/types.h>
200 /* Generic socket object definitions and includes */
201 #define PySocket_BUILDING_SOCKET
202 #include "socketmodule.h"
204 /* Addressing includes */
208 /* Non-MS WINDOWS includes */
211 /* Headers needed for inet_ntoa() and inet_addr() */
213 # include <net/netdb.h>
214 # elif defined(PYOS_OS2) && defined(PYCC_VACPP)
216 typedef size_t socklen_t
;
218 # include <arpa/inet.h>
224 # include <sys/ioctl.h>
225 # include <socklib.h>
227 int h_errno
; /* not used */
228 # define INET_ADDRSTRLEN 16
233 /* MS_WINDOWS includes */
243 # define offsetof(type, member) ((size_t)(&((type *)0)->member))
247 # define O_NONBLOCK O_NDELAY
250 #include "addrinfo.h"
252 #ifndef HAVE_INET_PTON
253 int inet_pton(int af
, const char *src
, void *dst
);
254 const char *inet_ntop(int af
, const void *src
, char *dst
, socklen_t size
);
258 /* On OS X, getaddrinfo returns no error indication of lookup
259 failure, so we must use the emulation instead of the libinfo
260 implementation. Unfortunately, performing an autoconf test
261 for this bug would require DNS access for the machine performing
262 the configuration, which is not acceptable. Therefore, we
263 determine the bug just by checking for __APPLE__. If this bug
264 gets ever fixed, perhaps checking for sys/version.h would be
265 appropriate, which is 10/0 on the system with the bug. */
266 #ifndef HAVE_GETNAMEINFO
267 /* This bug seems to be fixed in Jaguar. Ths easiest way I could
268 Find to check for Jaguar is that it has getnameinfo(), which
269 older releases don't have */
270 #undef HAVE_GETADDRINFO
274 /* I know this is a bad practice, but it is the easiest... */
275 #if !defined(HAVE_GETADDRINFO)
276 /* avoid clashes with the C library definition of the symbol. */
277 #define getaddrinfo fake_getaddrinfo
278 #define gai_strerror fake_gai_strerror
279 #define freeaddrinfo fake_freeaddrinfo
280 #include "getaddrinfo.c"
282 #if !defined(HAVE_GETNAMEINFO)
283 #define getnameinfo fake_getnameinfo
284 #include "getnameinfo.c"
287 #if defined(MS_WINDOWS) || defined(__BEOS__)
288 /* BeOS suffers from the same socket dichotomy as Win32... - [cjh] */
289 /* seem to be a few differences in the API */
290 #define SOCKETCLOSE closesocket
291 #define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */
295 #define EAFNOSUPPORT WSAEAFNOSUPPORT
296 #define snprintf _snprintf
299 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
300 #define SOCKETCLOSE soclose
301 #define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
305 #define SOCKETCLOSE close
309 /* TCP/IP Services for VMS uses a maximum send/revc buffer length of 65535 */
310 #define SEGMENT_SIZE 65535
314 * Constants for getnameinfo()
316 #if !defined(NI_MAXHOST)
317 #define NI_MAXHOST 1025
319 #if !defined(NI_MAXSERV)
320 #define NI_MAXSERV 32
323 /* XXX There's a problem here: *static* functions are not supposed to have
324 a Py prefix (or use CapitalizedWords). Later... */
326 /* Global variable holding the exception type for errors detected
327 by this module (but not argument type or memory errors, etc.). */
328 static PyObject
*socket_error
;
329 static PyObject
*socket_herror
;
330 static PyObject
*socket_gaierror
;
333 /* Global variable which is !=0 if Python is running in a RISC OS taskwindow */
334 static int taskwindow
;
337 /* A forward reference to the socket type object.
338 The sock_type variable contains pointers to various functions,
339 some of which call new_sockobject(), which uses sock_type, so
340 there has to be a circular reference. */
341 static PyTypeObject sock_type
;
343 /* Convenience function to raise an error according to errno
344 and return a NULL pointer from a function. */
350 int err_no
= WSAGetLastError();
355 {WSAEINTR
, "Interrupted system call"},
356 {WSAEBADF
, "Bad file descriptor"},
357 {WSAEACCES
, "Permission denied"},
358 {WSAEFAULT
, "Bad address"},
359 {WSAEINVAL
, "Invalid argument"},
360 {WSAEMFILE
, "Too many open files"},
362 "The socket operation could not complete "
364 {WSAEINPROGRESS
, "Operation now in progress"},
365 {WSAEALREADY
, "Operation already in progress"},
366 {WSAENOTSOCK
, "Socket operation on non-socket"},
367 {WSAEDESTADDRREQ
, "Destination address required"},
368 {WSAEMSGSIZE
, "Message too long"},
369 {WSAEPROTOTYPE
, "Protocol wrong type for socket"},
370 {WSAENOPROTOOPT
, "Protocol not available"},
371 {WSAEPROTONOSUPPORT
, "Protocol not supported"},
372 {WSAESOCKTNOSUPPORT
, "Socket type not supported"},
373 {WSAEOPNOTSUPP
, "Operation not supported"},
374 {WSAEPFNOSUPPORT
, "Protocol family not supported"},
375 {WSAEAFNOSUPPORT
, "Address family not supported"},
376 {WSAEADDRINUSE
, "Address already in use"},
377 {WSAEADDRNOTAVAIL
, "Can't assign requested address"},
378 {WSAENETDOWN
, "Network is down"},
379 {WSAENETUNREACH
, "Network is unreachable"},
380 {WSAENETRESET
, "Network dropped connection on reset"},
381 {WSAECONNABORTED
, "Software caused connection abort"},
382 {WSAECONNRESET
, "Connection reset by peer"},
383 {WSAENOBUFS
, "No buffer space available"},
384 {WSAEISCONN
, "Socket is already connected"},
385 {WSAENOTCONN
, "Socket is not connected"},
386 {WSAESHUTDOWN
, "Can't send after socket shutdown"},
387 {WSAETOOMANYREFS
, "Too many references: can't splice"},
388 {WSAETIMEDOUT
, "Operation timed out"},
389 {WSAECONNREFUSED
, "Connection refused"},
390 {WSAELOOP
, "Too many levels of symbolic links"},
391 {WSAENAMETOOLONG
, "File name too long"},
392 {WSAEHOSTDOWN
, "Host is down"},
393 {WSAEHOSTUNREACH
, "No route to host"},
394 {WSAENOTEMPTY
, "Directory not empty"},
395 {WSAEPROCLIM
, "Too many processes"},
396 {WSAEUSERS
, "Too many users"},
397 {WSAEDQUOT
, "Disc quota exceeded"},
398 {WSAESTALE
, "Stale NFS file handle"},
399 {WSAEREMOTE
, "Too many levels of remote in path"},
400 {WSASYSNOTREADY
, "Network subsystem is unvailable"},
401 {WSAVERNOTSUPPORTED
, "WinSock version is not supported"},
403 "Successful WSAStartup() not yet performed"},
404 {WSAEDISCON
, "Graceful shutdown in progress"},
405 /* Resolver errors */
406 {WSAHOST_NOT_FOUND
, "No such host is known"},
407 {WSATRY_AGAIN
, "Host not found, or server failed"},
408 {WSANO_RECOVERY
, "Unexpected server error encountered"},
409 {WSANO_DATA
, "Valid name without requested data"},
410 {WSANO_ADDRESS
, "No address, look for MX record"},
415 const char *msg
= "winsock error";
417 for (msgp
= msgs
; msgp
->msg
; msgp
++) {
418 if (err_no
== msgp
->no
) {
424 v
= Py_BuildValue("(is)", err_no
, msg
);
426 PyErr_SetObject(socket_error
, v
);
434 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
435 if (sock_errno() != NO_ERROR
) {
439 int myerrorcode
= sock_errno();
441 /* Retrieve socket-related error message from MPTN.MSG file */
442 rc
= DosGetMessage(NULL
, 0, outbuf
, sizeof(outbuf
),
443 myerrorcode
- SOCBASEERR
+ 26,
446 if (rc
== NO_ERROR
) {
449 /* OS/2 doesn't guarantee a terminator */
450 outbuf
[msglen
] = '\0';
451 if (strlen(outbuf
) > 0) {
452 /* If non-empty msg, trim CRLF */
453 char *lastc
= &outbuf
[ strlen(outbuf
)-1 ];
454 while (lastc
> outbuf
&& isspace(*lastc
)) {
455 /* Trim trailing whitespace (CRLF) */
459 v
= Py_BuildValue("(is)", myerrorcode
, outbuf
);
461 PyErr_SetObject(socket_error
, v
);
470 if (_inet_error
.errnum
!= NULL
) {
472 v
= Py_BuildValue("(is)", errno
, _inet_err());
474 PyErr_SetObject(socket_error
, v
);
481 return PyErr_SetFromErrno(socket_error
);
486 set_herror(int h_error
)
490 #ifdef HAVE_HSTRERROR
491 v
= Py_BuildValue("(is)", h_error
, (char *)hstrerror(h_error
));
493 v
= Py_BuildValue("(is)", h_error
, "host not found");
496 PyErr_SetObject(socket_herror
, v
);
505 set_gaierror(int error
)
510 /* EAI_SYSTEM is not available on Windows XP. */
511 if (error
== EAI_SYSTEM
)
515 #ifdef HAVE_GAI_STRERROR
516 v
= Py_BuildValue("(is)", error
, gai_strerror(error
));
518 v
= Py_BuildValue("(is)", error
, "getaddrinfo failed");
521 PyErr_SetObject(socket_gaierror
, v
);
528 /* Function to perform the setting of socket blocking mode
529 internally. block = (1 | 0). */
531 internal_setblocking(PySocketSockObject
*s
, int block
)
539 Py_BEGIN_ALLOW_THREADS
542 setsockopt(s
->sock_fd
, SOL_SOCKET
, SO_NONBLOCK
,
543 (void *)(&block
), sizeof(int));
547 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
549 ioctl(s
->sock_fd
, FIONBIO
, (caddr_t
)&block
, sizeof(block
));
552 ioctl(s
->sock_fd
, FIONBIO
, (char *)&block
);
553 #else /* !PYOS_OS2 && !_VMS */
554 delay_flag
= fcntl(s
->sock_fd
, F_GETFL
, 0);
556 delay_flag
&= (~O_NONBLOCK
);
558 delay_flag
|= O_NONBLOCK
;
559 fcntl(s
->sock_fd
, F_SETFL
, delay_flag
);
560 #endif /* !PYOS_OS2 */
561 #else /* MS_WINDOWS */
563 ioctlsocket(s
->sock_fd
, FIONBIO
, (u_long
*)&block
);
564 #endif /* MS_WINDOWS */
567 socketioctl(s
->sock_fd
, FIONBIO
, (u_long
*)&block
);
569 #endif /* __BEOS__ */
572 /* Since these don't return anything */
576 /* Do a select() on the socket, if necessary (sock_timeout > 0).
577 The argument writing indicates the direction.
578 This does not raise an exception or return a success indicator;
579 we'll let the actual socket call do that. */
581 internal_select(PySocketSockObject
*s
, int writing
)
586 /* Nothing to do unless we're in timeout mode (not non-blocking) */
587 if (s
->sock_timeout
<= 0.0)
590 /* Guard against closed socket */
594 /* Construct the arguments to select */
595 tv
.tv_sec
= (int)s
->sock_timeout
;
596 tv
.tv_usec
= (int)((s
->sock_timeout
- tv
.tv_sec
) * 1e6
);
598 FD_SET(s
->sock_fd
, &fds
);
600 /* See if the socket is ready */
602 select(s
->sock_fd
+1, NULL
, &fds
, NULL
, &tv
);
604 select(s
->sock_fd
+1, &fds
, NULL
, NULL
, &tv
);
607 /* Initialize a new socket object. */
609 static double defaulttimeout
= -1.0; /* Default timeout for new sockets */
612 init_sockobject(PySocketSockObject
*s
,
613 SOCKET_T fd
, int family
, int type
, int proto
)
619 s
->sock_family
= family
;
621 s
->sock_proto
= proto
;
622 s
->sock_timeout
= defaulttimeout
;
624 s
->errorhandler
= &set_error
;
626 if (defaulttimeout
>= 0.0)
627 internal_setblocking(s
, 0);
631 socketioctl(s
->sock_fd
, 0x80046679, (u_long
*)&block
);
636 /* Create a new socket object.
637 This just creates the object and initializes it.
638 If the creation fails, return NULL and set an exception (implicit
641 static PySocketSockObject
*
642 new_sockobject(SOCKET_T fd
, int family
, int type
, int proto
)
644 PySocketSockObject
*s
;
645 s
= (PySocketSockObject
*)
646 PyType_GenericNew(&sock_type
, NULL
, NULL
);
648 init_sockobject(s
, fd
, family
, type
, proto
);
653 /* Lock to allow python interpreter to continue, but only allow one
654 thread to be in gethostbyname or getaddrinfo */
655 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
656 PyThread_type_lock netdb_lock
;
660 /* Convert a string specifying a host name or one of a few symbolic
661 names to a numeric IP address. This usually calls gethostbyname()
662 to do the work; the names "" and "<broadcast>" are special.
663 Return the length (IPv4 should be 4 bytes), or negative if
664 an error occurred; then an exception is raised. */
667 setipaddr(char *name
, struct sockaddr
*addr_ret
, size_t addr_ret_size
, int af
)
669 struct addrinfo hints
, *res
;
674 memset((void *) addr_ret
, '\0', sizeof(*addr_ret
));
675 if (name
[0] == '\0') {
677 memset(&hints
, 0, sizeof(hints
));
678 hints
.ai_family
= af
;
679 hints
.ai_socktype
= SOCK_DGRAM
; /*dummy*/
680 hints
.ai_flags
= AI_PASSIVE
;
681 Py_BEGIN_ALLOW_THREADS
682 ACQUIRE_GETADDRINFO_LOCK
683 error
= getaddrinfo(NULL
, "0", &hints
, &res
);
685 /* We assume that those thread-unsafe getaddrinfo() versions
686 *are* safe regarding their return value, ie. that a
687 subsequent call to getaddrinfo() does not destroy the
688 outcome of the first call. */
689 RELEASE_GETADDRINFO_LOCK
694 switch (res
->ai_family
) {
705 PyErr_SetString(socket_error
,
706 "unsupported address family");
711 PyErr_SetString(socket_error
,
712 "wildcard resolved to multiple address");
715 if (res
->ai_addrlen
< addr_ret_size
)
716 addr_ret_size
= res
->ai_addrlen
;
717 memcpy(addr_ret
, res
->ai_addr
, addr_ret_size
);
721 if (name
[0] == '<' && strcmp(name
, "<broadcast>") == 0) {
722 struct sockaddr_in
*sin
;
723 if (af
!= AF_INET
&& af
!= AF_UNSPEC
) {
724 PyErr_SetString(socket_error
,
725 "address family mismatched");
728 sin
= (struct sockaddr_in
*)addr_ret
;
729 memset((void *) sin
, '\0', sizeof(*sin
));
730 sin
->sin_family
= AF_INET
;
731 #ifdef HAVE_SOCKADDR_SA_LEN
732 sin
->sin_len
= sizeof(*sin
);
734 sin
->sin_addr
.s_addr
= INADDR_BROADCAST
;
735 return sizeof(sin
->sin_addr
);
737 if (sscanf(name
, "%d.%d.%d.%d%c", &d1
, &d2
, &d3
, &d4
, &ch
) == 4 &&
738 0 <= d1
&& d1
<= 255 && 0 <= d2
&& d2
<= 255 &&
739 0 <= d3
&& d3
<= 255 && 0 <= d4
&& d4
<= 255) {
740 struct sockaddr_in
*sin
;
741 sin
= (struct sockaddr_in
*)addr_ret
;
742 sin
->sin_addr
.s_addr
= htonl(
743 ((long) d1
<< 24) | ((long) d2
<< 16) |
744 ((long) d3
<< 8) | ((long) d4
<< 0));
745 sin
->sin_family
= AF_INET
;
746 #ifdef HAVE_SOCKADDR_SA_LEN
747 sin
->sin_len
= sizeof(*sin
);
751 memset(&hints
, 0, sizeof(hints
));
752 hints
.ai_family
= af
;
753 Py_BEGIN_ALLOW_THREADS
754 ACQUIRE_GETADDRINFO_LOCK
755 error
= getaddrinfo(name
, NULL
, &hints
, &res
);
756 #if defined(__digital__) && defined(__unix__)
757 if (error
== EAI_NONAME
&& af
== AF_UNSPEC
) {
758 /* On Tru64 V5.1, numeric-to-addr conversion fails
759 if no address family is given. Assume IPv4 for now.*/
760 hints
.ai_family
= AF_INET
;
761 error
= getaddrinfo(name
, NULL
, &hints
, &res
);
765 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
770 if (res
->ai_addrlen
< addr_ret_size
)
771 addr_ret_size
= res
->ai_addrlen
;
772 memcpy((char *) addr_ret
, res
->ai_addr
, addr_ret_size
);
774 switch (addr_ret
->sa_family
) {
782 PyErr_SetString(socket_error
, "unknown address family");
788 /* Create a string object representing an IP address.
789 This is always a string of the form 'dd.dd.dd.dd' (with variable
793 makeipaddr(struct sockaddr
*addr
, int addrlen
)
795 char buf
[NI_MAXHOST
];
798 error
= getnameinfo(addr
, addrlen
, buf
, sizeof(buf
), NULL
, 0,
804 return PyString_FromString(buf
);
808 /* Create an object representing the given socket address,
809 suitable for passing it back to bind(), connect() etc.
810 The family field of the sockaddr structure is inspected
811 to determine what kind of address it really is. */
815 makesockaddr(int sockfd
, struct sockaddr
*addr
, int addrlen
)
818 /* No address -- may be recvfrom() from known socket */
824 /* XXX: BeOS version of accept() doesn't set family correctly */
825 addr
->sa_family
= AF_INET
;
828 switch (addr
->sa_family
) {
832 struct sockaddr_in
*a
;
833 PyObject
*addrobj
= makeipaddr(addr
, sizeof(*a
));
834 PyObject
*ret
= NULL
;
836 a
= (struct sockaddr_in
*)addr
;
837 ret
= Py_BuildValue("Oi", addrobj
, ntohs(a
->sin_port
));
843 #if defined(AF_UNIX) && !defined(PYOS_OS2)
846 struct sockaddr_un
*a
= (struct sockaddr_un
*) addr
;
847 return PyString_FromString(a
->sun_path
);
854 struct sockaddr_in6
*a
;
855 PyObject
*addrobj
= makeipaddr(addr
, sizeof(*a
));
856 PyObject
*ret
= NULL
;
858 a
= (struct sockaddr_in6
*)addr
;
859 ret
= Py_BuildValue("Oiii",
870 #ifdef HAVE_NETPACKET_PACKET_H
873 struct sockaddr_ll
*a
= (struct sockaddr_ll
*)addr
;
876 /* need to look up interface name give index */
877 if (a
->sll_ifindex
) {
878 ifr
.ifr_ifindex
= a
->sll_ifindex
;
879 if (ioctl(sockfd
, SIOCGIFNAME
, &ifr
) == 0)
880 ifname
= ifr
.ifr_name
;
882 return Py_BuildValue("shbhs#",
884 ntohs(a
->sll_protocol
),
892 /* More cases here... */
895 /* If we don't know the address family, don't raise an
896 exception -- return it as a tuple. */
897 return Py_BuildValue("is#",
900 sizeof(addr
->sa_data
));
906 /* Parse a socket address argument according to the socket object's
907 address family. Return 1 if the address was in the proper format,
908 0 of not. The address is returned through addr_ret, its length
912 getsockaddrarg(PySocketSockObject
*s
, PyObject
*args
,
913 struct sockaddr
**addr_ret
, int *len_ret
)
915 switch (s
->sock_family
) {
917 #if defined(AF_UNIX) && !defined(PYOS_OS2)
920 struct sockaddr_un
* addr
;
923 addr
= (struct sockaddr_un
*)&(s
->sock_addr
).un
;
924 if (!PyArg_Parse(args
, "t#", &path
, &len
))
926 if (len
> sizeof addr
->sun_path
) {
927 PyErr_SetString(socket_error
,
928 "AF_UNIX path too long");
931 addr
->sun_family
= s
->sock_family
;
932 memcpy(addr
->sun_path
, path
, len
);
933 addr
->sun_path
[len
] = 0;
934 *addr_ret
= (struct sockaddr
*) addr
;
935 *len_ret
= len
+ sizeof(*addr
) - sizeof(addr
->sun_path
);
942 struct sockaddr_in
* addr
;
945 addr
=(struct sockaddr_in
*)&(s
->sock_addr
).in
;
946 if (!PyTuple_Check(args
)) {
950 "AF_INET address must be tuple, not %.500s",
951 args
->ob_type
->tp_name
);
954 if (!PyArg_ParseTuple(args
, "eti:getsockaddrarg",
955 "idna", &host
, &port
))
957 if (setipaddr(host
, (struct sockaddr
*)addr
, sizeof(*addr
), AF_INET
) < 0)
959 addr
->sin_family
= AF_INET
;
960 addr
->sin_port
= htons((short)port
);
961 *addr_ret
= (struct sockaddr
*) addr
;
962 *len_ret
= sizeof *addr
;
969 struct sockaddr_in6
* addr
;
971 int port
, flowinfo
, scope_id
;
972 addr
= (struct sockaddr_in6
*)&(s
->sock_addr
).in6
;
973 flowinfo
= scope_id
= 0;
974 if (!PyArg_ParseTuple(args
, "eti|ii",
975 "idna", &host
, &port
, &flowinfo
,
979 if (setipaddr(host
, (struct sockaddr
*)addr
, sizeof(*addr
), AF_INET6
) < 0)
981 addr
->sin6_family
= s
->sock_family
;
982 addr
->sin6_port
= htons((short)port
);
983 addr
->sin6_flowinfo
= flowinfo
;
984 addr
->sin6_scope_id
= scope_id
;
985 *addr_ret
= (struct sockaddr
*) addr
;
986 *len_ret
= sizeof *addr
;
991 #ifdef HAVE_NETPACKET_PACKET_H
994 struct sockaddr_ll
* addr
;
1002 if (!PyArg_ParseTuple(args
, "si|iis", &interfaceName
,
1003 &protoNumber
, &pkttype
, &hatype
, &haddr
))
1005 strncpy(ifr
.ifr_name
, interfaceName
, sizeof(ifr
.ifr_name
));
1006 ifr
.ifr_name
[(sizeof(ifr
.ifr_name
))-1] = '\0';
1007 if (ioctl(s
->sock_fd
, SIOCGIFINDEX
, &ifr
) < 0) {
1011 addr
= &(s
->sock_addr
.ll
);
1012 addr
->sll_family
= AF_PACKET
;
1013 addr
->sll_protocol
= htons((short)protoNumber
);
1014 addr
->sll_ifindex
= ifr
.ifr_ifindex
;
1015 addr
->sll_pkttype
= pkttype
;
1016 addr
->sll_hatype
= hatype
;
1017 *addr_ret
= (struct sockaddr
*) addr
;
1018 *len_ret
= sizeof *addr
;
1023 /* More cases here... */
1026 PyErr_SetString(socket_error
, "getsockaddrarg: bad family");
1033 /* Get the address length according to the socket object's address family.
1034 Return 1 if the family is known, 0 otherwise. The length is returned
1038 getsockaddrlen(PySocketSockObject
*s
, socklen_t
*len_ret
)
1040 switch (s
->sock_family
) {
1042 #if defined(AF_UNIX) && !defined(PYOS_OS2)
1045 *len_ret
= sizeof (struct sockaddr_un
);
1048 #endif /* AF_UNIX */
1052 *len_ret
= sizeof (struct sockaddr_in
);
1059 *len_ret
= sizeof (struct sockaddr_in6
);
1064 #ifdef HAVE_NETPACKET_PACKET_H
1067 *len_ret
= sizeof (struct sockaddr_ll
);
1072 /* More cases here... */
1075 PyErr_SetString(socket_error
, "getsockaddrlen: bad family");
1082 /* s.accept() method */
1085 sock_accept(PySocketSockObject
*s
)
1090 PyObject
*sock
= NULL
;
1091 PyObject
*addr
= NULL
;
1092 PyObject
*res
= NULL
;
1094 if (!getsockaddrlen(s
, &addrlen
))
1096 memset(addrbuf
, 0, addrlen
);
1098 Py_BEGIN_ALLOW_THREADS
1099 internal_select(s
, 0);
1100 newfd
= accept(s
->sock_fd
, (struct sockaddr
*) addrbuf
, &addrlen
);
1101 Py_END_ALLOW_THREADS
1104 if (newfd
== INVALID_SOCKET
)
1108 return s
->errorhandler();
1110 /* Create the new object with unspecified family,
1111 to avoid calls to bind() etc. on it. */
1112 sock
= (PyObject
*) new_sockobject(newfd
,
1121 addr
= makesockaddr(s
->sock_fd
, (struct sockaddr
*)addrbuf
,
1126 res
= Py_BuildValue("OO", sock
, addr
);
1134 PyDoc_STRVAR(accept_doc
,
1135 "accept() -> (socket object, address info)\n\
1137 Wait for an incoming connection. Return a new socket representing the\n\
1138 connection, and the address of the client. For IP sockets, the address\n\
1139 info is a pair (hostaddr, port).");
1141 /* s.setblocking(flag) method. Argument:
1142 False -- non-blocking mode; same as settimeout(0)
1143 True -- blocking mode; same as settimeout(None)
1147 sock_setblocking(PySocketSockObject
*s
, PyObject
*arg
)
1151 block
= PyInt_AsLong(arg
);
1152 if (block
== -1 && PyErr_Occurred())
1155 s
->sock_timeout
= block
? -1.0 : 0.0;
1156 internal_setblocking(s
, block
);
1162 PyDoc_STRVAR(setblocking_doc
,
1163 "setblocking(flag)\n\
1165 Set the socket to blocking (flag is true) or non-blocking (false).\n\
1166 setblocking(True) is equivalent to settimeout(None);\n\
1167 setblocking(False) is equivalent to settimeout(0.0).");
1169 /* s.settimeout(timeout) method. Argument:
1170 None -- no timeout, blocking mode; same as setblocking(True)
1171 0.0 -- non-blocking mode; same as setblocking(False)
1172 > 0 -- timeout mode; operations time out after timeout seconds
1173 < 0 -- illegal; raises an exception
1176 sock_settimeout(PySocketSockObject
*s
, PyObject
*arg
)
1183 timeout
= PyFloat_AsDouble(arg
);
1184 if (timeout
< 0.0) {
1185 if (!PyErr_Occurred())
1186 PyErr_SetString(PyExc_ValueError
,
1187 "Timeout value out of range");
1192 s
->sock_timeout
= timeout
;
1193 internal_setblocking(s
, timeout
< 0.0);
1199 PyDoc_STRVAR(settimeout_doc
,
1200 "settimeout(timeout)\n\
1202 Set a timeout on socket operations. 'timeout' can be a float,\n\
1203 giving in seconds, or None. Setting a timeout of None disables\n\
1204 the timeout feature and is equivalent to setblocking(1).\n\
1205 Setting a timeout of zero is the same as setblocking(0).");
1207 /* s.gettimeout() method.
1208 Returns the timeout associated with a socket. */
1210 sock_gettimeout(PySocketSockObject
*s
)
1212 if (s
->sock_timeout
< 0.0) {
1217 return PyFloat_FromDouble(s
->sock_timeout
);
1220 PyDoc_STRVAR(gettimeout_doc
,
1221 "gettimeout() -> timeout\n\
1223 Returns the timeout in floating seconds associated with socket \n\
1224 operations. A timeout of None indicates that timeouts on socket \n\
1225 operations are disabled.");
1228 /* s.sleeptaskw(1 | 0) method */
1231 sock_sleeptaskw(PySocketSockObject
*s
,PyObject
*arg
)
1234 block
= PyInt_AsLong(arg
);
1235 if (block
== -1 && PyErr_Occurred())
1237 Py_BEGIN_ALLOW_THREADS
1238 socketioctl(s
->sock_fd
, 0x80046679, (u_long
*)&block
);
1239 Py_END_ALLOW_THREADS
1244 PyDoc_STRVAR(sleeptaskw_doc
,
1245 "sleeptaskw(flag)\n\
1247 Allow sleeps in taskwindows.");
1251 /* s.setsockopt() method.
1252 With an integer third argument, sets an integer option.
1253 With a string third argument, sets an option from a buffer;
1254 use optional built-in module 'struct' to encode the string. */
1257 sock_setsockopt(PySocketSockObject
*s
, PyObject
*args
)
1266 if (PyArg_ParseTuple(args
, "iii:setsockopt",
1267 &level
, &optname
, &flag
)) {
1268 buf
= (char *) &flag
;
1269 buflen
= sizeof flag
;
1273 if (!PyArg_ParseTuple(args
, "iis#:setsockopt",
1274 &level
, &optname
, &buf
, &buflen
))
1277 res
= setsockopt(s
->sock_fd
, level
, optname
, (void *)buf
, buflen
);
1279 return s
->errorhandler();
1284 PyDoc_STRVAR(setsockopt_doc
,
1285 "setsockopt(level, option, value)\n\
1287 Set a socket option. See the Unix manual for level and option.\n\
1288 The value argument can either be an integer or a string.");
1291 /* s.getsockopt() method.
1292 With two arguments, retrieves an integer option.
1293 With a third integer argument, retrieves a string buffer of that size;
1294 use optional built-in module 'struct' to decode the string. */
1297 sock_getsockopt(PySocketSockObject
*s
, PyObject
*args
)
1303 socklen_t buflen
= 0;
1306 /* We have incomplete socket support. */
1307 PyErr_SetString(socket_error
, "getsockopt not supported");
1311 if (!PyArg_ParseTuple(args
, "ii|i:getsockopt",
1312 &level
, &optname
, &buflen
))
1317 socklen_t flagsize
= sizeof flag
;
1318 res
= getsockopt(s
->sock_fd
, level
, optname
,
1319 (void *)&flag
, &flagsize
);
1321 return s
->errorhandler();
1322 return PyInt_FromLong(flag
);
1325 if (buflen
> 1024) {
1327 if (buflen
<= 0 || buflen
> 1024) {
1329 PyErr_SetString(socket_error
,
1330 "getsockopt buflen out of range");
1333 buf
= PyString_FromStringAndSize((char *)NULL
, buflen
);
1336 res
= getsockopt(s
->sock_fd
, level
, optname
,
1337 (void *)PyString_AS_STRING(buf
), &buflen
);
1340 return s
->errorhandler();
1342 _PyString_Resize(&buf
, buflen
);
1344 #endif /* __BEOS__ */
1347 PyDoc_STRVAR(getsockopt_doc
,
1348 "getsockopt(level, option[, buffersize]) -> value\n\
1350 Get a socket option. See the Unix manual for level and option.\n\
1351 If a nonzero buffersize argument is given, the return value is a\n\
1352 string of that length; otherwise it is an integer.");
1355 /* s.bind(sockaddr) method */
1358 sock_bind(PySocketSockObject
*s
, PyObject
*addro
)
1360 struct sockaddr
*addr
;
1364 if (!getsockaddrarg(s
, addro
, &addr
, &addrlen
))
1366 Py_BEGIN_ALLOW_THREADS
1367 res
= bind(s
->sock_fd
, addr
, addrlen
);
1368 Py_END_ALLOW_THREADS
1370 return s
->errorhandler();
1375 PyDoc_STRVAR(bind_doc
,
1378 Bind the socket to a local address. For IP sockets, the address is a\n\
1379 pair (host, port); the host must refer to the local host. For raw packet\n\
1380 sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");
1383 /* s.close() method.
1384 Set the file descriptor to -1 so operations tried subsequently
1385 will surely fail. */
1388 sock_close(PySocketSockObject
*s
)
1392 if ((fd
= s
->sock_fd
) != -1) {
1394 Py_BEGIN_ALLOW_THREADS
1395 (void) SOCKETCLOSE(fd
);
1396 Py_END_ALLOW_THREADS
1402 PyDoc_STRVAR(close_doc
,
1405 Close the socket. It cannot be used after this call.");
1408 internal_connect(PySocketSockObject
*s
, struct sockaddr
*addr
, int addrlen
)
1412 res
= connect(s
->sock_fd
, addr
, addrlen
);
1416 if (s
->sock_timeout
> 0.0) {
1417 if (res
< 0 && WSAGetLastError() == WSAEWOULDBLOCK
) {
1418 /* This is a mess. Best solution: trust select */
1421 tv
.tv_sec
= (int)s
->sock_timeout
;
1422 tv
.tv_usec
= (int)((s
->sock_timeout
- tv
.tv_sec
) * 1e6
);
1424 FD_SET(s
->sock_fd
, &fds
);
1425 res
= select(s
->sock_fd
+1, NULL
, &fds
, NULL
, &tv
);
1427 res
= WSAEWOULDBLOCK
;
1430 /* else if (res < 0) an error occurred */
1435 res
= WSAGetLastError();
1439 if (s
->sock_timeout
> 0.0) {
1440 if (res
< 0 && errno
== EINPROGRESS
) {
1441 internal_select(s
, 1);
1442 res
= connect(s
->sock_fd
, addr
, addrlen
);
1443 if (res
< 0 && errno
== EISCONN
)
1456 /* s.connect(sockaddr) method */
1459 sock_connect(PySocketSockObject
*s
, PyObject
*addro
)
1461 struct sockaddr
*addr
;
1465 if (!getsockaddrarg(s
, addro
, &addr
, &addrlen
))
1468 Py_BEGIN_ALLOW_THREADS
1469 res
= internal_connect(s
, addr
, addrlen
);
1470 Py_END_ALLOW_THREADS
1473 return s
->errorhandler();
1478 PyDoc_STRVAR(connect_doc
,
1479 "connect(address)\n\
1481 Connect the socket to a remote address. For IP sockets, the address\n\
1482 is a pair (host, port).");
1485 /* s.connect_ex(sockaddr) method */
1488 sock_connect_ex(PySocketSockObject
*s
, PyObject
*addro
)
1490 struct sockaddr
*addr
;
1494 if (!getsockaddrarg(s
, addro
, &addr
, &addrlen
))
1497 Py_BEGIN_ALLOW_THREADS
1498 res
= internal_connect(s
, addr
, addrlen
);
1499 Py_END_ALLOW_THREADS
1501 return PyInt_FromLong((long) res
);
1504 PyDoc_STRVAR(connect_ex_doc
,
1505 "connect_ex(address) -> errno\n\
1507 This is like connect(address), but returns an error code (the errno value)\n\
1508 instead of raising an exception when an error occurs.");
1511 /* s.fileno() method */
1514 sock_fileno(PySocketSockObject
*s
)
1516 #if SIZEOF_SOCKET_T <= SIZEOF_LONG
1517 return PyInt_FromLong((long) s
->sock_fd
);
1519 return PyLong_FromLongLong((PY_LONG_LONG
)s
->sock_fd
);
1523 PyDoc_STRVAR(fileno_doc
,
1524 "fileno() -> integer\n\
1526 Return the integer file descriptor of the socket.");
1530 /* s.dup() method */
1533 sock_dup(PySocketSockObject
*s
)
1538 newfd
= dup(s
->sock_fd
);
1540 return s
->errorhandler();
1541 sock
= (PyObject
*) new_sockobject(newfd
,
1550 PyDoc_STRVAR(dup_doc
,
1551 "dup() -> socket object\n\
1553 Return a new socket object connected to the same system resource.");
1558 /* s.getsockname() method */
1561 sock_getsockname(PySocketSockObject
*s
)
1567 if (!getsockaddrlen(s
, &addrlen
))
1569 memset(addrbuf
, 0, addrlen
);
1570 Py_BEGIN_ALLOW_THREADS
1571 res
= getsockname(s
->sock_fd
, (struct sockaddr
*) addrbuf
, &addrlen
);
1572 Py_END_ALLOW_THREADS
1574 return s
->errorhandler();
1575 return makesockaddr(s
->sock_fd
, (struct sockaddr
*) addrbuf
, addrlen
);
1578 PyDoc_STRVAR(getsockname_doc
,
1579 "getsockname() -> address info\n\
1581 Return the address of the local endpoint. For IP sockets, the address\n\
1582 info is a pair (hostaddr, port).");
1585 #ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
1586 /* s.getpeername() method */
1589 sock_getpeername(PySocketSockObject
*s
)
1595 if (!getsockaddrlen(s
, &addrlen
))
1597 memset(addrbuf
, 0, addrlen
);
1598 Py_BEGIN_ALLOW_THREADS
1599 res
= getpeername(s
->sock_fd
, (struct sockaddr
*) addrbuf
, &addrlen
);
1600 Py_END_ALLOW_THREADS
1602 return s
->errorhandler();
1603 return makesockaddr(s
->sock_fd
, (struct sockaddr
*) addrbuf
, addrlen
);
1606 PyDoc_STRVAR(getpeername_doc
,
1607 "getpeername() -> address info\n\
1609 Return the address of the remote endpoint. For IP sockets, the address\n\
1610 info is a pair (hostaddr, port).");
1612 #endif /* HAVE_GETPEERNAME */
1615 /* s.listen(n) method */
1618 sock_listen(PySocketSockObject
*s
, PyObject
*arg
)
1623 backlog
= PyInt_AsLong(arg
);
1624 if (backlog
== -1 && PyErr_Occurred())
1626 Py_BEGIN_ALLOW_THREADS
1629 res
= listen(s
->sock_fd
, backlog
);
1630 Py_END_ALLOW_THREADS
1632 return s
->errorhandler();
1637 PyDoc_STRVAR(listen_doc
,
1640 Enable a server to accept connections. The backlog argument must be at\n\
1641 least 1; it specifies the number of unaccepted connection that the system\n\
1642 will allow before refusing new connections.");
1646 /* s.makefile(mode) method.
1647 Create a new open file object referring to a dupped version of
1648 the socket's file descriptor. (The dup() call is necessary so
1649 that the open file and socket objects may be closed independent
1651 The mode argument specifies 'r' or 'w' passed to fdopen(). */
1654 sock_makefile(PySocketSockObject
*s
, PyObject
*args
)
1656 extern int fclose(FILE *);
1671 if (!PyArg_ParseTuple(args
, "|si:makefile", &mode
, &bufsize
))
1674 if (strcmp(mode
,"rb") == 0) {
1678 if (strcmp(mode
,"wb") == 0) {
1684 if (((fd
= _open_osfhandle(s
->sock_fd
, _O_BINARY
)) < 0) ||
1685 ((fd
= dup(fd
)) < 0) || ((fp
= fdopen(fd
, mode
)) == NULL
))
1687 if ((fd
= dup(s
->sock_fd
)) < 0 || (fp
= fdopen(fd
, mode
)) == NULL
)
1692 return s
->errorhandler();
1695 /* Workaround for bug in Metrowerks MSL vs. GUSI I/O library */
1696 if (strchr(mode
, 'b') != NULL
)
1699 f
= PyFile_FromFile(fp
, "<socket>", mode
, fclose
);
1701 PyFile_SetBufSize(f
, bufsize
);
1705 PyDoc_STRVAR(makefile_doc
,
1706 "makefile([mode[, buffersize]]) -> file object\n\
1708 Return a regular file object corresponding to the socket.\n\
1709 The mode and buffersize arguments are as for the built-in open() function.");
1714 /* s.recv(nbytes [,flags]) method */
1717 sock_recv(PySocketSockObject
*s
, PyObject
*args
)
1719 int len
, n
, flags
= 0;
1726 if (!PyArg_ParseTuple(args
, "i|i:recv", &len
, &flags
))
1730 PyErr_SetString(PyExc_ValueError
,
1731 "negative buffersize in recv");
1735 buf
= PyString_FromStringAndSize((char *) 0, len
);
1740 Py_BEGIN_ALLOW_THREADS
1741 internal_select(s
, 0);
1742 n
= recv(s
->sock_fd
, PyString_AS_STRING(buf
), len
, flags
);
1743 Py_END_ALLOW_THREADS
1747 return s
->errorhandler();
1750 _PyString_Resize(&buf
, n
);
1752 read_buf
= PyString_AsString(buf
);
1754 while (read_length
!= 0) {
1755 unsigned int segment
;
1757 segment
= read_length
/SEGMENT_SIZE
;
1759 segment
= SEGMENT_SIZE
;
1762 segment
= read_length
;
1765 Py_BEGIN_ALLOW_THREADS
1766 internal_select(s
, 0);
1767 n
= recv(s
->sock_fd
, read_buf
, segment
, flags
);
1768 Py_END_ALLOW_THREADS
1772 return s
->errorhandler();
1774 if (n
!= read_length
) {
1779 read_length
-= segment
;
1780 read_buf
+= segment
;
1782 if (_PyString_Resize(&buf
, (read_buf
- PyString_AsString(buf
))) < 0)
1790 PyDoc_STRVAR(recv_doc
,
1791 "recv(buffersize[, flags]) -> data\n\
1793 Receive up to buffersize bytes from the socket. For the optional flags\n\
1794 argument, see the Unix manual. When no data is available, block until\n\
1795 at least one byte is available or until the remote end is closed. When\n\
1796 the remote end is closed and all data is read, return the empty string.");
1799 /* s.recvfrom(nbytes [,flags]) method */
1802 sock_recvfrom(PySocketSockObject
*s
, PyObject
*args
)
1805 PyObject
*buf
= NULL
;
1806 PyObject
*addr
= NULL
;
1807 PyObject
*ret
= NULL
;
1808 int len
, n
, flags
= 0;
1811 if (!PyArg_ParseTuple(args
, "i|i:recvfrom", &len
, &flags
))
1814 if (!getsockaddrlen(s
, &addrlen
))
1816 buf
= PyString_FromStringAndSize((char *) 0, len
);
1820 Py_BEGIN_ALLOW_THREADS
1821 memset(addrbuf
, 0, addrlen
);
1822 internal_select(s
, 0);
1823 n
= recvfrom(s
->sock_fd
, PyString_AS_STRING(buf
), len
, flags
,
1825 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
1826 (struct sockaddr
*)addrbuf
, &addrlen
1828 (void *)addrbuf
, &addrlen
1831 (struct sockaddr
*)addrbuf
, &addrlen
1834 Py_END_ALLOW_THREADS
1838 return s
->errorhandler();
1841 if (n
!= len
&& _PyString_Resize(&buf
, n
) < 0)
1844 if (!(addr
= makesockaddr(s
->sock_fd
, (struct sockaddr
*)addrbuf
,
1848 ret
= Py_BuildValue("OO", buf
, addr
);
1856 PyDoc_STRVAR(recvfrom_doc
,
1857 "recvfrom(buffersize[, flags]) -> (data, address info)\n\
1859 Like recv(buffersize, flags) but also return the sender's address info.");
1861 /* s.send(data [,flags]) method */
1864 sock_send(PySocketSockObject
*s
, PyObject
*args
)
1867 int len
, n
, flags
= 0;
1872 if (!PyArg_ParseTuple(args
, "s#|i:send", &buf
, &len
, &flags
))
1876 Py_BEGIN_ALLOW_THREADS
1877 internal_select(s
, 1);
1878 n
= send(s
->sock_fd
, buf
, len
, flags
);
1879 Py_END_ALLOW_THREADS
1882 return s
->errorhandler();
1884 /* Divide packet into smaller segments for */
1885 /* TCP/IP Services for OpenVMS */
1887 while (send_length
!= 0) {
1888 unsigned int segment
;
1890 segment
= send_length
/ SEGMENT_SIZE
;
1892 segment
= SEGMENT_SIZE
;
1895 segment
= send_length
;
1897 Py_BEGIN_ALLOW_THREADS
1898 internal_select(s
, 1);
1899 n
= send(s
->sock_fd
, buf
, segment
, flags
);
1900 Py_END_ALLOW_THREADS
1902 return s
->errorhandler();
1904 send_length
-= segment
;
1908 return PyInt_FromLong((long)n
);
1911 PyDoc_STRVAR(send_doc
,
1912 "send(data[, flags]) -> count\n\
1914 Send a data string to the socket. For the optional flags\n\
1915 argument, see the Unix manual. Return the number of bytes\n\
1916 sent; this may be less than len(data) if the network is busy.");
1919 /* s.sendall(data [,flags]) method */
1922 sock_sendall(PySocketSockObject
*s
, PyObject
*args
)
1925 int len
, n
, flags
= 0;
1927 if (!PyArg_ParseTuple(args
, "s#|i:sendall", &buf
, &len
, &flags
))
1930 Py_BEGIN_ALLOW_THREADS
1932 internal_select(s
, 1);
1933 n
= send(s
->sock_fd
, buf
, len
, flags
);
1939 Py_END_ALLOW_THREADS
1942 return s
->errorhandler();
1948 PyDoc_STRVAR(sendall_doc
,
1949 "sendall(data[, flags])\n\
1951 Send a data string to the socket. For the optional flags\n\
1952 argument, see the Unix manual. This calls send() repeatedly\n\
1953 until all data is sent. If an error occurs, it's impossible\n\
1954 to tell how much data has been sent.");
1957 /* s.sendto(data, [flags,] sockaddr) method */
1960 sock_sendto(PySocketSockObject
*s
, PyObject
*args
)
1964 struct sockaddr
*addr
;
1965 int addrlen
, len
, n
, flags
;
1968 if (!PyArg_ParseTuple(args
, "s#O:sendto", &buf
, &len
, &addro
)) {
1970 if (!PyArg_ParseTuple(args
, "s#iO:sendto",
1971 &buf
, &len
, &flags
, &addro
))
1975 if (!getsockaddrarg(s
, addro
, &addr
, &addrlen
))
1978 Py_BEGIN_ALLOW_THREADS
1979 internal_select(s
, 1);
1980 n
= sendto(s
->sock_fd
, buf
, len
, flags
, addr
, addrlen
);
1981 Py_END_ALLOW_THREADS
1984 return s
->errorhandler();
1985 return PyInt_FromLong((long)n
);
1988 PyDoc_STRVAR(sendto_doc
,
1989 "sendto(data[, flags], address) -> count\n\
1991 Like send(data, flags) but allows specifying the destination address.\n\
1992 For IP sockets, the address is a pair (hostaddr, port).");
1995 /* s.shutdown(how) method */
1998 sock_shutdown(PySocketSockObject
*s
, PyObject
*arg
)
2003 how
= PyInt_AsLong(arg
);
2004 if (how
== -1 && PyErr_Occurred())
2006 Py_BEGIN_ALLOW_THREADS
2007 res
= shutdown(s
->sock_fd
, how
);
2008 Py_END_ALLOW_THREADS
2010 return s
->errorhandler();
2015 PyDoc_STRVAR(shutdown_doc
,
2018 Shut down the reading side of the socket (flag == 0), the writing side\n\
2019 of the socket (flag == 1), or both ends (flag == 2).");
2022 /* List of methods for socket objects */
2024 static PyMethodDef sock_methods
[] = {
2025 {"accept", (PyCFunction
)sock_accept
, METH_NOARGS
,
2027 {"bind", (PyCFunction
)sock_bind
, METH_O
,
2029 {"close", (PyCFunction
)sock_close
, METH_NOARGS
,
2031 {"connect", (PyCFunction
)sock_connect
, METH_O
,
2033 {"connect_ex", (PyCFunction
)sock_connect_ex
, METH_O
,
2036 {"dup", (PyCFunction
)sock_dup
, METH_NOARGS
,
2039 {"fileno", (PyCFunction
)sock_fileno
, METH_NOARGS
,
2041 #ifdef HAVE_GETPEERNAME
2042 {"getpeername", (PyCFunction
)sock_getpeername
,
2043 METH_NOARGS
, getpeername_doc
},
2045 {"getsockname", (PyCFunction
)sock_getsockname
,
2046 METH_NOARGS
, getsockname_doc
},
2047 {"getsockopt", (PyCFunction
)sock_getsockopt
, METH_VARARGS
,
2049 {"listen", (PyCFunction
)sock_listen
, METH_O
,
2052 {"makefile", (PyCFunction
)sock_makefile
, METH_VARARGS
,
2055 {"recv", (PyCFunction
)sock_recv
, METH_VARARGS
,
2057 {"recvfrom", (PyCFunction
)sock_recvfrom
, METH_VARARGS
,
2059 {"send", (PyCFunction
)sock_send
, METH_VARARGS
,
2061 {"sendall", (PyCFunction
)sock_sendall
, METH_VARARGS
,
2063 {"sendto", (PyCFunction
)sock_sendto
, METH_VARARGS
,
2065 {"setblocking", (PyCFunction
)sock_setblocking
, METH_O
,
2067 {"settimeout", (PyCFunction
)sock_settimeout
, METH_O
,
2069 {"gettimeout", (PyCFunction
)sock_gettimeout
, METH_NOARGS
,
2071 {"setsockopt", (PyCFunction
)sock_setsockopt
, METH_VARARGS
,
2073 {"shutdown", (PyCFunction
)sock_shutdown
, METH_O
,
2076 {"sleeptaskw", (PyCFunction
)sock_sleeptaskw
, METH_O
,
2079 {NULL
, NULL
} /* sentinel */
2083 /* Deallocate a socket object in response to the last Py_DECREF().
2084 First close the file description. */
2087 sock_dealloc(PySocketSockObject
*s
)
2089 if (s
->sock_fd
!= -1)
2090 (void) SOCKETCLOSE(s
->sock_fd
);
2091 s
->ob_type
->tp_free((PyObject
*)s
);
2096 sock_repr(PySocketSockObject
*s
)
2099 #if SIZEOF_SOCKET_T > SIZEOF_LONG
2100 if (s
->sock_fd
> LONG_MAX
) {
2101 /* this can occur on Win64, and actually there is a special
2102 ugly printf formatter for decimal pointer length integer
2103 printing, only bother if necessary*/
2104 PyErr_SetString(PyExc_OverflowError
,
2105 "no printf formatter to display "
2106 "the socket descriptor in decimal");
2112 "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
2113 (long)s
->sock_fd
, s
->sock_family
,
2116 return PyString_FromString(buf
);
2120 /* Create a new, uninitialized socket object. */
2123 sock_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
2127 new = type
->tp_alloc(type
, 0);
2129 ((PySocketSockObject
*)new)->sock_fd
= -1;
2130 ((PySocketSockObject
*)new)->sock_timeout
= -1.0;
2131 ((PySocketSockObject
*)new)->errorhandler
= &set_error
;
2137 /* Initialize a new socket object. */
2141 sock_initobj(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
2143 PySocketSockObject
*s
= (PySocketSockObject
*)self
;
2145 int family
= AF_INET
, type
= SOCK_STREAM
, proto
= 0;
2146 static char *keywords
[] = {"family", "type", "proto", 0};
2148 if (!PyArg_ParseTupleAndKeywords(args
, kwds
,
2149 "|iii:socket", keywords
,
2150 &family
, &type
, &proto
))
2153 Py_BEGIN_ALLOW_THREADS
2154 fd
= socket(family
, type
, proto
);
2155 Py_END_ALLOW_THREADS
2158 if (fd
== INVALID_SOCKET
)
2166 init_sockobject(s
, fd
, family
, type
, proto
);
2167 /* From now on, ignore SIGPIPE and let the error checking
2170 (void) signal(SIGPIPE
, SIG_IGN
);
2178 /* Type object for socket objects. */
2180 static PyTypeObject sock_type
= {
2181 PyObject_HEAD_INIT(0) /* Must fill in type value later */
2183 "_socket.socket", /* tp_name */
2184 sizeof(PySocketSockObject
), /* tp_basicsize */
2185 0, /* tp_itemsize */
2186 (destructor
)sock_dealloc
, /* tp_dealloc */
2191 (reprfunc
)sock_repr
, /* tp_repr */
2192 0, /* tp_as_number */
2193 0, /* tp_as_sequence */
2194 0, /* tp_as_mapping */
2198 PyObject_GenericGetAttr
, /* tp_getattro */
2199 0, /* tp_setattro */
2200 0, /* tp_as_buffer */
2201 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
2202 sock_doc
, /* tp_doc */
2203 0, /* tp_traverse */
2205 0, /* tp_richcompare */
2206 0, /* tp_weaklistoffset */
2208 0, /* tp_iternext */
2209 sock_methods
, /* tp_methods */
2214 0, /* tp_descr_get */
2215 0, /* tp_descr_set */
2216 0, /* tp_dictoffset */
2217 sock_initobj
, /* tp_init */
2218 PyType_GenericAlloc
, /* tp_alloc */
2219 sock_new
, /* tp_new */
2220 PyObject_Del
, /* tp_free */
2224 /* Python interface to gethostname(). */
2228 socket_gethostname(PyObject
*self
, PyObject
*args
)
2232 if (!PyArg_ParseTuple(args
, ":gethostname"))
2234 Py_BEGIN_ALLOW_THREADS
2235 res
= gethostname(buf
, (int) sizeof buf
- 1);
2236 Py_END_ALLOW_THREADS
2239 buf
[sizeof buf
- 1] = '\0';
2240 return PyString_FromString(buf
);
2243 PyDoc_STRVAR(gethostname_doc
,
2244 "gethostname() -> string\n\
2246 Return the current host name.");
2249 /* Python interface to gethostbyname(name). */
2253 socket_gethostbyname(PyObject
*self
, PyObject
*args
)
2257 struct sockaddr_storage addrbuf
;
2259 struct sockaddr_in addrbuf
;
2262 if (!PyArg_ParseTuple(args
, "s:gethostbyname", &name
))
2264 if (setipaddr(name
, (struct sockaddr
*)&addrbuf
, sizeof(addrbuf
), AF_INET
) < 0)
2266 return makeipaddr((struct sockaddr
*)&addrbuf
,
2267 sizeof(struct sockaddr_in
));
2270 PyDoc_STRVAR(gethostbyname_doc
,
2271 "gethostbyname(host) -> address\n\
2273 Return the IP address (a string of the form '255.255.255.255') for a host.");
2276 /* Convenience function common to gethostbyname_ex and gethostbyaddr */
2279 gethost_common(struct hostent
*h
, struct sockaddr
*addr
, int alen
, int af
)
2282 PyObject
*rtn_tuple
= (PyObject
*)NULL
;
2283 PyObject
*name_list
= (PyObject
*)NULL
;
2284 PyObject
*addr_list
= (PyObject
*)NULL
;
2288 /* Let's get real error message to return */
2290 set_herror(h_errno
);
2292 PyErr_SetString(socket_error
, "host not found");
2297 if (h
->h_addrtype
!= af
) {
2298 #ifdef HAVE_STRERROR
2299 /* Let's get real error message to return */
2300 PyErr_SetString(socket_error
,
2301 (char *)strerror(EAFNOSUPPORT
));
2305 "Address family not supported by protocol family");
2313 if (alen
< sizeof(struct sockaddr_in
))
2319 if (alen
< sizeof(struct sockaddr_in6
))
2326 if ((name_list
= PyList_New(0)) == NULL
)
2329 if ((addr_list
= PyList_New(0)) == NULL
)
2332 for (pch
= h
->h_aliases
; *pch
!= NULL
; pch
++) {
2334 tmp
= PyString_FromString(*pch
);
2338 status
= PyList_Append(name_list
, tmp
);
2345 for (pch
= h
->h_addr_list
; *pch
!= NULL
; pch
++) {
2352 struct sockaddr_in sin
;
2353 memset(&sin
, 0, sizeof(sin
));
2354 sin
.sin_family
= af
;
2355 #ifdef HAVE_SOCKADDR_SA_LEN
2356 sin
.sin_len
= sizeof(sin
);
2358 memcpy(&sin
.sin_addr
, *pch
, sizeof(sin
.sin_addr
));
2359 tmp
= makeipaddr((struct sockaddr
*)&sin
, sizeof(sin
));
2361 if (pch
== h
->h_addr_list
&& alen
>= sizeof(sin
))
2362 memcpy((char *) addr
, &sin
, sizeof(sin
));
2369 struct sockaddr_in6 sin6
;
2370 memset(&sin6
, 0, sizeof(sin6
));
2371 sin6
.sin6_family
= af
;
2372 #ifdef HAVE_SOCKADDR_SA_LEN
2373 sin6
.sin6_len
= sizeof(sin6
);
2375 memcpy(&sin6
.sin6_addr
, *pch
, sizeof(sin6
.sin6_addr
));
2376 tmp
= makeipaddr((struct sockaddr
*)&sin6
,
2379 if (pch
== h
->h_addr_list
&& alen
>= sizeof(sin6
))
2380 memcpy((char *) addr
, &sin6
, sizeof(sin6
));
2385 default: /* can't happen */
2386 PyErr_SetString(socket_error
,
2387 "unsupported address family");
2394 status
= PyList_Append(addr_list
, tmp
);
2401 rtn_tuple
= Py_BuildValue("sOO", h
->h_name
, name_list
, addr_list
);
2404 Py_XDECREF(name_list
);
2405 Py_XDECREF(addr_list
);
2410 /* Python interface to gethostbyname_ex(name). */
2414 socket_gethostbyname_ex(PyObject
*self
, PyObject
*args
)
2419 struct sockaddr_storage addr
;
2421 struct sockaddr_in addr
;
2423 struct sockaddr
*sa
;
2425 #ifdef HAVE_GETHOSTBYNAME_R
2426 struct hostent hp_allocated
;
2427 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
2428 struct hostent_data data
;
2431 int buf_len
= (sizeof buf
) - 1;
2434 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2437 #endif /* HAVE_GETHOSTBYNAME_R */
2439 if (!PyArg_ParseTuple(args
, "s:gethostbyname_ex", &name
))
2441 if (setipaddr(name
, (struct sockaddr
*)&addr
, sizeof(addr
), AF_INET
) < 0)
2443 Py_BEGIN_ALLOW_THREADS
2444 #ifdef HAVE_GETHOSTBYNAME_R
2445 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2446 result
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
,
2448 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
2449 h
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
, &errnop
);
2450 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
2451 memset((void *) &data
, '\0', sizeof(data
));
2452 result
= gethostbyname_r(name
, &hp_allocated
, &data
);
2453 h
= (result
!= 0) ? NULL
: &hp_allocated
;
2455 #else /* not HAVE_GETHOSTBYNAME_R */
2456 #ifdef USE_GETHOSTBYNAME_LOCK
2457 PyThread_acquire_lock(netdb_lock
, 1);
2459 h
= gethostbyname(name
);
2460 #endif /* HAVE_GETHOSTBYNAME_R */
2461 Py_END_ALLOW_THREADS
2462 /* Some C libraries would require addr.__ss_family instead of
2464 Therefore, we cast the sockaddr_storage into sockaddr to
2465 access sa_family. */
2466 sa
= (struct sockaddr
*)&addr
;
2467 ret
= gethost_common(h
, (struct sockaddr
*)&addr
, sizeof(addr
),
2469 #ifdef USE_GETHOSTBYNAME_LOCK
2470 PyThread_release_lock(netdb_lock
);
2475 PyDoc_STRVAR(ghbn_ex_doc
,
2476 "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
2478 Return the true host name, a list of aliases, and a list of IP addresses,\n\
2479 for a host. The host argument is a string giving a host name or IP number.");
2482 /* Python interface to gethostbyaddr(IP). */
2486 socket_gethostbyaddr(PyObject
*self
, PyObject
*args
)
2489 struct sockaddr_storage addr
;
2491 struct sockaddr_in addr
;
2493 struct sockaddr
*sa
= (struct sockaddr
*)&addr
;
2497 #ifdef HAVE_GETHOSTBYNAME_R
2498 struct hostent hp_allocated
;
2499 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
2500 struct hostent_data data
;
2503 int buf_len
= (sizeof buf
) - 1;
2506 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2509 #endif /* HAVE_GETHOSTBYNAME_R */
2514 if (!PyArg_ParseTuple(args
, "s:gethostbyaddr", &ip_num
))
2517 if (setipaddr(ip_num
, sa
, sizeof(addr
), af
) < 0)
2524 ap
= (char *)&((struct sockaddr_in
*)sa
)->sin_addr
;
2525 al
= sizeof(((struct sockaddr_in
*)sa
)->sin_addr
);
2529 ap
= (char *)&((struct sockaddr_in6
*)sa
)->sin6_addr
;
2530 al
= sizeof(((struct sockaddr_in6
*)sa
)->sin6_addr
);
2534 PyErr_SetString(socket_error
, "unsupported address family");
2537 Py_BEGIN_ALLOW_THREADS
2538 #ifdef HAVE_GETHOSTBYNAME_R
2539 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2540 result
= gethostbyaddr_r(ap
, al
, af
,
2541 &hp_allocated
, buf
, buf_len
,
2543 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
2544 h
= gethostbyaddr_r(ap
, al
, af
,
2545 &hp_allocated
, buf
, buf_len
, &errnop
);
2546 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
2547 memset((void *) &data
, '\0', sizeof(data
));
2548 result
= gethostbyaddr_r(ap
, al
, af
, &hp_allocated
, &data
);
2549 h
= (result
!= 0) ? NULL
: &hp_allocated
;
2551 #else /* not HAVE_GETHOSTBYNAME_R */
2552 #ifdef USE_GETHOSTBYNAME_LOCK
2553 PyThread_acquire_lock(netdb_lock
, 1);
2555 h
= gethostbyaddr(ap
, al
, af
);
2556 #endif /* HAVE_GETHOSTBYNAME_R */
2557 Py_END_ALLOW_THREADS
2558 ret
= gethost_common(h
, (struct sockaddr
*)&addr
, sizeof(addr
), af
);
2559 #ifdef USE_GETHOSTBYNAME_LOCK
2560 PyThread_release_lock(netdb_lock
);
2565 PyDoc_STRVAR(gethostbyaddr_doc
,
2566 "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
2568 Return the true host name, a list of aliases, and a list of IP addresses,\n\
2569 for a host. The host argument is a string giving a host name or IP number.");
2572 /* Python interface to getservbyname(name).
2573 This only returns the port number, since the other info is already
2574 known or not useful (like the list of aliases). */
2578 socket_getservbyname(PyObject
*self
, PyObject
*args
)
2582 if (!PyArg_ParseTuple(args
, "ss:getservbyname", &name
, &proto
))
2584 Py_BEGIN_ALLOW_THREADS
2585 sp
= getservbyname(name
, proto
);
2586 Py_END_ALLOW_THREADS
2588 PyErr_SetString(socket_error
, "service/proto not found");
2591 return PyInt_FromLong((long) ntohs(sp
->s_port
));
2594 PyDoc_STRVAR(getservbyname_doc
,
2595 "getservbyname(servicename, protocolname) -> integer\n\
2597 Return a port number from a service name and protocol name.\n\
2598 The protocol name should be 'tcp' or 'udp'.");
2601 /* Python interface to getprotobyname(name).
2602 This only returns the protocol number, since the other info is
2603 already known or not useful (like the list of aliases). */
2607 socket_getprotobyname(PyObject
*self
, PyObject
*args
)
2610 struct protoent
*sp
;
2612 /* Not available in BeOS yet. - [cjh] */
2613 PyErr_SetString(socket_error
, "getprotobyname not supported");
2616 if (!PyArg_ParseTuple(args
, "s:getprotobyname", &name
))
2618 Py_BEGIN_ALLOW_THREADS
2619 sp
= getprotobyname(name
);
2620 Py_END_ALLOW_THREADS
2622 PyErr_SetString(socket_error
, "protocol not found");
2625 return PyInt_FromLong((long) sp
->p_proto
);
2629 PyDoc_STRVAR(getprotobyname_doc
,
2630 "getprotobyname(name) -> integer\n\
2632 Return the protocol number for the named protocol. (Rarely used.)");
2636 /* Create a socket object from a numeric file description.
2637 Useful e.g. if stdin is a socket.
2638 Additional arguments as for socket(). */
2642 socket_fromfd(PyObject
*self
, PyObject
*args
)
2644 PySocketSockObject
*s
;
2646 int family
, type
, proto
= 0;
2647 if (!PyArg_ParseTuple(args
, "iii|i:fromfd",
2648 &fd
, &family
, &type
, &proto
))
2650 /* Dup the fd so it and the socket can be closed independently */
2654 s
= new_sockobject(fd
, family
, type
, proto
);
2655 /* From now on, ignore SIGPIPE and let the error checking
2658 (void) signal(SIGPIPE
, SIG_IGN
);
2660 return (PyObject
*) s
;
2663 PyDoc_STRVAR(fromfd_doc
,
2664 "fromfd(fd, family, type[, proto]) -> socket object\n\
2666 Create a socket object from the given file descriptor.\n\
2667 The remaining arguments are the same as for socket().");
2673 socket_ntohs(PyObject
*self
, PyObject
*args
)
2677 if (!PyArg_ParseTuple(args
, "i:ntohs", &x1
)) {
2680 x2
= (int)ntohs((short)x1
);
2681 return PyInt_FromLong(x2
);
2684 PyDoc_STRVAR(ntohs_doc
,
2685 "ntohs(integer) -> integer\n\
2687 Convert a 16-bit integer from network to host byte order.");
2691 socket_ntohl(PyObject
*self
, PyObject
*arg
)
2695 if (PyInt_Check(arg
)) {
2696 x
= PyInt_AS_LONG(arg
);
2697 if (x
== (unsigned long) -1 && PyErr_Occurred())
2700 else if (PyLong_Check(arg
)) {
2701 x
= PyLong_AsUnsignedLong(arg
);
2702 if (x
== (unsigned long) -1 && PyErr_Occurred())
2707 /* only want the trailing 32 bits */
2708 y
= x
& 0xFFFFFFFFUL
;
2710 return PyErr_Format(PyExc_OverflowError
,
2711 "long int larger than 32 bits");
2717 return PyErr_Format(PyExc_TypeError
,
2718 "expected int/long, %s found",
2719 arg
->ob_type
->tp_name
);
2720 if (x
== (unsigned long) -1 && PyErr_Occurred())
2722 return PyInt_FromLong(ntohl(x
));
2725 PyDoc_STRVAR(ntohl_doc
,
2726 "ntohl(integer) -> integer\n\
2728 Convert a 32-bit integer from network to host byte order.");
2732 socket_htons(PyObject
*self
, PyObject
*args
)
2734 unsigned long x1
, x2
;
2736 if (!PyArg_ParseTuple(args
, "i:htons", &x1
)) {
2739 x2
= (int)htons((short)x1
);
2740 return PyInt_FromLong(x2
);
2743 PyDoc_STRVAR(htons_doc
,
2744 "htons(integer) -> integer\n\
2746 Convert a 16-bit integer from host to network byte order.");
2750 socket_htonl(PyObject
*self
, PyObject
*arg
)
2754 if (PyInt_Check(arg
)) {
2755 x
= PyInt_AS_LONG(arg
);
2756 if (x
== (unsigned long) -1 && PyErr_Occurred())
2759 else if (PyLong_Check(arg
)) {
2760 x
= PyLong_AsUnsignedLong(arg
);
2761 if (x
== (unsigned long) -1 && PyErr_Occurred())
2766 /* only want the trailing 32 bits */
2767 y
= x
& 0xFFFFFFFFUL
;
2769 return PyErr_Format(PyExc_OverflowError
,
2770 "long int larger than 32 bits");
2776 return PyErr_Format(PyExc_TypeError
,
2777 "expected int/long, %s found",
2778 arg
->ob_type
->tp_name
);
2779 return PyInt_FromLong(htonl(x
));
2782 PyDoc_STRVAR(htonl_doc
,
2783 "htonl(integer) -> integer\n\
2785 Convert a 32-bit integer from host to network byte order.");
2787 /* socket.inet_aton() and socket.inet_ntoa() functions. */
2789 PyDoc_STRVAR(inet_aton_doc
,
2790 "inet_aton(string) -> packed 32-bit IP representation\n\
2792 Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
2793 binary format used in low-level network functions.");
2796 socket_inet_aton(PyObject
*self
, PyObject
*args
)
2799 #define INADDR_NONE (-1)
2801 #ifdef HAVE_INET_ATON
2804 /* Have to use inet_addr() instead */
2805 unsigned long packed_addr
;
2809 if (!PyArg_ParseTuple(args
, "s:inet_aton", &ip_addr
))
2813 #ifdef HAVE_INET_ATON
2814 if (inet_aton(ip_addr
, &buf
))
2815 return PyString_FromStringAndSize((char *)(&buf
),
2818 PyErr_SetString(socket_error
,
2819 "illegal IP address string passed to inet_aton");
2822 #else /* ! HAVE_INET_ATON */
2823 /* XXX Problem here: inet_aton('255.255.255.255') raises
2824 an exception while it should be a valid address. */
2825 packed_addr
= inet_addr(ip_addr
);
2827 if (packed_addr
== INADDR_NONE
) { /* invalid address */
2828 PyErr_SetString(socket_error
,
2829 "illegal IP address string passed to inet_aton");
2832 return PyString_FromStringAndSize((char *) &packed_addr
,
2833 sizeof(packed_addr
));
2837 PyDoc_STRVAR(inet_ntoa_doc
,
2838 "inet_ntoa(packed_ip) -> ip_address_string\n\
2840 Convert an IP address from 32-bit packed binary format to string format");
2843 socket_inet_ntoa(PyObject
*self
, PyObject
*args
)
2847 struct in_addr packed_addr
;
2849 if (!PyArg_ParseTuple(args
, "s#:inet_ntoa", &packed_str
, &addr_len
)) {
2853 if (addr_len
!= sizeof(packed_addr
)) {
2854 PyErr_SetString(socket_error
,
2855 "packed IP wrong length for inet_ntoa");
2859 memcpy(&packed_addr
, packed_str
, addr_len
);
2861 return PyString_FromString(inet_ntoa(packed_addr
));
2864 #ifdef HAVE_INET_PTON
2866 PyDoc_STRVAR(inet_pton_doc
,
2867 "inet_pton(af, ip) -> packed IP address string\n\
2869 Convert an IP address from string format to a packed string suitable\n\
2870 for use with low-level network functions.");
2873 socket_inet_pton(PyObject
*self
, PyObject
*args
)
2879 char packed
[MAX(sizeof(struct in_addr
), sizeof(struct in6_addr
))];
2881 char packed
[sizeof(struct in_addr
)];
2883 if (!PyArg_ParseTuple(args
, "is:inet_pton", &af
, &ip
)) {
2887 retval
= inet_pton(af
, ip
, packed
);
2889 PyErr_SetFromErrno(socket_error
);
2891 } else if (retval
== 0) {
2892 PyErr_SetString(socket_error
,
2893 "illegal IP address string passed to inet_pton");
2895 } else if (af
== AF_INET
) {
2896 return PyString_FromStringAndSize(packed
,
2897 sizeof(struct in_addr
));
2899 } else if (af
== AF_INET6
) {
2900 return PyString_FromStringAndSize(packed
,
2901 sizeof(struct in6_addr
));
2904 PyErr_SetString(socket_error
, "unknown address family");
2909 PyDoc_STRVAR(inet_ntop_doc
,
2910 "inet_ntop(af, packed_ip) -> string formatted IP address\n\
2912 Convert a packed IP address of the given family to string format.");
2915 socket_inet_ntop(PyObject
*self
, PyObject
*args
)
2922 char ip
[MAX(INET_ADDRSTRLEN
, INET6_ADDRSTRLEN
) + 1];
2924 char ip
[INET_ADDRSTRLEN
+ 1];
2927 /* Guarantee NUL-termination for PyString_FromString() below */
2928 memset((void *) &ip
[0], '\0', sizeof(ip
) + 1);
2930 if (!PyArg_ParseTuple(args
, "is#:inet_ntop", &af
, &packed
, &len
)) {
2934 if (af
== AF_INET
) {
2935 if (len
!= sizeof(struct in_addr
)) {
2936 PyErr_SetString(PyExc_ValueError
,
2937 "invalid length of packed IP address string");
2941 } else if (af
== AF_INET6
) {
2942 if (len
!= sizeof(struct in6_addr
)) {
2943 PyErr_SetString(PyExc_ValueError
,
2944 "invalid length of packed IP address string");
2949 PyErr_Format(PyExc_ValueError
,
2950 "unknown address family %d", af
);
2954 retval
= inet_ntop(af
, packed
, ip
, sizeof(ip
));
2956 PyErr_SetFromErrno(socket_error
);
2959 return PyString_FromString(retval
);
2963 PyErr_SetString(PyExc_RuntimeError
, "invalid handling of inet_ntop");
2967 #endif /* HAVE_INET_PTON */
2969 /* Python interface to getaddrinfo(host, port). */
2973 socket_getaddrinfo(PyObject
*self
, PyObject
*args
)
2975 struct addrinfo hints
, *res
;
2976 struct addrinfo
*res0
= NULL
;
2977 PyObject
*hobj
= NULL
;
2978 PyObject
*pobj
= (PyObject
*)NULL
;
2981 int family
, socktype
, protocol
, flags
;
2983 PyObject
*all
= (PyObject
*)NULL
;
2984 PyObject
*single
= (PyObject
*)NULL
;
2985 PyObject
*idna
= NULL
;
2987 family
= socktype
= protocol
= flags
= 0;
2989 if (!PyArg_ParseTuple(args
, "OO|iiii:getaddrinfo",
2990 &hobj
, &pobj
, &family
, &socktype
,
2991 &protocol
, &flags
)) {
2994 if (hobj
== Py_None
) {
2996 } else if (PyUnicode_Check(hobj
)) {
2997 idna
= PyObject_CallMethod(hobj
, "encode", "s", "idna");
3000 hptr
= PyString_AsString(idna
);
3001 } else if (PyString_Check(hobj
)) {
3002 hptr
= PyString_AsString(hobj
);
3004 PyErr_SetString(PyExc_TypeError
,
3005 "getaddrinfo() argument 1 must be string or None");
3008 if (PyInt_Check(pobj
)) {
3009 PyOS_snprintf(pbuf
, sizeof(pbuf
), "%ld", PyInt_AsLong(pobj
));
3011 } else if (PyString_Check(pobj
)) {
3012 pptr
= PyString_AsString(pobj
);
3013 } else if (pobj
== Py_None
) {
3014 pptr
= (char *)NULL
;
3016 PyErr_SetString(socket_error
, "Int or String expected");
3019 memset(&hints
, 0, sizeof(hints
));
3020 hints
.ai_family
= family
;
3021 hints
.ai_socktype
= socktype
;
3022 hints
.ai_protocol
= protocol
;
3023 hints
.ai_flags
= flags
;
3024 Py_BEGIN_ALLOW_THREADS
3025 ACQUIRE_GETADDRINFO_LOCK
3026 error
= getaddrinfo(hptr
, pptr
, &hints
, &res0
);
3027 Py_END_ALLOW_THREADS
3028 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
3030 set_gaierror(error
);
3034 if ((all
= PyList_New(0)) == NULL
)
3036 for (res
= res0
; res
; res
= res
->ai_next
) {
3038 makesockaddr(-1, res
->ai_addr
, res
->ai_addrlen
);
3041 single
= Py_BuildValue("iiisO", res
->ai_family
,
3042 res
->ai_socktype
, res
->ai_protocol
,
3043 res
->ai_canonname
? res
->ai_canonname
: "",
3049 if (PyList_Append(all
, single
))
3063 return (PyObject
*)NULL
;
3066 PyDoc_STRVAR(getaddrinfo_doc
,
3067 "getaddrinfo(host, port [, family, socktype, proto, flags])\n\
3068 -> list of (family, socktype, proto, canonname, sockaddr)\n\
3070 Resolve host and port into addrinfo struct.");
3072 /* Python interface to getnameinfo(sa, flags). */
3076 socket_getnameinfo(PyObject
*self
, PyObject
*args
)
3078 PyObject
*sa
= (PyObject
*)NULL
;
3081 int port
, flowinfo
, scope_id
;
3082 char hbuf
[NI_MAXHOST
], pbuf
[NI_MAXSERV
];
3083 struct addrinfo hints
, *res
= NULL
;
3085 PyObject
*ret
= (PyObject
*)NULL
;
3087 flags
= flowinfo
= scope_id
= 0;
3088 if (!PyArg_ParseTuple(args
, "Oi:getnameinfo", &sa
, &flags
))
3090 if (!PyArg_ParseTuple(sa
, "si|ii",
3091 &hostp
, &port
, &flowinfo
, &scope_id
))
3093 PyOS_snprintf(pbuf
, sizeof(pbuf
), "%d", port
);
3094 memset(&hints
, 0, sizeof(hints
));
3095 hints
.ai_family
= AF_UNSPEC
;
3096 hints
.ai_socktype
= SOCK_DGRAM
; /* make numeric port happy */
3097 Py_BEGIN_ALLOW_THREADS
3098 ACQUIRE_GETADDRINFO_LOCK
3099 error
= getaddrinfo(hostp
, pbuf
, &hints
, &res
);
3100 Py_END_ALLOW_THREADS
3101 RELEASE_GETADDRINFO_LOCK
/* see comment in setipaddr() */
3103 set_gaierror(error
);
3107 PyErr_SetString(socket_error
,
3108 "sockaddr resolved to multiple addresses");
3111 switch (res
->ai_family
) {
3116 if (PyArg_ParseTuple(sa
, "si", &t1
, &t2
) == 0) {
3117 PyErr_SetString(socket_error
,
3118 "IPv4 sockaddr must be 2 tuple");
3126 struct sockaddr_in6
*sin6
;
3127 sin6
= (struct sockaddr_in6
*)res
->ai_addr
;
3128 sin6
->sin6_flowinfo
= flowinfo
;
3129 sin6
->sin6_scope_id
= scope_id
;
3134 error
= getnameinfo(res
->ai_addr
, res
->ai_addrlen
,
3135 hbuf
, sizeof(hbuf
), pbuf
, sizeof(pbuf
), flags
);
3137 set_gaierror(error
);
3140 ret
= Py_BuildValue("ss", hbuf
, pbuf
);
3148 PyDoc_STRVAR(getnameinfo_doc
,
3149 "getnameinfo(sockaddr, flags) --> (host, port)\n\
3151 Get host and port for a sockaddr.");
3154 /* Python API to getting and setting the default timeout value. */
3157 socket_getdefaulttimeout(PyObject
*self
)
3159 if (defaulttimeout
< 0.0) {
3164 return PyFloat_FromDouble(defaulttimeout
);
3167 PyDoc_STRVAR(getdefaulttimeout_doc
,
3168 "getdefaulttimeout() -> timeout\n\
3170 Returns the default timeout in floating seconds for new socket objects.\n\
3171 A value of None indicates that new socket objects have no timeout.\n\
3172 When the socket module is first imported, the default is None.");
3175 socket_setdefaulttimeout(PyObject
*self
, PyObject
*arg
)
3182 timeout
= PyFloat_AsDouble(arg
);
3183 if (timeout
< 0.0) {
3184 if (!PyErr_Occurred())
3185 PyErr_SetString(PyExc_ValueError
,
3186 "Timeout value out of range");
3191 defaulttimeout
= timeout
;
3197 PyDoc_STRVAR(setdefaulttimeout_doc
,
3198 "setdefaulttimeout(timeout)\n\
3200 Set the default timeout in floating seconds for new socket objects.\n\
3201 A value of None indicates that new socket objects have no timeout.\n\
3202 When the socket module is first imported, the default is None.");
3205 /* List of functions exported by this module. */
3207 static PyMethodDef socket_methods
[] = {
3208 {"gethostbyname", socket_gethostbyname
,
3209 METH_VARARGS
, gethostbyname_doc
},
3210 {"gethostbyname_ex", socket_gethostbyname_ex
,
3211 METH_VARARGS
, ghbn_ex_doc
},
3212 {"gethostbyaddr", socket_gethostbyaddr
,
3213 METH_VARARGS
, gethostbyaddr_doc
},
3214 {"gethostname", socket_gethostname
,
3215 METH_VARARGS
, gethostname_doc
},
3216 {"getservbyname", socket_getservbyname
,
3217 METH_VARARGS
, getservbyname_doc
},
3218 {"getprotobyname", socket_getprotobyname
,
3219 METH_VARARGS
,getprotobyname_doc
},
3221 {"fromfd", socket_fromfd
,
3222 METH_VARARGS
, fromfd_doc
},
3224 {"ntohs", socket_ntohs
,
3225 METH_VARARGS
, ntohs_doc
},
3226 {"ntohl", socket_ntohl
,
3228 {"htons", socket_htons
,
3229 METH_VARARGS
, htons_doc
},
3230 {"htonl", socket_htonl
,
3232 {"inet_aton", socket_inet_aton
,
3233 METH_VARARGS
, inet_aton_doc
},
3234 {"inet_ntoa", socket_inet_ntoa
,
3235 METH_VARARGS
, inet_ntoa_doc
},
3236 #ifdef HAVE_INET_PTON
3237 {"inet_pton", socket_inet_pton
,
3238 METH_VARARGS
, inet_pton_doc
},
3239 {"inet_ntop", socket_inet_ntop
,
3240 METH_VARARGS
, inet_ntop_doc
},
3242 {"getaddrinfo", socket_getaddrinfo
,
3243 METH_VARARGS
, getaddrinfo_doc
},
3244 {"getnameinfo", socket_getnameinfo
,
3245 METH_VARARGS
, getnameinfo_doc
},
3246 {"getdefaulttimeout", (PyCFunction
)socket_getdefaulttimeout
,
3247 METH_NOARGS
, getdefaulttimeout_doc
},
3248 {"setdefaulttimeout", socket_setdefaulttimeout
,
3249 METH_O
, setdefaulttimeout_doc
},
3250 {NULL
, NULL
} /* Sentinel */
3255 #define OS_INIT_DEFINED
3263 _kernel_swi(0x43380, &r
, &r
);
3264 taskwindow
= r
.r
[0];
3273 #define OS_INIT_DEFINED
3275 /* Additional initialization and cleanup for Windows */
3289 ret
= WSAStartup(0x0101, &WSAData
);
3291 case 0: /* No error */
3293 return 1; /* Success */
3294 case WSASYSNOTREADY
:
3295 PyErr_SetString(PyExc_ImportError
,
3296 "WSAStartup failed: network not ready");
3298 case WSAVERNOTSUPPORTED
:
3302 "WSAStartup failed: requested version not supported");
3305 PyOS_snprintf(buf
, sizeof(buf
),
3306 "WSAStartup failed: error code %d", ret
);
3307 PyErr_SetString(PyExc_ImportError
, buf
);
3310 return 0; /* Failure */
3313 #endif /* MS_WINDOWS */
3317 #define OS_INIT_DEFINED
3319 /* Additional initialization for OS/2 */
3326 int rc
= sock_init();
3329 return 1; /* Success */
3332 PyOS_snprintf(reason
, sizeof(reason
),
3333 "OS/2 TCP/IP Error# %d", sock_errno());
3334 PyErr_SetString(PyExc_ImportError
, reason
);
3336 return 0; /* Failure */
3338 /* No need to initialise sockets with GCC/EMX */
3339 return 1; /* Success */
3343 #endif /* PYOS_OS2 */
3346 #ifndef OS_INIT_DEFINED
3350 return 1; /* Success */
3355 /* C API table - always add new things to the end for binary
3358 PySocketModule_APIObject PySocketModuleAPI
=
3364 /* Initialize the _socket module.
3366 This module is actually called "_socket", and there's a wrapper
3367 "socket.py" which implements some additional functionality. On some
3368 platforms (e.g. Windows and OS/2), socket.py also implements a
3369 wrapper for the socket type that provides missing functionality such
3370 as makefile(), dup() and fromfd(). The import of "_socket" may fail
3371 with an ImportError exception if os-specific initialization fails.
3372 On Windows, this does WINSOCK initialization. When WINSOCK is
3373 initialized succesfully, a call to WSACleanup() is scheduled to be
3377 PyDoc_STRVAR(socket_doc
,
3378 "Implementation module for socket operations.\n\
3380 See the socket module for documentation.");
3385 PyObject
*m
, *has_ipv6
;
3390 sock_type
.ob_type
= &PyType_Type
;
3391 m
= Py_InitModule3(PySocket_MODULE_NAME
,
3395 socket_error
= PyErr_NewException("socket.error", NULL
, NULL
);
3396 if (socket_error
== NULL
)
3398 Py_INCREF(socket_error
);
3399 PyModule_AddObject(m
, "error", socket_error
);
3400 socket_herror
= PyErr_NewException("socket.herror",
3401 socket_error
, NULL
);
3402 if (socket_herror
== NULL
)
3404 Py_INCREF(socket_herror
);
3405 PyModule_AddObject(m
, "herror", socket_herror
);
3406 socket_gaierror
= PyErr_NewException("socket.gaierror", socket_error
,
3408 if (socket_gaierror
== NULL
)
3410 Py_INCREF(socket_gaierror
);
3411 PyModule_AddObject(m
, "gaierror", socket_gaierror
);
3412 Py_INCREF((PyObject
*)&sock_type
);
3413 if (PyModule_AddObject(m
, "SocketType",
3414 (PyObject
*)&sock_type
) != 0)
3416 Py_INCREF((PyObject
*)&sock_type
);
3417 if (PyModule_AddObject(m
, "socket",
3418 (PyObject
*)&sock_type
) != 0)
3424 has_ipv6
= Py_False
;
3426 Py_INCREF(has_ipv6
);
3427 PyModule_AddObject(m
, "has_ipv6", has_ipv6
);
3430 if (PyModule_AddObject(m
, PySocket_CAPI_NAME
,
3431 PyCObject_FromVoidPtr((void *)&PySocketModuleAPI
, NULL
)
3435 /* Address families (we only support AF_INET and AF_UNIX) */
3437 PyModule_AddIntConstant(m
, "AF_UNSPEC", AF_UNSPEC
);
3439 PyModule_AddIntConstant(m
, "AF_INET", AF_INET
);
3441 PyModule_AddIntConstant(m
, "AF_INET6", AF_INET6
);
3442 #endif /* AF_INET6 */
3443 #if defined(AF_UNIX) && !defined(PYOS_OS2)
3444 PyModule_AddIntConstant(m
, "AF_UNIX", AF_UNIX
);
3445 #endif /* AF_UNIX */
3447 /* Amateur Radio AX.25 */
3448 PyModule_AddIntConstant(m
, "AF_AX25", AF_AX25
);
3451 PyModule_AddIntConstant(m
, "AF_IPX", AF_IPX
); /* Novell IPX */
3455 PyModule_AddIntConstant(m
, "AF_APPLETALK", AF_APPLETALK
);
3458 /* Amateur radio NetROM */
3459 PyModule_AddIntConstant(m
, "AF_NETROM", AF_NETROM
);
3462 /* Multiprotocol bridge */
3463 PyModule_AddIntConstant(m
, "AF_BRIDGE", AF_BRIDGE
);
3466 /* Reserved for Werner's ATM */
3467 PyModule_AddIntConstant(m
, "AF_AAL5", AF_AAL5
);
3470 /* Reserved for X.25 project */
3471 PyModule_AddIntConstant(m
, "AF_X25", AF_X25
);
3474 PyModule_AddIntConstant(m
, "AF_INET6", AF_INET6
); /* IP version 6 */
3477 /* Amateur Radio X.25 PLP */
3478 PyModule_AddIntConstant(m
, "AF_ROSE", AF_ROSE
);
3480 #ifdef HAVE_NETPACKET_PACKET_H
3481 PyModule_AddIntConstant(m
, "AF_PACKET", AF_PACKET
);
3482 PyModule_AddIntConstant(m
, "PF_PACKET", PF_PACKET
);
3483 PyModule_AddIntConstant(m
, "PACKET_HOST", PACKET_HOST
);
3484 PyModule_AddIntConstant(m
, "PACKET_BROADCAST", PACKET_BROADCAST
);
3485 PyModule_AddIntConstant(m
, "PACKET_MULTICAST", PACKET_MULTICAST
);
3486 PyModule_AddIntConstant(m
, "PACKET_OTHERHOST", PACKET_OTHERHOST
);
3487 PyModule_AddIntConstant(m
, "PACKET_OUTGOING", PACKET_OUTGOING
);
3488 PyModule_AddIntConstant(m
, "PACKET_LOOPBACK", PACKET_LOOPBACK
);
3489 PyModule_AddIntConstant(m
, "PACKET_FASTROUTE", PACKET_FASTROUTE
);
3493 PyModule_AddIntConstant(m
, "SOCK_STREAM", SOCK_STREAM
);
3494 PyModule_AddIntConstant(m
, "SOCK_DGRAM", SOCK_DGRAM
);
3496 /* We have incomplete socket support. */
3497 PyModule_AddIntConstant(m
, "SOCK_RAW", SOCK_RAW
);
3498 PyModule_AddIntConstant(m
, "SOCK_SEQPACKET", SOCK_SEQPACKET
);
3499 #if defined(SOCK_RDM)
3500 PyModule_AddIntConstant(m
, "SOCK_RDM", SOCK_RDM
);
3505 PyModule_AddIntConstant(m
, "SO_DEBUG", SO_DEBUG
);
3507 #ifdef SO_ACCEPTCONN
3508 PyModule_AddIntConstant(m
, "SO_ACCEPTCONN", SO_ACCEPTCONN
);
3511 PyModule_AddIntConstant(m
, "SO_REUSEADDR", SO_REUSEADDR
);
3514 PyModule_AddIntConstant(m
, "SO_KEEPALIVE", SO_KEEPALIVE
);
3517 PyModule_AddIntConstant(m
, "SO_DONTROUTE", SO_DONTROUTE
);
3520 PyModule_AddIntConstant(m
, "SO_BROADCAST", SO_BROADCAST
);
3522 #ifdef SO_USELOOPBACK
3523 PyModule_AddIntConstant(m
, "SO_USELOOPBACK", SO_USELOOPBACK
);
3526 PyModule_AddIntConstant(m
, "SO_LINGER", SO_LINGER
);
3529 PyModule_AddIntConstant(m
, "SO_OOBINLINE", SO_OOBINLINE
);
3532 PyModule_AddIntConstant(m
, "SO_REUSEPORT", SO_REUSEPORT
);
3535 PyModule_AddIntConstant(m
, "SO_SNDBUF", SO_SNDBUF
);
3538 PyModule_AddIntConstant(m
, "SO_RCVBUF", SO_RCVBUF
);
3541 PyModule_AddIntConstant(m
, "SO_SNDLOWAT", SO_SNDLOWAT
);
3544 PyModule_AddIntConstant(m
, "SO_RCVLOWAT", SO_RCVLOWAT
);
3547 PyModule_AddIntConstant(m
, "SO_SNDTIMEO", SO_SNDTIMEO
);
3550 PyModule_AddIntConstant(m
, "SO_RCVTIMEO", SO_RCVTIMEO
);
3553 PyModule_AddIntConstant(m
, "SO_ERROR", SO_ERROR
);
3556 PyModule_AddIntConstant(m
, "SO_TYPE", SO_TYPE
);
3559 /* Maximum number of connections for "listen" */
3561 PyModule_AddIntConstant(m
, "SOMAXCONN", SOMAXCONN
);
3563 PyModule_AddIntConstant(m
, "SOMAXCONN", 5); /* Common value */
3566 /* Flags for send, recv */
3568 PyModule_AddIntConstant(m
, "MSG_OOB", MSG_OOB
);
3571 PyModule_AddIntConstant(m
, "MSG_PEEK", MSG_PEEK
);
3573 #ifdef MSG_DONTROUTE
3574 PyModule_AddIntConstant(m
, "MSG_DONTROUTE", MSG_DONTROUTE
);
3577 PyModule_AddIntConstant(m
, "MSG_DONTWAIT", MSG_DONTWAIT
);
3580 PyModule_AddIntConstant(m
, "MSG_EOR", MSG_EOR
);
3583 PyModule_AddIntConstant(m
, "MSG_TRUNC", MSG_TRUNC
);
3586 PyModule_AddIntConstant(m
, "MSG_CTRUNC", MSG_CTRUNC
);
3589 PyModule_AddIntConstant(m
, "MSG_WAITALL", MSG_WAITALL
);
3592 PyModule_AddIntConstant(m
, "MSG_BTAG", MSG_BTAG
);
3595 PyModule_AddIntConstant(m
, "MSG_ETAG", MSG_ETAG
);
3598 /* Protocol level and numbers, usable for [gs]etsockopt */
3600 PyModule_AddIntConstant(m
, "SOL_SOCKET", SOL_SOCKET
);
3603 PyModule_AddIntConstant(m
, "SOL_IP", SOL_IP
);
3605 PyModule_AddIntConstant(m
, "SOL_IP", 0);
3608 PyModule_AddIntConstant(m
, "SOL_IPX", SOL_IPX
);
3611 PyModule_AddIntConstant(m
, "SOL_AX25", SOL_AX25
);
3614 PyModule_AddIntConstant(m
, "SOL_ATALK", SOL_ATALK
);
3617 PyModule_AddIntConstant(m
, "SOL_NETROM", SOL_NETROM
);
3620 PyModule_AddIntConstant(m
, "SOL_ROSE", SOL_ROSE
);
3623 PyModule_AddIntConstant(m
, "SOL_TCP", SOL_TCP
);
3625 PyModule_AddIntConstant(m
, "SOL_TCP", 6);
3628 PyModule_AddIntConstant(m
, "SOL_UDP", SOL_UDP
);
3630 PyModule_AddIntConstant(m
, "SOL_UDP", 17);
3633 PyModule_AddIntConstant(m
, "IPPROTO_IP", IPPROTO_IP
);
3635 PyModule_AddIntConstant(m
, "IPPROTO_IP", 0);
3637 #ifdef IPPROTO_HOPOPTS
3638 PyModule_AddIntConstant(m
, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS
);
3641 PyModule_AddIntConstant(m
, "IPPROTO_ICMP", IPPROTO_ICMP
);
3643 PyModule_AddIntConstant(m
, "IPPROTO_ICMP", 1);
3646 PyModule_AddIntConstant(m
, "IPPROTO_IGMP", IPPROTO_IGMP
);
3649 PyModule_AddIntConstant(m
, "IPPROTO_GGP", IPPROTO_GGP
);
3652 PyModule_AddIntConstant(m
, "IPPROTO_IPV4", IPPROTO_IPV4
);
3655 PyModule_AddIntConstant(m
, "IPPROTO_IPIP", IPPROTO_IPIP
);
3658 PyModule_AddIntConstant(m
, "IPPROTO_TCP", IPPROTO_TCP
);
3660 PyModule_AddIntConstant(m
, "IPPROTO_TCP", 6);
3663 PyModule_AddIntConstant(m
, "IPPROTO_EGP", IPPROTO_EGP
);
3666 PyModule_AddIntConstant(m
, "IPPROTO_PUP", IPPROTO_PUP
);
3669 PyModule_AddIntConstant(m
, "IPPROTO_UDP", IPPROTO_UDP
);
3671 PyModule_AddIntConstant(m
, "IPPROTO_UDP", 17);
3674 PyModule_AddIntConstant(m
, "IPPROTO_IDP", IPPROTO_IDP
);
3676 #ifdef IPPROTO_HELLO
3677 PyModule_AddIntConstant(m
, "IPPROTO_HELLO", IPPROTO_HELLO
);
3680 PyModule_AddIntConstant(m
, "IPPROTO_ND", IPPROTO_ND
);
3683 PyModule_AddIntConstant(m
, "IPPROTO_TP", IPPROTO_TP
);
3686 PyModule_AddIntConstant(m
, "IPPROTO_IPV6", IPPROTO_IPV6
);
3688 #ifdef IPPROTO_ROUTING
3689 PyModule_AddIntConstant(m
, "IPPROTO_ROUTING", IPPROTO_ROUTING
);
3691 #ifdef IPPROTO_FRAGMENT
3692 PyModule_AddIntConstant(m
, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT
);
3695 PyModule_AddIntConstant(m
, "IPPROTO_RSVP", IPPROTO_RSVP
);
3698 PyModule_AddIntConstant(m
, "IPPROTO_GRE", IPPROTO_GRE
);
3701 PyModule_AddIntConstant(m
, "IPPROTO_ESP", IPPROTO_ESP
);
3704 PyModule_AddIntConstant(m
, "IPPROTO_AH", IPPROTO_AH
);
3706 #ifdef IPPROTO_MOBILE
3707 PyModule_AddIntConstant(m
, "IPPROTO_MOBILE", IPPROTO_MOBILE
);
3709 #ifdef IPPROTO_ICMPV6
3710 PyModule_AddIntConstant(m
, "IPPROTO_ICMPV6", IPPROTO_ICMPV6
);
3713 PyModule_AddIntConstant(m
, "IPPROTO_NONE", IPPROTO_NONE
);
3715 #ifdef IPPROTO_DSTOPTS
3716 PyModule_AddIntConstant(m
, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS
);
3719 PyModule_AddIntConstant(m
, "IPPROTO_XTP", IPPROTO_XTP
);
3722 PyModule_AddIntConstant(m
, "IPPROTO_EON", IPPROTO_EON
);
3725 PyModule_AddIntConstant(m
, "IPPROTO_PIM", IPPROTO_PIM
);
3727 #ifdef IPPROTO_IPCOMP
3728 PyModule_AddIntConstant(m
, "IPPROTO_IPCOMP", IPPROTO_IPCOMP
);
3731 PyModule_AddIntConstant(m
, "IPPROTO_VRRP", IPPROTO_VRRP
);
3734 PyModule_AddIntConstant(m
, "IPPROTO_BIP", IPPROTO_BIP
);
3738 PyModule_AddIntConstant(m
, "IPPROTO_RAW", IPPROTO_RAW
);
3740 PyModule_AddIntConstant(m
, "IPPROTO_RAW", 255);
3743 PyModule_AddIntConstant(m
, "IPPROTO_MAX", IPPROTO_MAX
);
3746 /* Some port configuration */
3747 #ifdef IPPORT_RESERVED
3748 PyModule_AddIntConstant(m
, "IPPORT_RESERVED", IPPORT_RESERVED
);
3750 PyModule_AddIntConstant(m
, "IPPORT_RESERVED", 1024);
3752 #ifdef IPPORT_USERRESERVED
3753 PyModule_AddIntConstant(m
, "IPPORT_USERRESERVED", IPPORT_USERRESERVED
);
3755 PyModule_AddIntConstant(m
, "IPPORT_USERRESERVED", 5000);
3758 /* Some reserved IP v.4 addresses */
3760 PyModule_AddIntConstant(m
, "INADDR_ANY", INADDR_ANY
);
3762 PyModule_AddIntConstant(m
, "INADDR_ANY", 0x00000000);
3764 #ifdef INADDR_BROADCAST
3765 PyModule_AddIntConstant(m
, "INADDR_BROADCAST", INADDR_BROADCAST
);
3767 PyModule_AddIntConstant(m
, "INADDR_BROADCAST", 0xffffffff);
3769 #ifdef INADDR_LOOPBACK
3770 PyModule_AddIntConstant(m
, "INADDR_LOOPBACK", INADDR_LOOPBACK
);
3772 PyModule_AddIntConstant(m
, "INADDR_LOOPBACK", 0x7F000001);
3774 #ifdef INADDR_UNSPEC_GROUP
3775 PyModule_AddIntConstant(m
, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP
);
3777 PyModule_AddIntConstant(m
, "INADDR_UNSPEC_GROUP", 0xe0000000);
3779 #ifdef INADDR_ALLHOSTS_GROUP
3780 PyModule_AddIntConstant(m
, "INADDR_ALLHOSTS_GROUP",
3781 INADDR_ALLHOSTS_GROUP
);
3783 PyModule_AddIntConstant(m
, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
3785 #ifdef INADDR_MAX_LOCAL_GROUP
3786 PyModule_AddIntConstant(m
, "INADDR_MAX_LOCAL_GROUP",
3787 INADDR_MAX_LOCAL_GROUP
);
3789 PyModule_AddIntConstant(m
, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
3792 PyModule_AddIntConstant(m
, "INADDR_NONE", INADDR_NONE
);
3794 PyModule_AddIntConstant(m
, "INADDR_NONE", 0xffffffff);
3797 /* IPv4 [gs]etsockopt options */
3799 PyModule_AddIntConstant(m
, "IP_OPTIONS", IP_OPTIONS
);
3802 PyModule_AddIntConstant(m
, "IP_HDRINCL", IP_HDRINCL
);
3805 PyModule_AddIntConstant(m
, "IP_TOS", IP_TOS
);
3808 PyModule_AddIntConstant(m
, "IP_TTL", IP_TTL
);
3811 PyModule_AddIntConstant(m
, "IP_RECVOPTS", IP_RECVOPTS
);
3813 #ifdef IP_RECVRETOPTS
3814 PyModule_AddIntConstant(m
, "IP_RECVRETOPTS", IP_RECVRETOPTS
);
3816 #ifdef IP_RECVDSTADDR
3817 PyModule_AddIntConstant(m
, "IP_RECVDSTADDR", IP_RECVDSTADDR
);
3820 PyModule_AddIntConstant(m
, "IP_RETOPTS", IP_RETOPTS
);
3822 #ifdef IP_MULTICAST_IF
3823 PyModule_AddIntConstant(m
, "IP_MULTICAST_IF", IP_MULTICAST_IF
);
3825 #ifdef IP_MULTICAST_TTL
3826 PyModule_AddIntConstant(m
, "IP_MULTICAST_TTL", IP_MULTICAST_TTL
);
3828 #ifdef IP_MULTICAST_LOOP
3829 PyModule_AddIntConstant(m
, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP
);
3831 #ifdef IP_ADD_MEMBERSHIP
3832 PyModule_AddIntConstant(m
, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP
);
3834 #ifdef IP_DROP_MEMBERSHIP
3835 PyModule_AddIntConstant(m
, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP
);
3837 #ifdef IP_DEFAULT_MULTICAST_TTL
3838 PyModule_AddIntConstant(m
, "IP_DEFAULT_MULTICAST_TTL",
3839 IP_DEFAULT_MULTICAST_TTL
);
3841 #ifdef IP_DEFAULT_MULTICAST_LOOP
3842 PyModule_AddIntConstant(m
, "IP_DEFAULT_MULTICAST_LOOP",
3843 IP_DEFAULT_MULTICAST_LOOP
);
3845 #ifdef IP_MAX_MEMBERSHIPS
3846 PyModule_AddIntConstant(m
, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS
);
3849 /* IPv6 [gs]etsockopt options, defined in RFC2553 */
3850 #ifdef IPV6_JOIN_GROUP
3851 PyModule_AddIntConstant(m
, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP
);
3853 #ifdef IPV6_LEAVE_GROUP
3854 PyModule_AddIntConstant(m
, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP
);
3856 #ifdef IPV6_MULTICAST_HOPS
3857 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS
);
3859 #ifdef IPV6_MULTICAST_IF
3860 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF
);
3862 #ifdef IPV6_MULTICAST_LOOP
3863 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP
);
3865 #ifdef IPV6_UNICAST_HOPS
3866 PyModule_AddIntConstant(m
, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS
);
3871 PyModule_AddIntConstant(m
, "TCP_NODELAY", TCP_NODELAY
);
3874 PyModule_AddIntConstant(m
, "TCP_MAXSEG", TCP_MAXSEG
);
3877 PyModule_AddIntConstant(m
, "TCP_CORK", TCP_CORK
);
3880 PyModule_AddIntConstant(m
, "TCP_KEEPIDLE", TCP_KEEPIDLE
);
3882 #ifdef TCP_KEEPINTVL
3883 PyModule_AddIntConstant(m
, "TCP_KEEPINTVL", TCP_KEEPINTVL
);
3886 PyModule_AddIntConstant(m
, "TCP_KEEPCNT", TCP_KEEPCNT
);
3889 PyModule_AddIntConstant(m
, "TCP_SYNCNT", TCP_SYNCNT
);
3892 PyModule_AddIntConstant(m
, "TCP_LINGER2", TCP_LINGER2
);
3894 #ifdef TCP_DEFER_ACCEPT
3895 PyModule_AddIntConstant(m
, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT
);
3897 #ifdef TCP_WINDOW_CLAMP
3898 PyModule_AddIntConstant(m
, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP
);
3901 PyModule_AddIntConstant(m
, "TCP_INFO", TCP_INFO
);
3904 PyModule_AddIntConstant(m
, "TCP_QUICKACK", TCP_QUICKACK
);
3910 PyModule_AddIntConstant(m
, "IPX_TYPE", IPX_TYPE
);
3913 /* get{addr,name}info parameters */
3914 #ifdef EAI_ADDRFAMILY
3915 PyModule_AddIntConstant(m
, "EAI_ADDRFAMILY", EAI_ADDRFAMILY
);
3918 PyModule_AddIntConstant(m
, "EAI_AGAIN", EAI_AGAIN
);
3921 PyModule_AddIntConstant(m
, "EAI_BADFLAGS", EAI_BADFLAGS
);
3924 PyModule_AddIntConstant(m
, "EAI_FAIL", EAI_FAIL
);
3927 PyModule_AddIntConstant(m
, "EAI_FAMILY", EAI_FAMILY
);
3930 PyModule_AddIntConstant(m
, "EAI_MEMORY", EAI_MEMORY
);
3933 PyModule_AddIntConstant(m
, "EAI_NODATA", EAI_NODATA
);
3936 PyModule_AddIntConstant(m
, "EAI_NONAME", EAI_NONAME
);
3939 PyModule_AddIntConstant(m
, "EAI_SERVICE", EAI_SERVICE
);
3942 PyModule_AddIntConstant(m
, "EAI_SOCKTYPE", EAI_SOCKTYPE
);
3945 PyModule_AddIntConstant(m
, "EAI_SYSTEM", EAI_SYSTEM
);
3948 PyModule_AddIntConstant(m
, "EAI_BADHINTS", EAI_BADHINTS
);
3951 PyModule_AddIntConstant(m
, "EAI_PROTOCOL", EAI_PROTOCOL
);
3954 PyModule_AddIntConstant(m
, "EAI_MAX", EAI_MAX
);
3957 PyModule_AddIntConstant(m
, "AI_PASSIVE", AI_PASSIVE
);
3960 PyModule_AddIntConstant(m
, "AI_CANONNAME", AI_CANONNAME
);
3962 #ifdef AI_NUMERICHOST
3963 PyModule_AddIntConstant(m
, "AI_NUMERICHOST", AI_NUMERICHOST
);
3966 PyModule_AddIntConstant(m
, "AI_MASK", AI_MASK
);
3969 PyModule_AddIntConstant(m
, "AI_ALL", AI_ALL
);
3971 #ifdef AI_V4MAPPED_CFG
3972 PyModule_AddIntConstant(m
, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG
);
3974 #ifdef AI_ADDRCONFIG
3975 PyModule_AddIntConstant(m
, "AI_ADDRCONFIG", AI_ADDRCONFIG
);
3978 PyModule_AddIntConstant(m
, "AI_V4MAPPED", AI_V4MAPPED
);
3981 PyModule_AddIntConstant(m
, "AI_DEFAULT", AI_DEFAULT
);
3984 PyModule_AddIntConstant(m
, "NI_MAXHOST", NI_MAXHOST
);
3987 PyModule_AddIntConstant(m
, "NI_MAXSERV", NI_MAXSERV
);
3990 PyModule_AddIntConstant(m
, "NI_NOFQDN", NI_NOFQDN
);
3992 #ifdef NI_NUMERICHOST
3993 PyModule_AddIntConstant(m
, "NI_NUMERICHOST", NI_NUMERICHOST
);
3996 PyModule_AddIntConstant(m
, "NI_NAMEREQD", NI_NAMEREQD
);
3998 #ifdef NI_NUMERICSERV
3999 PyModule_AddIntConstant(m
, "NI_NUMERICSERV", NI_NUMERICSERV
);
4002 PyModule_AddIntConstant(m
, "NI_DGRAM", NI_DGRAM
);
4005 /* Initialize gethostbyname lock */
4006 #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
4007 netdb_lock
= PyThread_allocate_lock();
4012 #ifndef HAVE_INET_PTON
4014 /* Simplistic emulation code for inet_pton that only works for IPv4 */
4015 /* These are not exposed because they do not set errno properly */
4018 inet_pton(int af
, const char *src
, void *dst
)
4020 if (af
== AF_INET
) {
4022 packed_addr
= inet_addr(src
);
4023 if (packed_addr
== INADDR_NONE
)
4025 memcpy(dst
, &packed_addr
, 4);
4028 /* Should set errno to EAFNOSUPPORT */
4033 inet_ntop(int af
, const void *src
, char *dst
, socklen_t size
)
4035 if (af
== AF_INET
) {
4036 struct in_addr packed_addr
;
4038 /* Should set errno to ENOSPC. */
4040 memcpy(&packed_addr
, src
, sizeof(packed_addr
));
4041 return strncpy(dst
, inet_ntoa(packed_addr
), size
);
4043 /* Should set errno to EAFNOSUPPORT */