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.inet_aton(IP address) -> 32-bit packed IP representation
39 - socket.inet_ntoa(packed IP) -> IP address string
40 - socket.getdefaulttimeout() -> None | float
41 - socket.setdefaulttimeout(None | float)
42 - an Internet socket address is a pair (hostname, port)
43 where hostname can be anything recognized by gethostbyname()
44 (including the dd.dd.dd.dd notation) and port is in host byte order
45 - where a hostname is returned, the dd.dd.dd.dd notation is used
46 - a UNIX domain socket address is a string specifying the pathname
47 - an AF_PACKET socket address is a tuple containing a string
48 specifying the ethernet interface and an integer specifying
49 the Ethernet protocol number to be received. For example:
50 ("eth0",0x1234). Optional 3rd,4th,5th elements in the tuple
51 specify packet-type and ha-type/addr -- these are ignored by
52 networking code, but accepted since they are returned by the
55 Local naming conventions:
57 - names starting with sock_ are socket object methods
58 - names starting with socket_ are module-level functions
59 - names starting with PySocket are exported through socketmodule.h
65 /* Socket object documentation */
66 PyDoc_STRVAR(sock_doc
,
67 "socket([family[, type[, proto]]]) -> socket object\n\
69 Open a socket of the given type. The family argument specifies the\n\
70 address family; it defaults to AF_INET. The type argument specifies\n\
71 whether this is a stream (SOCK_STREAM, this is the default)\n\
72 or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0,\n\
73 specifying the default protocol. Keyword arguments are accepted.\n\
75 A socket object represents one endpoint of a network connection.\n\
77 Methods of socket objects (keyword arguments not allowed):\n\
79 accept() -- accept a connection, returning new socket and client address\n\
80 bind(addr) -- bind the socket to a local address\n\
81 close() -- close the socket\n\
82 connect(addr) -- connect the socket to a remote address\n\
83 connect_ex(addr) -- connect, return an error code instead of an exception\n\
84 dup() -- return a new socket object identical to the current one [*]\n\
85 fileno() -- return underlying file descriptor\n\
86 getpeername() -- return remote address [*]\n\
87 getsockname() -- return local address\n\
88 getsockopt(level, optname[, buflen]) -- get socket options\n\
89 gettimeout() -- return timeout or None\n\
90 listen(n) -- start listening for incoming connections\n\
91 makefile([mode, [bufsize]]) -- return a file object for the socket [*]\n\
92 recv(buflen[, flags]) -- receive data\n\
93 recvfrom(buflen[, flags]) -- receive data and sender's address\n\
94 sendall(data[, flags]) -- send all data\n\
95 send(data[, flags]) -- send data, may not send all of it\n\
96 sendto(data[, flags], addr) -- send data to a given address\n\
97 setblocking(0 | 1) -- set or clear the blocking I/O flag\n\
98 setsockopt(level, optname, value) -- set socket options\n\
99 settimeout(None | float) -- set or clear the timeout\n\
100 shutdown(how) -- shut down traffic in one or both directions\n\
102 [*] not available on all platforms!");
104 /* XXX This is a terrible mess of of platform-dependent preprocessor hacks.
105 I hope some day someone can clean this up please... */
107 /* Hacks for gethostbyname_r(). On some non-Linux platforms, the configure
108 script doesn't get this right, so we hardcode some platform checks below.
109 On the other hand, not all Linux versions agree, so there the settings
110 computed by the configure script are needed! */
113 # undef HAVE_GETHOSTBYNAME_R_3_ARG
114 # undef HAVE_GETHOSTBYNAME_R_5_ARG
115 # undef HAVE_GETHOSTBYNAME_R_6_ARG
119 # undef HAVE_GETHOSTBYNAME_R
122 #ifdef HAVE_GETHOSTBYNAME_R
123 # if defined(_AIX) || defined(__osf__)
124 # define HAVE_GETHOSTBYNAME_R_3_ARG
125 # elif defined(__sun) || defined(__sgi)
126 # define HAVE_GETHOSTBYNAME_R_5_ARG
127 # elif defined(linux)
128 /* Rely on the configure script */
130 # undef HAVE_GETHOSTBYNAME_R
134 #if !defined(HAVE_GETHOSTBYNAME_R) && defined(WITH_THREAD) && \
136 # define USE_GETHOSTBYNAME_LOCK
139 #ifdef USE_GETHOSTBYNAME_LOCK
140 # include "pythread.h"
143 #if defined(PYCC_VACPP)
146 # include <sys/ioctl.h>
152 #if ! defined(_SOCKADDR_LEN)
156 # include "TCPIP_IOCTL_ROUTINE"
162 #if defined(PYOS_OS2)
164 # define INCL_DOSERRORS
165 # define INCL_NOPMAPI
169 #if defined(__sgi)&&_COMPILER_VERSION>700 && !_SGIAPI
170 /* make sure that the reentrant (gethostbyaddr_r etc)
171 functions are declared correctly if compiling with
172 MIPSPro 7.x in ANSI C mode (default) */
177 /* Generic includes */
178 #include <sys/types.h>
181 /* Generic socket object definitions and includes */
182 #define PySocket_BUILDING_SOCKET
183 #include "socketmodule.h"
185 /* Addressing includes */
189 /* Non-MS WINDOWS includes */
192 /* Headers needed for inet_ntoa() and inet_addr() */
194 # include <net/netdb.h>
195 # elif defined(PYOS_OS2) && defined(PYCC_VACPP)
197 typedef size_t socklen_t
;
199 # include <arpa/inet.h>
205 # include <sys/fcntl.h>
207 int h_errno
; /* not used */
212 /* MS_WINDOWS includes */
222 # define offsetof(type, member) ((size_t)(&((type *)0)->member))
226 # define O_NONBLOCK O_NDELAY
229 #include "addrinfo.h"
231 #ifndef HAVE_INET_PTON
232 int inet_pton(int af
, const char *src
, void *dst
);
233 const char *inet_ntop(int af
, const void *src
, char *dst
, socklen_t size
);
237 /* On OS X, getaddrinfo returns no error indication of lookup
238 failure, so we must use the emulation instead of the libinfo
239 implementation. Unfortunately, performing an autoconf test
240 for this bug would require DNS access for the machine performing
241 the configuration, which is not acceptable. Therefore, we
242 determine the bug just by checking for __APPLE__. If this bug
243 gets ever fixed, perhaps checking for sys/version.h would be
244 appropriate, which is 10/0 on the system with the bug. */
245 #ifndef HAVE_GETNAMEINFO
246 /* This bug seems to be fixed in Jaguar. Ths easiest way I could
247 Find to check for Jaguar is that it has getnameinfo(), which
248 older releases don't have */
249 #undef HAVE_GETADDRINFO
250 /* avoid clashes with the C library definition of the symbol. */
251 #define getaddrinfo fake_getaddrinfo
255 /* I know this is a bad practice, but it is the easiest... */
256 #if !defined(HAVE_GETADDRINFO)
257 #include "getaddrinfo.c"
259 #if !defined(HAVE_GETNAMEINFO)
260 #include "getnameinfo.c"
263 #if defined(MS_WINDOWS) || defined(__BEOS__)
264 /* BeOS suffers from the same socket dichotomy as Win32... - [cjh] */
265 /* seem to be a few differences in the API */
266 #define SOCKETCLOSE closesocket
267 #define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */
271 #define EAFNOSUPPORT WSAEAFNOSUPPORT
272 #define snprintf _snprintf
275 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
276 #define SOCKETCLOSE soclose
277 #define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
281 #define SOCKETCLOSE close
285 /* TCP/IP Services for VMS uses a maximum send/revc buffer length of 65535 */
286 #define SEGMENT_SIZE 65535
289 /* XXX There's a problem here: *static* functions are not supposed to have
290 a Py prefix (or use CapitalizedWords). Later... */
292 /* Global variable holding the exception type for errors detected
293 by this module (but not argument type or memory errors, etc.). */
294 static PyObject
*socket_error
;
295 static PyObject
*socket_herror
;
296 static PyObject
*socket_gaierror
;
299 /* Global variable which is !=0 if Python is running in a RISC OS taskwindow */
300 static int taskwindow
;
303 /* A forward reference to the socket type object.
304 The sock_type variable contains pointers to various functions,
305 some of which call new_sockobject(), which uses sock_type, so
306 there has to be a circular reference. */
307 static PyTypeObject sock_type
;
309 /* Convenience function to raise an error according to errno
310 and return a NULL pointer from a function. */
316 int err_no
= WSAGetLastError();
321 {WSAEINTR
, "Interrupted system call"},
322 {WSAEBADF
, "Bad file descriptor"},
323 {WSAEACCES
, "Permission denied"},
324 {WSAEFAULT
, "Bad address"},
325 {WSAEINVAL
, "Invalid argument"},
326 {WSAEMFILE
, "Too many open files"},
328 "The socket operation could not complete "
330 {WSAEINPROGRESS
, "Operation now in progress"},
331 {WSAEALREADY
, "Operation already in progress"},
332 {WSAENOTSOCK
, "Socket operation on non-socket"},
333 {WSAEDESTADDRREQ
, "Destination address required"},
334 {WSAEMSGSIZE
, "Message too long"},
335 {WSAEPROTOTYPE
, "Protocol wrong type for socket"},
336 {WSAENOPROTOOPT
, "Protocol not available"},
337 {WSAEPROTONOSUPPORT
, "Protocol not supported"},
338 {WSAESOCKTNOSUPPORT
, "Socket type not supported"},
339 {WSAEOPNOTSUPP
, "Operation not supported"},
340 {WSAEPFNOSUPPORT
, "Protocol family not supported"},
341 {WSAEAFNOSUPPORT
, "Address family not supported"},
342 {WSAEADDRINUSE
, "Address already in use"},
343 {WSAEADDRNOTAVAIL
, "Can't assign requested address"},
344 {WSAENETDOWN
, "Network is down"},
345 {WSAENETUNREACH
, "Network is unreachable"},
346 {WSAENETRESET
, "Network dropped connection on reset"},
347 {WSAECONNABORTED
, "Software caused connection abort"},
348 {WSAECONNRESET
, "Connection reset by peer"},
349 {WSAENOBUFS
, "No buffer space available"},
350 {WSAEISCONN
, "Socket is already connected"},
351 {WSAENOTCONN
, "Socket is not connected"},
352 {WSAESHUTDOWN
, "Can't send after socket shutdown"},
353 {WSAETOOMANYREFS
, "Too many references: can't splice"},
354 {WSAETIMEDOUT
, "Operation timed out"},
355 {WSAECONNREFUSED
, "Connection refused"},
356 {WSAELOOP
, "Too many levels of symbolic links"},
357 {WSAENAMETOOLONG
, "File name too long"},
358 {WSAEHOSTDOWN
, "Host is down"},
359 {WSAEHOSTUNREACH
, "No route to host"},
360 {WSAENOTEMPTY
, "Directory not empty"},
361 {WSAEPROCLIM
, "Too many processes"},
362 {WSAEUSERS
, "Too many users"},
363 {WSAEDQUOT
, "Disc quota exceeded"},
364 {WSAESTALE
, "Stale NFS file handle"},
365 {WSAEREMOTE
, "Too many levels of remote in path"},
366 {WSASYSNOTREADY
, "Network subsystem is unvailable"},
367 {WSAVERNOTSUPPORTED
, "WinSock version is not supported"},
369 "Successful WSAStartup() not yet performed"},
370 {WSAEDISCON
, "Graceful shutdown in progress"},
371 /* Resolver errors */
372 {WSAHOST_NOT_FOUND
, "No such host is known"},
373 {WSATRY_AGAIN
, "Host not found, or server failed"},
374 {WSANO_RECOVERY
, "Unexpected server error encountered"},
375 {WSANO_DATA
, "Valid name without requested data"},
376 {WSANO_ADDRESS
, "No address, look for MX record"},
381 const char *msg
= "winsock error";
383 for (msgp
= msgs
; msgp
->msg
; msgp
++) {
384 if (err_no
== msgp
->no
) {
390 v
= Py_BuildValue("(is)", err_no
, msg
);
392 PyErr_SetObject(socket_error
, v
);
400 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
401 if (sock_errno() != NO_ERROR
) {
405 int myerrorcode
= sock_errno();
407 /* Retrieve socket-related error message from MPTN.MSG file */
408 rc
= DosGetMessage(NULL
, 0, outbuf
, sizeof(outbuf
),
409 myerrorcode
- SOCBASEERR
+ 26,
412 if (rc
== NO_ERROR
) {
415 /* OS/2 doesn't guarantee a terminator */
416 outbuf
[msglen
] = '\0';
417 if (strlen(outbuf
) > 0) {
418 /* If non-empty msg, trim CRLF */
419 char *lastc
= &outbuf
[ strlen(outbuf
)-1 ];
420 while (lastc
> outbuf
&& isspace(*lastc
)) {
421 /* Trim trailing whitespace (CRLF) */
425 v
= Py_BuildValue("(is)", myerrorcode
, outbuf
);
427 PyErr_SetObject(socket_error
, v
);
435 return PyErr_SetFromErrno(socket_error
);
440 set_herror(int h_error
)
444 #ifdef HAVE_HSTRERROR
445 v
= Py_BuildValue("(is)", h_error
, (char *)hstrerror(h_error
));
447 v
= Py_BuildValue("(is)", h_error
, "host not found");
450 PyErr_SetObject(socket_herror
, v
);
459 set_gaierror(int error
)
464 /* EAI_SYSTEM is not available on Windows XP. */
465 if (error
== EAI_SYSTEM
)
469 #ifdef HAVE_GAI_STRERROR
470 v
= Py_BuildValue("(is)", error
, gai_strerror(error
));
472 v
= Py_BuildValue("(is)", error
, "getaddrinfo failed");
475 PyErr_SetObject(socket_gaierror
, v
);
482 /* Function to perform the setting of socket blocking mode
483 internally. block = (1 | 0). */
485 internal_setblocking(PySocketSockObject
*s
, int block
)
493 Py_BEGIN_ALLOW_THREADS
496 setsockopt(s
->sock_fd
, SOL_SOCKET
, SO_NONBLOCK
,
497 (void *)(&block
), sizeof(int));
501 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
503 ioctl(s
->sock_fd
, FIONBIO
, (caddr_t
)&block
, sizeof(block
));
506 ioctl(s
->sock_fd
, FIONBIO
, (char *)&block
);
507 #else /* !PYOS_OS2 && !_VMS */
508 delay_flag
= fcntl(s
->sock_fd
, F_GETFL
, 0);
510 delay_flag
&= (~O_NONBLOCK
);
512 delay_flag
|= O_NONBLOCK
;
513 fcntl(s
->sock_fd
, F_SETFL
, delay_flag
);
514 #endif /* !PYOS_OS2 */
515 #else /* MS_WINDOWS */
517 ioctlsocket(s
->sock_fd
, FIONBIO
, (u_long
*)&block
);
518 #endif /* MS_WINDOWS */
519 #endif /* __BEOS__ */
523 /* Since these don't return anything */
527 /* Do a select() on the socket, if necessary (sock_timeout > 0).
528 The argument writing indicates the direction.
529 This does not raise an exception or return a success indicator;
530 we'll let the actual socket call do that. */
532 internal_select(PySocketSockObject
*s
, int writing
)
537 /* Nothing to do unless we're in timeout mode (not non-blocking) */
538 if (s
->sock_timeout
<= 0.0)
541 /* Guard against closed socket */
545 /* Construct the arguments to select */
546 tv
.tv_sec
= (int)s
->sock_timeout
;
547 tv
.tv_usec
= (int)((s
->sock_timeout
- tv
.tv_sec
) * 1e6
);
549 FD_SET(s
->sock_fd
, &fds
);
551 /* See if the socket is ready */
553 select(s
->sock_fd
+1, NULL
, &fds
, NULL
, &tv
);
555 select(s
->sock_fd
+1, &fds
, NULL
, NULL
, &tv
);
558 /* Initialize a new socket object. */
560 static double defaulttimeout
= -1.0; /* Default timeout for new sockets */
563 init_sockobject(PySocketSockObject
*s
,
564 SOCKET_T fd
, int family
, int type
, int proto
)
570 s
->sock_family
= family
;
572 s
->sock_proto
= proto
;
573 s
->sock_timeout
= defaulttimeout
;
575 s
->errorhandler
= &set_error
;
577 if (defaulttimeout
>= 0.0)
578 internal_setblocking(s
, 0);
582 socketioctl(s
->sock_fd
, 0x80046679, (u_long
*)&block
);
587 /* Create a new socket object.
588 This just creates the object and initializes it.
589 If the creation fails, return NULL and set an exception (implicit
592 static PySocketSockObject
*
593 new_sockobject(SOCKET_T fd
, int family
, int type
, int proto
)
595 PySocketSockObject
*s
;
596 s
= (PySocketSockObject
*)
597 PyType_GenericNew(&sock_type
, NULL
, NULL
);
599 init_sockobject(s
, fd
, family
, type
, proto
);
604 /* Lock to allow python interpreter to continue, but only allow one
605 thread to be in gethostbyname */
606 #ifdef USE_GETHOSTBYNAME_LOCK
607 PyThread_type_lock gethostbyname_lock
;
611 /* Convert a string specifying a host name or one of a few symbolic
612 names to a numeric IP address. This usually calls gethostbyname()
613 to do the work; the names "" and "<broadcast>" are special.
614 Return the length (IPv4 should be 4 bytes), or negative if
615 an error occurred; then an exception is raised. */
618 setipaddr(char *name
, struct sockaddr
*addr_ret
, size_t addr_ret_size
, int af
)
620 struct addrinfo hints
, *res
;
623 memset((void *) addr_ret
, '\0', sizeof(*addr_ret
));
624 if (name
[0] == '\0') {
626 memset(&hints
, 0, sizeof(hints
));
627 hints
.ai_family
= af
;
628 hints
.ai_socktype
= SOCK_DGRAM
; /*dummy*/
629 hints
.ai_flags
= AI_PASSIVE
;
630 error
= getaddrinfo(NULL
, "0", &hints
, &res
);
635 switch (res
->ai_family
) {
646 PyErr_SetString(socket_error
,
647 "unsupported address family");
652 PyErr_SetString(socket_error
,
653 "wildcard resolved to multiple address");
656 if (res
->ai_addrlen
< addr_ret_size
)
657 addr_ret_size
= res
->ai_addrlen
;
658 memcpy(addr_ret
, res
->ai_addr
, addr_ret_size
);
662 if (name
[0] == '<' && strcmp(name
, "<broadcast>") == 0) {
663 struct sockaddr_in
*sin
;
664 if (af
!= AF_INET
&& af
!= AF_UNSPEC
) {
665 PyErr_SetString(socket_error
,
666 "address family mismatched");
669 sin
= (struct sockaddr_in
*)addr_ret
;
670 memset((void *) sin
, '\0', sizeof(*sin
));
671 sin
->sin_family
= AF_INET
;
672 #ifdef HAVE_SOCKADDR_SA_LEN
673 sin
->sin_len
= sizeof(*sin
);
675 sin
->sin_addr
.s_addr
= INADDR_BROADCAST
;
676 return sizeof(sin
->sin_addr
);
678 memset(&hints
, 0, sizeof(hints
));
679 hints
.ai_family
= af
;
680 error
= getaddrinfo(name
, NULL
, &hints
, &res
);
681 #if defined(__digital__) && defined(__unix__)
682 if (error
== EAI_NONAME
&& af
== AF_UNSPEC
) {
683 /* On Tru64 V5.1, numeric-to-addr conversion fails
684 if no address family is given. Assume IPv4 for now.*/
685 hints
.ai_family
= AF_INET
;
686 error
= getaddrinfo(name
, NULL
, &hints
, &res
);
693 if (res
->ai_addrlen
< addr_ret_size
)
694 addr_ret_size
= res
->ai_addrlen
;
695 memcpy((char *) addr_ret
, res
->ai_addr
, addr_ret_size
);
697 switch (addr_ret
->sa_family
) {
705 PyErr_SetString(socket_error
, "unknown address family");
711 /* Create a string object representing an IP address.
712 This is always a string of the form 'dd.dd.dd.dd' (with variable
716 makeipaddr(struct sockaddr
*addr
, int addrlen
)
718 char buf
[NI_MAXHOST
];
721 error
= getnameinfo(addr
, addrlen
, buf
, sizeof(buf
), NULL
, 0,
727 return PyString_FromString(buf
);
731 /* Create an object representing the given socket address,
732 suitable for passing it back to bind(), connect() etc.
733 The family field of the sockaddr structure is inspected
734 to determine what kind of address it really is. */
738 makesockaddr(int sockfd
, struct sockaddr
*addr
, int addrlen
)
741 /* No address -- may be recvfrom() from known socket */
747 /* XXX: BeOS version of accept() doesn't set family correctly */
748 addr
->sa_family
= AF_INET
;
751 switch (addr
->sa_family
) {
755 struct sockaddr_in
*a
;
756 PyObject
*addrobj
= makeipaddr(addr
, sizeof(*a
));
757 PyObject
*ret
= NULL
;
759 a
= (struct sockaddr_in
*)addr
;
760 ret
= Py_BuildValue("Oi", addrobj
, ntohs(a
->sin_port
));
766 #if defined(AF_UNIX) && !defined(PYOS_OS2)
769 struct sockaddr_un
*a
= (struct sockaddr_un
*) addr
;
770 return PyString_FromString(a
->sun_path
);
777 struct sockaddr_in6
*a
;
778 PyObject
*addrobj
= makeipaddr(addr
, sizeof(*a
));
779 PyObject
*ret
= NULL
;
781 a
= (struct sockaddr_in6
*)addr
;
782 ret
= Py_BuildValue("Oiii",
793 #ifdef HAVE_NETPACKET_PACKET_H
796 struct sockaddr_ll
*a
= (struct sockaddr_ll
*)addr
;
799 /* need to look up interface name give index */
800 if (a
->sll_ifindex
) {
801 ifr
.ifr_ifindex
= a
->sll_ifindex
;
802 if (ioctl(sockfd
, SIOCGIFNAME
, &ifr
) == 0)
803 ifname
= ifr
.ifr_name
;
805 return Py_BuildValue("shbhs#",
807 ntohs(a
->sll_protocol
),
815 /* More cases here... */
818 /* If we don't know the address family, don't raise an
819 exception -- return it as a tuple. */
820 return Py_BuildValue("is#",
823 sizeof(addr
->sa_data
));
829 /* Parse a socket address argument according to the socket object's
830 address family. Return 1 if the address was in the proper format,
831 0 of not. The address is returned through addr_ret, its length
835 getsockaddrarg(PySocketSockObject
*s
, PyObject
*args
,
836 struct sockaddr
**addr_ret
, int *len_ret
)
838 switch (s
->sock_family
) {
840 #if defined(AF_UNIX) && !defined(PYOS_OS2)
843 struct sockaddr_un
* addr
;
846 addr
= (struct sockaddr_un
*)&(s
->sock_addr
).un
;
847 if (!PyArg_Parse(args
, "t#", &path
, &len
))
849 if (len
> sizeof addr
->sun_path
) {
850 PyErr_SetString(socket_error
,
851 "AF_UNIX path too long");
854 addr
->sun_family
= s
->sock_family
;
855 memcpy(addr
->sun_path
, path
, len
);
856 addr
->sun_path
[len
] = 0;
857 *addr_ret
= (struct sockaddr
*) addr
;
858 *len_ret
= len
+ sizeof(*addr
) - sizeof(addr
->sun_path
);
865 struct sockaddr_in
* addr
;
868 addr
=(struct sockaddr_in
*)&(s
->sock_addr
).in
;
869 if (!PyTuple_Check(args
)) {
873 "AF_INET address must be tuple, not %.500s",
874 args
->ob_type
->tp_name
);
877 if (!PyArg_ParseTuple(args
, "si:getsockaddrarg", &host
, &port
))
879 if (setipaddr(host
, (struct sockaddr
*)addr
, sizeof(*addr
), AF_INET
) < 0)
881 addr
->sin_family
= AF_INET
;
882 addr
->sin_port
= htons((short)port
);
883 *addr_ret
= (struct sockaddr
*) addr
;
884 *len_ret
= sizeof *addr
;
891 struct sockaddr_in6
* addr
;
893 int port
, flowinfo
, scope_id
;
894 addr
= (struct sockaddr_in6
*)&(s
->sock_addr
).in6
;
895 flowinfo
= scope_id
= 0;
896 if (!PyArg_ParseTuple(args
, "si|ii", &host
, &port
, &flowinfo
,
900 if (setipaddr(host
, (struct sockaddr
*)addr
, sizeof(*addr
), AF_INET6
) < 0)
902 addr
->sin6_family
= s
->sock_family
;
903 addr
->sin6_port
= htons((short)port
);
904 addr
->sin6_flowinfo
= flowinfo
;
905 addr
->sin6_scope_id
= scope_id
;
906 *addr_ret
= (struct sockaddr
*) addr
;
907 *len_ret
= sizeof *addr
;
912 #ifdef HAVE_NETPACKET_PACKET_H
915 struct sockaddr_ll
* addr
;
923 if (!PyArg_ParseTuple(args
, "si|iis", &interfaceName
,
924 &protoNumber
, &pkttype
, &hatype
, &haddr
))
926 strncpy(ifr
.ifr_name
, interfaceName
, sizeof(ifr
.ifr_name
));
927 ifr
.ifr_name
[(sizeof(ifr
.ifr_name
))-1] = '\0';
928 if (ioctl(s
->sock_fd
, SIOCGIFINDEX
, &ifr
) < 0) {
932 addr
= &(s
->sock_addr
.ll
);
933 addr
->sll_family
= AF_PACKET
;
934 addr
->sll_protocol
= htons((short)protoNumber
);
935 addr
->sll_ifindex
= ifr
.ifr_ifindex
;
936 addr
->sll_pkttype
= pkttype
;
937 addr
->sll_hatype
= hatype
;
938 *addr_ret
= (struct sockaddr
*) addr
;
939 *len_ret
= sizeof *addr
;
944 /* More cases here... */
947 PyErr_SetString(socket_error
, "getsockaddrarg: bad family");
954 /* Get the address length according to the socket object's address family.
955 Return 1 if the family is known, 0 otherwise. The length is returned
959 getsockaddrlen(PySocketSockObject
*s
, socklen_t
*len_ret
)
961 switch (s
->sock_family
) {
963 #if defined(AF_UNIX) && !defined(PYOS_OS2)
966 *len_ret
= sizeof (struct sockaddr_un
);
973 *len_ret
= sizeof (struct sockaddr_in
);
980 *len_ret
= sizeof (struct sockaddr_in6
);
985 #ifdef HAVE_NETPACKET_PACKET_H
988 *len_ret
= sizeof (struct sockaddr_ll
);
993 /* More cases here... */
996 PyErr_SetString(socket_error
, "getsockaddrlen: bad family");
1003 /* s.accept() method */
1006 sock_accept(PySocketSockObject
*s
)
1011 PyObject
*sock
= NULL
;
1012 PyObject
*addr
= NULL
;
1013 PyObject
*res
= NULL
;
1015 if (!getsockaddrlen(s
, &addrlen
))
1017 memset(addrbuf
, 0, addrlen
);
1019 Py_BEGIN_ALLOW_THREADS
1020 internal_select(s
, 0);
1021 newfd
= accept(s
->sock_fd
, (struct sockaddr
*) addrbuf
, &addrlen
);
1022 Py_END_ALLOW_THREADS
1025 if (newfd
== INVALID_SOCKET
)
1029 return s
->errorhandler();
1031 /* Create the new object with unspecified family,
1032 to avoid calls to bind() etc. on it. */
1033 sock
= (PyObject
*) new_sockobject(newfd
,
1042 addr
= makesockaddr(s
->sock_fd
, (struct sockaddr
*)addrbuf
,
1047 res
= Py_BuildValue("OO", sock
, addr
);
1055 PyDoc_STRVAR(accept_doc
,
1056 "accept() -> (socket object, address info)\n\
1058 Wait for an incoming connection. Return a new socket representing the\n\
1059 connection, and the address of the client. For IP sockets, the address\n\
1060 info is a pair (hostaddr, port).");
1062 /* s.setblocking(flag) method. Argument:
1063 False -- non-blocking mode; same as settimeout(0)
1064 True -- blocking mode; same as settimeout(None)
1068 sock_setblocking(PySocketSockObject
*s
, PyObject
*arg
)
1072 block
= PyInt_AsLong(arg
);
1073 if (block
== -1 && PyErr_Occurred())
1076 s
->sock_timeout
= block
? -1.0 : 0.0;
1077 internal_setblocking(s
, block
);
1083 PyDoc_STRVAR(setblocking_doc
,
1084 "setblocking(flag)\n\
1086 Set the socket to blocking (flag is true) or non-blocking (false).\n\
1087 setblocking(True) is equivalent to settimeout(None);\n\
1088 setblocking(False) is equivalent to settimeout(0.0).");
1090 /* s.settimeout(timeout) method. Argument:
1091 None -- no timeout, blocking mode; same as setblocking(True)
1092 0.0 -- non-blocking mode; same as setblocking(False)
1093 > 0 -- timeout mode; operations time out after timeout seconds
1094 < 0 -- illegal; raises an exception
1097 sock_settimeout(PySocketSockObject
*s
, PyObject
*arg
)
1104 timeout
= PyFloat_AsDouble(arg
);
1105 if (timeout
< 0.0) {
1106 if (!PyErr_Occurred())
1107 PyErr_SetString(PyExc_ValueError
,
1108 "Timeout value out of range");
1113 s
->sock_timeout
= timeout
;
1114 internal_setblocking(s
, timeout
< 0.0);
1120 PyDoc_STRVAR(settimeout_doc
,
1121 "settimeout(timeout)\n\
1123 Set a timeout on socket operations. 'timeout' can be a float,\n\
1124 giving in seconds, or None. Setting a timeout of None disables\n\
1125 the timeout feature and is equivalent to setblocking(1).\n\
1126 Setting a timeout of zero is the same as setblocking(0).");
1128 /* s.gettimeout() method.
1129 Returns the timeout associated with a socket. */
1131 sock_gettimeout(PySocketSockObject
*s
)
1133 if (s
->sock_timeout
< 0.0) {
1138 return PyFloat_FromDouble(s
->sock_timeout
);
1141 PyDoc_STRVAR(gettimeout_doc
,
1142 "gettimeout() -> timeout\n\
1144 Returns the timeout in floating seconds associated with socket \n\
1145 operations. A timeout of None indicates that timeouts on socket \n\
1146 operations are disabled.");
1149 /* s.sleeptaskw(1 | 0) method */
1152 sock_sleeptaskw(PySocketSockObject
*s
,PyObject
*args
)
1156 if (!PyArg_Parse(args
, "i", &block
))
1158 Py_BEGIN_ALLOW_THREADS
1159 socketioctl(s
->sock_fd
, 0x80046679, (u_long
*)&block
);
1160 Py_END_ALLOW_THREADS
1165 PyDoc_STRVAR(sleeptaskw_doc
,
1166 "sleeptaskw(flag)\n\
1168 Allow sleeps in taskwindows.");
1172 /* s.setsockopt() method.
1173 With an integer third argument, sets an integer option.
1174 With a string third argument, sets an option from a buffer;
1175 use optional built-in module 'struct' to encode the string. */
1178 sock_setsockopt(PySocketSockObject
*s
, PyObject
*args
)
1187 if (PyArg_ParseTuple(args
, "iii:setsockopt",
1188 &level
, &optname
, &flag
)) {
1189 buf
= (char *) &flag
;
1190 buflen
= sizeof flag
;
1194 if (!PyArg_ParseTuple(args
, "iis#:setsockopt",
1195 &level
, &optname
, &buf
, &buflen
))
1198 res
= setsockopt(s
->sock_fd
, level
, optname
, (void *)buf
, buflen
);
1200 return s
->errorhandler();
1205 PyDoc_STRVAR(setsockopt_doc
,
1206 "setsockopt(level, option, value)\n\
1208 Set a socket option. See the Unix manual for level and option.\n\
1209 The value argument can either be an integer or a string.");
1212 /* s.getsockopt() method.
1213 With two arguments, retrieves an integer option.
1214 With a third integer argument, retrieves a string buffer of that size;
1215 use optional built-in module 'struct' to decode the string. */
1218 sock_getsockopt(PySocketSockObject
*s
, PyObject
*args
)
1224 socklen_t buflen
= 0;
1227 /* We have incomplete socket support. */
1228 PyErr_SetString(socket_error
, "getsockopt not supported");
1232 if (!PyArg_ParseTuple(args
, "ii|i:getsockopt",
1233 &level
, &optname
, &buflen
))
1238 socklen_t flagsize
= sizeof flag
;
1239 res
= getsockopt(s
->sock_fd
, level
, optname
,
1240 (void *)&flag
, &flagsize
);
1242 return s
->errorhandler();
1243 return PyInt_FromLong(flag
);
1246 if (buflen
> 1024) {
1248 if (buflen
<= 0 || buflen
> 1024) {
1250 PyErr_SetString(socket_error
,
1251 "getsockopt buflen out of range");
1254 buf
= PyString_FromStringAndSize((char *)NULL
, buflen
);
1257 res
= getsockopt(s
->sock_fd
, level
, optname
,
1258 (void *)PyString_AS_STRING(buf
), &buflen
);
1261 return s
->errorhandler();
1263 _PyString_Resize(&buf
, buflen
);
1265 #endif /* __BEOS__ */
1268 PyDoc_STRVAR(getsockopt_doc
,
1269 "getsockopt(level, option[, buffersize]) -> value\n\
1271 Get a socket option. See the Unix manual for level and option.\n\
1272 If a nonzero buffersize argument is given, the return value is a\n\
1273 string of that length; otherwise it is an integer.");
1276 /* s.bind(sockaddr) method */
1279 sock_bind(PySocketSockObject
*s
, PyObject
*addro
)
1281 struct sockaddr
*addr
;
1285 if (!getsockaddrarg(s
, addro
, &addr
, &addrlen
))
1287 Py_BEGIN_ALLOW_THREADS
1288 res
= bind(s
->sock_fd
, addr
, addrlen
);
1289 Py_END_ALLOW_THREADS
1291 return s
->errorhandler();
1296 PyDoc_STRVAR(bind_doc
,
1299 Bind the socket to a local address. For IP sockets, the address is a\n\
1300 pair (host, port); the host must refer to the local host. For raw packet\n\
1301 sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");
1304 /* s.close() method.
1305 Set the file descriptor to -1 so operations tried subsequently
1306 will surely fail. */
1309 sock_close(PySocketSockObject
*s
)
1313 if ((fd
= s
->sock_fd
) != -1) {
1315 Py_BEGIN_ALLOW_THREADS
1316 (void) SOCKETCLOSE(fd
);
1317 Py_END_ALLOW_THREADS
1323 PyDoc_STRVAR(close_doc
,
1326 Close the socket. It cannot be used after this call.");
1329 internal_connect(PySocketSockObject
*s
, struct sockaddr
*addr
, int addrlen
)
1333 res
= connect(s
->sock_fd
, addr
, addrlen
);
1337 if (s
->sock_timeout
> 0.0) {
1338 if (res
< 0 && WSAGetLastError() == WSAEWOULDBLOCK
) {
1339 /* This is a mess. Best solution: trust select */
1342 tv
.tv_sec
= (int)s
->sock_timeout
;
1343 tv
.tv_usec
= (int)((s
->sock_timeout
- tv
.tv_sec
) * 1e6
);
1345 FD_SET(s
->sock_fd
, &fds
);
1346 res
= select(s
->sock_fd
+1, NULL
, &fds
, NULL
, &tv
);
1348 res
= WSAEWOULDBLOCK
;
1351 /* else if (res < 0) an error occurred */
1356 res
= WSAGetLastError();
1360 if (s
->sock_timeout
> 0.0) {
1361 if (res
< 0 && errno
== EINPROGRESS
) {
1362 internal_select(s
, 1);
1363 res
= connect(s
->sock_fd
, addr
, addrlen
);
1364 if (res
< 0 && errno
== EISCONN
)
1377 /* s.connect(sockaddr) method */
1380 sock_connect(PySocketSockObject
*s
, PyObject
*addro
)
1382 struct sockaddr
*addr
;
1386 if (!getsockaddrarg(s
, addro
, &addr
, &addrlen
))
1389 Py_BEGIN_ALLOW_THREADS
1390 res
= internal_connect(s
, addr
, addrlen
);
1391 Py_END_ALLOW_THREADS
1394 return s
->errorhandler();
1399 PyDoc_STRVAR(connect_doc
,
1400 "connect(address)\n\
1402 Connect the socket to a remote address. For IP sockets, the address\n\
1403 is a pair (host, port).");
1406 /* s.connect_ex(sockaddr) method */
1409 sock_connect_ex(PySocketSockObject
*s
, PyObject
*addro
)
1411 struct sockaddr
*addr
;
1415 if (!getsockaddrarg(s
, addro
, &addr
, &addrlen
))
1418 Py_BEGIN_ALLOW_THREADS
1419 res
= internal_connect(s
, addr
, addrlen
);
1420 Py_END_ALLOW_THREADS
1422 return PyInt_FromLong((long) res
);
1425 PyDoc_STRVAR(connect_ex_doc
,
1426 "connect_ex(address) -> errno\n\
1428 This is like connect(address), but returns an error code (the errno value)\n\
1429 instead of raising an exception when an error occurs.");
1432 /* s.fileno() method */
1435 sock_fileno(PySocketSockObject
*s
)
1437 #if SIZEOF_SOCKET_T <= SIZEOF_LONG
1438 return PyInt_FromLong((long) s
->sock_fd
);
1440 return PyLong_FromLongLong((LONG_LONG
)s
->sock_fd
);
1444 PyDoc_STRVAR(fileno_doc
,
1445 "fileno() -> integer\n\
1447 Return the integer file descriptor of the socket.");
1451 /* s.dup() method */
1454 sock_dup(PySocketSockObject
*s
)
1459 newfd
= dup(s
->sock_fd
);
1461 return s
->errorhandler();
1462 sock
= (PyObject
*) new_sockobject(newfd
,
1471 PyDoc_STRVAR(dup_doc
,
1472 "dup() -> socket object\n\
1474 Return a new socket object connected to the same system resource.");
1479 /* s.getsockname() method */
1482 sock_getsockname(PySocketSockObject
*s
)
1488 if (!getsockaddrlen(s
, &addrlen
))
1490 memset(addrbuf
, 0, addrlen
);
1491 Py_BEGIN_ALLOW_THREADS
1492 res
= getsockname(s
->sock_fd
, (struct sockaddr
*) addrbuf
, &addrlen
);
1493 Py_END_ALLOW_THREADS
1495 return s
->errorhandler();
1496 return makesockaddr(s
->sock_fd
, (struct sockaddr
*) addrbuf
, addrlen
);
1499 PyDoc_STRVAR(getsockname_doc
,
1500 "getsockname() -> address info\n\
1502 Return the address of the local endpoint. For IP sockets, the address\n\
1503 info is a pair (hostaddr, port).");
1506 #ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
1507 /* s.getpeername() method */
1510 sock_getpeername(PySocketSockObject
*s
)
1516 if (!getsockaddrlen(s
, &addrlen
))
1518 memset(addrbuf
, 0, addrlen
);
1519 Py_BEGIN_ALLOW_THREADS
1520 res
= getpeername(s
->sock_fd
, (struct sockaddr
*) addrbuf
, &addrlen
);
1521 Py_END_ALLOW_THREADS
1523 return s
->errorhandler();
1524 return makesockaddr(s
->sock_fd
, (struct sockaddr
*) addrbuf
, addrlen
);
1527 PyDoc_STRVAR(getpeername_doc
,
1528 "getpeername() -> address info\n\
1530 Return the address of the remote endpoint. For IP sockets, the address\n\
1531 info is a pair (hostaddr, port).");
1533 #endif /* HAVE_GETPEERNAME */
1536 /* s.listen(n) method */
1539 sock_listen(PySocketSockObject
*s
, PyObject
*arg
)
1544 backlog
= PyInt_AsLong(arg
);
1545 if (backlog
== -1 && PyErr_Occurred())
1547 Py_BEGIN_ALLOW_THREADS
1550 res
= listen(s
->sock_fd
, backlog
);
1551 Py_END_ALLOW_THREADS
1553 return s
->errorhandler();
1558 PyDoc_STRVAR(listen_doc
,
1561 Enable a server to accept connections. The backlog argument must be at\n\
1562 least 1; it specifies the number of unaccepted connection that the system\n\
1563 will allow before refusing new connections.");
1567 /* s.makefile(mode) method.
1568 Create a new open file object referring to a dupped version of
1569 the socket's file descriptor. (The dup() call is necessary so
1570 that the open file and socket objects may be closed independent
1572 The mode argument specifies 'r' or 'w' passed to fdopen(). */
1575 sock_makefile(PySocketSockObject
*s
, PyObject
*args
)
1577 extern int fclose(FILE *);
1592 if (!PyArg_ParseTuple(args
, "|si:makefile", &mode
, &bufsize
))
1595 if (strcmp(mode
,"rb") == 0) {
1599 if (strcmp(mode
,"wb") == 0) {
1605 if (((fd
= _open_osfhandle(s
->sock_fd
, _O_BINARY
)) < 0) ||
1606 ((fd
= dup(fd
)) < 0) || ((fp
= fdopen(fd
, mode
)) == NULL
))
1608 if ((fd
= dup(s
->sock_fd
)) < 0 || (fp
= fdopen(fd
, mode
)) == NULL
)
1613 return s
->errorhandler();
1616 /* Workaround for bug in Metrowerks MSL vs. GUSI I/O library */
1617 if (strchr(mode
, 'b') != NULL
)
1620 f
= PyFile_FromFile(fp
, "<socket>", mode
, fclose
);
1622 PyFile_SetBufSize(f
, bufsize
);
1626 PyDoc_STRVAR(makefile_doc
,
1627 "makefile([mode[, buffersize]]) -> file object\n\
1629 Return a regular file object corresponding to the socket.\n\
1630 The mode and buffersize arguments are as for the built-in open() function.");
1635 /* s.recv(nbytes [,flags]) method */
1638 sock_recv(PySocketSockObject
*s
, PyObject
*args
)
1640 int len
, n
, flags
= 0;
1647 if (!PyArg_ParseTuple(args
, "i|i:recv", &len
, &flags
))
1651 PyErr_SetString(PyExc_ValueError
,
1652 "negative buffersize in recv");
1656 buf
= PyString_FromStringAndSize((char *) 0, len
);
1661 Py_BEGIN_ALLOW_THREADS
1662 internal_select(s
, 0);
1663 n
= recv(s
->sock_fd
, PyString_AS_STRING(buf
), len
, flags
);
1664 Py_END_ALLOW_THREADS
1668 return s
->errorhandler();
1671 _PyString_Resize(&buf
, n
);
1673 read_buf
= PyString_AsString(buf
);
1675 while (read_length
!= 0) {
1676 unsigned int segment
;
1678 segment
= read_length
/SEGMENT_SIZE
;
1680 segment
= SEGMENT_SIZE
;
1683 segment
= read_length
;
1686 Py_BEGIN_ALLOW_THREADS
1687 internal_select(s
, 0);
1688 n
= recv(s
->sock_fd
, read_buf
, segment
, flags
);
1689 Py_END_ALLOW_THREADS
1693 return s
->errorhandler();
1695 if (n
!= read_length
) {
1700 read_length
-= segment
;
1701 read_buf
+= segment
;
1703 if (_PyString_Resize(&buf
, (read_buf
- PyString_AsString(buf
))) < 0)
1711 PyDoc_STRVAR(recv_doc
,
1712 "recv(buffersize[, flags]) -> data\n\
1714 Receive up to buffersize bytes from the socket. For the optional flags\n\
1715 argument, see the Unix manual. When no data is available, block until\n\
1716 at least one byte is available or until the remote end is closed. When\n\
1717 the remote end is closed and all data is read, return the empty string.");
1720 /* s.recvfrom(nbytes [,flags]) method */
1723 sock_recvfrom(PySocketSockObject
*s
, PyObject
*args
)
1726 PyObject
*buf
= NULL
;
1727 PyObject
*addr
= NULL
;
1728 PyObject
*ret
= NULL
;
1729 int len
, n
, flags
= 0;
1732 if (!PyArg_ParseTuple(args
, "i|i:recvfrom", &len
, &flags
))
1735 if (!getsockaddrlen(s
, &addrlen
))
1737 buf
= PyString_FromStringAndSize((char *) 0, len
);
1741 Py_BEGIN_ALLOW_THREADS
1742 memset(addrbuf
, 0, addrlen
);
1743 internal_select(s
, 0);
1744 n
= recvfrom(s
->sock_fd
, PyString_AS_STRING(buf
), len
, flags
,
1746 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
1747 (struct sockaddr
*)addrbuf
, &addrlen
1749 (void *)addrbuf
, &addrlen
1752 (struct sockaddr
*)addrbuf
, &addrlen
1755 Py_END_ALLOW_THREADS
1759 return s
->errorhandler();
1762 if (n
!= len
&& _PyString_Resize(&buf
, n
) < 0)
1765 if (!(addr
= makesockaddr(s
->sock_fd
, (struct sockaddr
*)addrbuf
,
1769 ret
= Py_BuildValue("OO", buf
, addr
);
1777 PyDoc_STRVAR(recvfrom_doc
,
1778 "recvfrom(buffersize[, flags]) -> (data, address info)\n\
1780 Like recv(buffersize, flags) but also return the sender's address info.");
1782 /* s.send(data [,flags]) method */
1785 sock_send(PySocketSockObject
*s
, PyObject
*args
)
1788 int len
, n
, flags
= 0;
1793 if (!PyArg_ParseTuple(args
, "s#|i:send", &buf
, &len
, &flags
))
1797 Py_BEGIN_ALLOW_THREADS
1798 internal_select(s
, 1);
1799 n
= send(s
->sock_fd
, buf
, len
, flags
);
1800 Py_END_ALLOW_THREADS
1803 return s
->errorhandler();
1805 /* Divide packet into smaller segments for */
1806 /* TCP/IP Services for OpenVMS */
1808 while (send_length
!= 0) {
1809 unsigned int segment
;
1811 segment
= send_length
/ SEGMENT_SIZE
;
1813 segment
= SEGMENT_SIZE
;
1816 segment
= send_length
;
1818 Py_BEGIN_ALLOW_THREADS
1819 internal_select(s
, 1);
1820 n
= send(s
->sock_fd
, buf
, segment
, flags
);
1821 Py_END_ALLOW_THREADS
1823 return s
->errorhandler();
1825 send_length
-= segment
;
1829 return PyInt_FromLong((long)n
);
1832 PyDoc_STRVAR(send_doc
,
1833 "send(data[, flags]) -> count\n\
1835 Send a data string to the socket. For the optional flags\n\
1836 argument, see the Unix manual. Return the number of bytes\n\
1837 sent; this may be less than len(data) if the network is busy.");
1840 /* s.sendall(data [,flags]) method */
1843 sock_sendall(PySocketSockObject
*s
, PyObject
*args
)
1846 int len
, n
, flags
= 0;
1848 if (!PyArg_ParseTuple(args
, "s#|i:sendall", &buf
, &len
, &flags
))
1851 Py_BEGIN_ALLOW_THREADS
1853 internal_select(s
, 1);
1854 n
= send(s
->sock_fd
, buf
, len
, flags
);
1860 Py_END_ALLOW_THREADS
1863 return s
->errorhandler();
1869 PyDoc_STRVAR(sendall_doc
,
1870 "sendall(data[, flags])\n\
1872 Send a data string to the socket. For the optional flags\n\
1873 argument, see the Unix manual. This calls send() repeatedly\n\
1874 until all data is sent. If an error occurs, it's impossible\n\
1875 to tell how much data has been sent.");
1878 /* s.sendto(data, [flags,] sockaddr) method */
1881 sock_sendto(PySocketSockObject
*s
, PyObject
*args
)
1885 struct sockaddr
*addr
;
1886 int addrlen
, len
, n
, flags
;
1889 if (!PyArg_ParseTuple(args
, "s#O:sendto", &buf
, &len
, &addro
)) {
1891 if (!PyArg_ParseTuple(args
, "s#iO:sendto",
1892 &buf
, &len
, &flags
, &addro
))
1896 if (!getsockaddrarg(s
, addro
, &addr
, &addrlen
))
1899 Py_BEGIN_ALLOW_THREADS
1900 internal_select(s
, 1);
1901 n
= sendto(s
->sock_fd
, buf
, len
, flags
, addr
, addrlen
);
1902 Py_END_ALLOW_THREADS
1905 return s
->errorhandler();
1906 return PyInt_FromLong((long)n
);
1909 PyDoc_STRVAR(sendto_doc
,
1910 "sendto(data[, flags], address) -> count\n\
1912 Like send(data, flags) but allows specifying the destination address.\n\
1913 For IP sockets, the address is a pair (hostaddr, port).");
1916 /* s.shutdown(how) method */
1919 sock_shutdown(PySocketSockObject
*s
, PyObject
*arg
)
1924 how
= PyInt_AsLong(arg
);
1925 if (how
== -1 && PyErr_Occurred())
1927 Py_BEGIN_ALLOW_THREADS
1928 res
= shutdown(s
->sock_fd
, how
);
1929 Py_END_ALLOW_THREADS
1931 return s
->errorhandler();
1936 PyDoc_STRVAR(shutdown_doc
,
1939 Shut down the reading side of the socket (flag == 0), the writing side\n\
1940 of the socket (flag == 1), or both ends (flag == 2).");
1943 /* List of methods for socket objects */
1945 static PyMethodDef sock_methods
[] = {
1946 {"accept", (PyCFunction
)sock_accept
, METH_NOARGS
,
1948 {"bind", (PyCFunction
)sock_bind
, METH_O
,
1950 {"close", (PyCFunction
)sock_close
, METH_NOARGS
,
1952 {"connect", (PyCFunction
)sock_connect
, METH_O
,
1954 {"connect_ex", (PyCFunction
)sock_connect_ex
, METH_O
,
1957 {"dup", (PyCFunction
)sock_dup
, METH_NOARGS
,
1960 {"fileno", (PyCFunction
)sock_fileno
, METH_NOARGS
,
1962 #ifdef HAVE_GETPEERNAME
1963 {"getpeername", (PyCFunction
)sock_getpeername
,
1964 METH_NOARGS
, getpeername_doc
},
1966 {"getsockname", (PyCFunction
)sock_getsockname
,
1967 METH_NOARGS
, getsockname_doc
},
1968 {"getsockopt", (PyCFunction
)sock_getsockopt
, METH_VARARGS
,
1970 {"listen", (PyCFunction
)sock_listen
, METH_O
,
1973 {"makefile", (PyCFunction
)sock_makefile
, METH_VARARGS
,
1976 {"recv", (PyCFunction
)sock_recv
, METH_VARARGS
,
1978 {"recvfrom", (PyCFunction
)sock_recvfrom
, METH_VARARGS
,
1980 {"send", (PyCFunction
)sock_send
, METH_VARARGS
,
1982 {"sendall", (PyCFunction
)sock_sendall
, METH_VARARGS
,
1984 {"sendto", (PyCFunction
)sock_sendto
, METH_VARARGS
,
1986 {"setblocking", (PyCFunction
)sock_setblocking
, METH_O
,
1988 {"settimeout", (PyCFunction
)sock_settimeout
, METH_O
,
1990 {"gettimeout", (PyCFunction
)sock_gettimeout
, METH_NOARGS
,
1992 {"setsockopt", (PyCFunction
)sock_setsockopt
, METH_VARARGS
,
1994 {"shutdown", (PyCFunction
)sock_shutdown
, METH_O
,
1997 {"sleeptaskw", (PyCFunction
)sock_sleeptaskw
, METH_VARARGS
,
2000 {NULL
, NULL
} /* sentinel */
2004 /* Deallocate a socket object in response to the last Py_DECREF().
2005 First close the file description. */
2008 sock_dealloc(PySocketSockObject
*s
)
2010 if (s
->sock_fd
!= -1)
2011 (void) SOCKETCLOSE(s
->sock_fd
);
2012 s
->ob_type
->tp_free((PyObject
*)s
);
2017 sock_repr(PySocketSockObject
*s
)
2020 #if SIZEOF_SOCKET_T > SIZEOF_LONG
2021 if (s
->sock_fd
> LONG_MAX
) {
2022 /* this can occur on Win64, and actually there is a special
2023 ugly printf formatter for decimal pointer length integer
2024 printing, only bother if necessary*/
2025 PyErr_SetString(PyExc_OverflowError
,
2026 "no printf formatter to display "
2027 "the socket descriptor in decimal");
2033 "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
2034 (long)s
->sock_fd
, s
->sock_family
,
2037 return PyString_FromString(buf
);
2041 /* Create a new, uninitialized socket object. */
2044 sock_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
2048 new = type
->tp_alloc(type
, 0);
2050 ((PySocketSockObject
*)new)->sock_fd
= -1;
2051 ((PySocketSockObject
*)new)->sock_timeout
= -1.0;
2052 ((PySocketSockObject
*)new)->errorhandler
= &set_error
;
2058 /* Initialize a new socket object. */
2062 sock_initobj(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
2064 PySocketSockObject
*s
= (PySocketSockObject
*)self
;
2066 int family
= AF_INET
, type
= SOCK_STREAM
, proto
= 0;
2067 static char *keywords
[] = {"family", "type", "proto", 0};
2069 if (!PyArg_ParseTupleAndKeywords(args
, kwds
,
2070 "|iii:socket", keywords
,
2071 &family
, &type
, &proto
))
2074 Py_BEGIN_ALLOW_THREADS
2075 fd
= socket(family
, type
, proto
);
2076 Py_END_ALLOW_THREADS
2079 if (fd
== INVALID_SOCKET
)
2087 init_sockobject(s
, fd
, family
, type
, proto
);
2088 /* From now on, ignore SIGPIPE and let the error checking
2091 (void) signal(SIGPIPE
, SIG_IGN
);
2099 /* Type object for socket objects. */
2101 static PyTypeObject sock_type
= {
2102 PyObject_HEAD_INIT(0) /* Must fill in type value later */
2104 "_socket.socket", /* tp_name */
2105 sizeof(PySocketSockObject
), /* tp_basicsize */
2106 0, /* tp_itemsize */
2107 (destructor
)sock_dealloc
, /* tp_dealloc */
2112 (reprfunc
)sock_repr
, /* tp_repr */
2113 0, /* tp_as_number */
2114 0, /* tp_as_sequence */
2115 0, /* tp_as_mapping */
2119 PyObject_GenericGetAttr
, /* tp_getattro */
2120 0, /* tp_setattro */
2121 0, /* tp_as_buffer */
2122 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
2123 sock_doc
, /* tp_doc */
2124 0, /* tp_traverse */
2126 0, /* tp_richcompare */
2127 0, /* tp_weaklistoffset */
2129 0, /* tp_iternext */
2130 sock_methods
, /* tp_methods */
2135 0, /* tp_descr_get */
2136 0, /* tp_descr_set */
2137 0, /* tp_dictoffset */
2138 sock_initobj
, /* tp_init */
2139 PyType_GenericAlloc
, /* tp_alloc */
2140 sock_new
, /* tp_new */
2141 PyObject_Del
, /* tp_free */
2145 /* Python interface to gethostname(). */
2149 socket_gethostname(PyObject
*self
, PyObject
*args
)
2153 if (!PyArg_ParseTuple(args
, ":gethostname"))
2155 Py_BEGIN_ALLOW_THREADS
2156 res
= gethostname(buf
, (int) sizeof buf
- 1);
2157 Py_END_ALLOW_THREADS
2160 buf
[sizeof buf
- 1] = '\0';
2161 return PyString_FromString(buf
);
2164 PyDoc_STRVAR(gethostname_doc
,
2165 "gethostname() -> string\n\
2167 Return the current host name.");
2170 /* Python interface to gethostbyname(name). */
2174 socket_gethostbyname(PyObject
*self
, PyObject
*args
)
2177 struct sockaddr_storage addrbuf
;
2179 if (!PyArg_ParseTuple(args
, "s:gethostbyname", &name
))
2181 if (setipaddr(name
, (struct sockaddr
*)&addrbuf
, sizeof(addrbuf
), AF_INET
) < 0)
2183 return makeipaddr((struct sockaddr
*)&addrbuf
,
2184 sizeof(struct sockaddr_in
));
2187 PyDoc_STRVAR(gethostbyname_doc
,
2188 "gethostbyname(host) -> address\n\
2190 Return the IP address (a string of the form '255.255.255.255') for a host.");
2193 /* Convenience function common to gethostbyname_ex and gethostbyaddr */
2196 gethost_common(struct hostent
*h
, struct sockaddr
*addr
, int alen
, int af
)
2199 PyObject
*rtn_tuple
= (PyObject
*)NULL
;
2200 PyObject
*name_list
= (PyObject
*)NULL
;
2201 PyObject
*addr_list
= (PyObject
*)NULL
;
2205 /* Let's get real error message to return */
2207 set_herror(h_errno
);
2209 PyErr_SetString(socket_error
, "host not found");
2214 if (h
->h_addrtype
!= af
) {
2215 #ifdef HAVE_STRERROR
2216 /* Let's get real error message to return */
2217 PyErr_SetString(socket_error
,
2218 (char *)strerror(EAFNOSUPPORT
));
2222 "Address family not supported by protocol family");
2230 if (alen
< sizeof(struct sockaddr_in
))
2236 if (alen
< sizeof(struct sockaddr_in6
))
2243 if ((name_list
= PyList_New(0)) == NULL
)
2246 if ((addr_list
= PyList_New(0)) == NULL
)
2249 for (pch
= h
->h_aliases
; *pch
!= NULL
; pch
++) {
2251 tmp
= PyString_FromString(*pch
);
2255 status
= PyList_Append(name_list
, tmp
);
2262 for (pch
= h
->h_addr_list
; *pch
!= NULL
; pch
++) {
2269 struct sockaddr_in sin
;
2270 memset(&sin
, 0, sizeof(sin
));
2271 sin
.sin_family
= af
;
2272 #ifdef HAVE_SOCKADDR_SA_LEN
2273 sin
.sin_len
= sizeof(sin
);
2275 memcpy(&sin
.sin_addr
, *pch
, sizeof(sin
.sin_addr
));
2276 tmp
= makeipaddr((struct sockaddr
*)&sin
, sizeof(sin
));
2278 if (pch
== h
->h_addr_list
&& alen
>= sizeof(sin
))
2279 memcpy((char *) addr
, &sin
, sizeof(sin
));
2286 struct sockaddr_in6 sin6
;
2287 memset(&sin6
, 0, sizeof(sin6
));
2288 sin6
.sin6_family
= af
;
2289 #ifdef HAVE_SOCKADDR_SA_LEN
2290 sin6
.sin6_len
= sizeof(sin6
);
2292 memcpy(&sin6
.sin6_addr
, *pch
, sizeof(sin6
.sin6_addr
));
2293 tmp
= makeipaddr((struct sockaddr
*)&sin6
,
2296 if (pch
== h
->h_addr_list
&& alen
>= sizeof(sin6
))
2297 memcpy((char *) addr
, &sin6
, sizeof(sin6
));
2302 default: /* can't happen */
2303 PyErr_SetString(socket_error
,
2304 "unsupported address family");
2311 status
= PyList_Append(addr_list
, tmp
);
2318 rtn_tuple
= Py_BuildValue("sOO", h
->h_name
, name_list
, addr_list
);
2321 Py_XDECREF(name_list
);
2322 Py_XDECREF(addr_list
);
2327 /* Python interface to gethostbyname_ex(name). */
2331 socket_gethostbyname_ex(PyObject
*self
, PyObject
*args
)
2335 struct sockaddr_storage addr
;
2336 struct sockaddr
*sa
;
2338 #ifdef HAVE_GETHOSTBYNAME_R
2339 struct hostent hp_allocated
;
2340 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
2341 struct hostent_data data
;
2344 int buf_len
= (sizeof buf
) - 1;
2347 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2350 #endif /* HAVE_GETHOSTBYNAME_R */
2352 if (!PyArg_ParseTuple(args
, "s:gethostbyname_ex", &name
))
2354 if (setipaddr(name
, (struct sockaddr
*)&addr
, sizeof(addr
), AF_INET
) < 0)
2356 Py_BEGIN_ALLOW_THREADS
2357 #ifdef HAVE_GETHOSTBYNAME_R
2358 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2359 result
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
,
2361 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
2362 h
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
, &errnop
);
2363 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
2364 memset((void *) &data
, '\0', sizeof(data
));
2365 result
= gethostbyname_r(name
, &hp_allocated
, &data
);
2366 h
= (result
!= 0) ? NULL
: &hp_allocated
;
2368 #else /* not HAVE_GETHOSTBYNAME_R */
2369 #ifdef USE_GETHOSTBYNAME_LOCK
2370 PyThread_acquire_lock(gethostbyname_lock
, 1);
2372 h
= gethostbyname(name
);
2373 #endif /* HAVE_GETHOSTBYNAME_R */
2374 Py_END_ALLOW_THREADS
2375 /* Some C libraries would require addr.__ss_family instead of
2377 Therefore, we cast the sockaddr_storage into sockaddr to
2378 access sa_family. */
2379 sa
= (struct sockaddr
*)&addr
;
2380 ret
= gethost_common(h
, (struct sockaddr
*)&addr
, sizeof(addr
),
2382 #ifdef USE_GETHOSTBYNAME_LOCK
2383 PyThread_release_lock(gethostbyname_lock
);
2388 PyDoc_STRVAR(ghbn_ex_doc
,
2389 "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
2391 Return the true host name, a list of aliases, and a list of IP addresses,\n\
2392 for a host. The host argument is a string giving a host name or IP number.");
2395 /* Python interface to gethostbyaddr(IP). */
2399 socket_gethostbyaddr(PyObject
*self
, PyObject
*args
)
2402 struct sockaddr_storage addr
;
2404 struct sockaddr_in addr
;
2406 struct sockaddr
*sa
= (struct sockaddr
*)&addr
;
2410 #ifdef HAVE_GETHOSTBYNAME_R
2411 struct hostent hp_allocated
;
2412 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
2413 struct hostent_data data
;
2416 int buf_len
= (sizeof buf
) - 1;
2419 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2422 #endif /* HAVE_GETHOSTBYNAME_R */
2427 if (!PyArg_ParseTuple(args
, "s:gethostbyaddr", &ip_num
))
2430 if (setipaddr(ip_num
, sa
, sizeof(addr
), af
) < 0)
2437 ap
= (char *)&((struct sockaddr_in
*)sa
)->sin_addr
;
2438 al
= sizeof(((struct sockaddr_in
*)sa
)->sin_addr
);
2442 ap
= (char *)&((struct sockaddr_in6
*)sa
)->sin6_addr
;
2443 al
= sizeof(((struct sockaddr_in6
*)sa
)->sin6_addr
);
2447 PyErr_SetString(socket_error
, "unsupported address family");
2450 Py_BEGIN_ALLOW_THREADS
2451 #ifdef HAVE_GETHOSTBYNAME_R
2452 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
2453 result
= gethostbyaddr_r(ap
, al
, af
,
2454 &hp_allocated
, buf
, buf_len
,
2456 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
2457 h
= gethostbyaddr_r(ap
, al
, af
,
2458 &hp_allocated
, buf
, buf_len
, &errnop
);
2459 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
2460 memset((void *) &data
, '\0', sizeof(data
));
2461 result
= gethostbyaddr_r(ap
, al
, af
, &hp_allocated
, &data
);
2462 h
= (result
!= 0) ? NULL
: &hp_allocated
;
2464 #else /* not HAVE_GETHOSTBYNAME_R */
2465 #ifdef USE_GETHOSTBYNAME_LOCK
2466 PyThread_acquire_lock(gethostbyname_lock
, 1);
2468 h
= gethostbyaddr(ap
, al
, af
);
2469 #endif /* HAVE_GETHOSTBYNAME_R */
2470 Py_END_ALLOW_THREADS
2471 ret
= gethost_common(h
, (struct sockaddr
*)&addr
, sizeof(addr
), af
);
2472 #ifdef USE_GETHOSTBYNAME_LOCK
2473 PyThread_release_lock(gethostbyname_lock
);
2478 PyDoc_STRVAR(gethostbyaddr_doc
,
2479 "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
2481 Return the true host name, a list of aliases, and a list of IP addresses,\n\
2482 for a host. The host argument is a string giving a host name or IP number.");
2485 /* Python interface to getservbyname(name).
2486 This only returns the port number, since the other info is already
2487 known or not useful (like the list of aliases). */
2491 socket_getservbyname(PyObject
*self
, PyObject
*args
)
2495 if (!PyArg_ParseTuple(args
, "ss:getservbyname", &name
, &proto
))
2497 Py_BEGIN_ALLOW_THREADS
2498 sp
= getservbyname(name
, proto
);
2499 Py_END_ALLOW_THREADS
2501 PyErr_SetString(socket_error
, "service/proto not found");
2504 return PyInt_FromLong((long) ntohs(sp
->s_port
));
2507 PyDoc_STRVAR(getservbyname_doc
,
2508 "getservbyname(servicename, protocolname) -> integer\n\
2510 Return a port number from a service name and protocol name.\n\
2511 The protocol name should be 'tcp' or 'udp'.");
2514 /* Python interface to getprotobyname(name).
2515 This only returns the protocol number, since the other info is
2516 already known or not useful (like the list of aliases). */
2520 socket_getprotobyname(PyObject
*self
, PyObject
*args
)
2523 struct protoent
*sp
;
2525 /* Not available in BeOS yet. - [cjh] */
2526 PyErr_SetString(socket_error
, "getprotobyname not supported");
2529 if (!PyArg_ParseTuple(args
, "s:getprotobyname", &name
))
2531 Py_BEGIN_ALLOW_THREADS
2532 sp
= getprotobyname(name
);
2533 Py_END_ALLOW_THREADS
2535 PyErr_SetString(socket_error
, "protocol not found");
2538 return PyInt_FromLong((long) sp
->p_proto
);
2542 PyDoc_STRVAR(getprotobyname_doc
,
2543 "getprotobyname(name) -> integer\n\
2545 Return the protocol number for the named protocol. (Rarely used.)");
2549 /* Create a socket object from a numeric file description.
2550 Useful e.g. if stdin is a socket.
2551 Additional arguments as for socket(). */
2555 socket_fromfd(PyObject
*self
, PyObject
*args
)
2557 PySocketSockObject
*s
;
2559 int family
, type
, proto
= 0;
2560 if (!PyArg_ParseTuple(args
, "iii|i:fromfd",
2561 &fd
, &family
, &type
, &proto
))
2563 /* Dup the fd so it and the socket can be closed independently */
2567 s
= new_sockobject(fd
, family
, type
, proto
);
2568 /* From now on, ignore SIGPIPE and let the error checking
2571 (void) signal(SIGPIPE
, SIG_IGN
);
2573 return (PyObject
*) s
;
2576 PyDoc_STRVAR(fromfd_doc
,
2577 "fromfd(fd, family, type[, proto]) -> socket object\n\
2579 Create a socket object from the given file descriptor.\n\
2580 The remaining arguments are the same as for socket().");
2586 socket_ntohs(PyObject
*self
, PyObject
*args
)
2590 if (!PyArg_ParseTuple(args
, "i:ntohs", &x1
)) {
2593 x2
= (int)ntohs((short)x1
);
2594 return PyInt_FromLong(x2
);
2597 PyDoc_STRVAR(ntohs_doc
,
2598 "ntohs(integer) -> integer\n\
2600 Convert a 16-bit integer from network to host byte order.");
2604 socket_ntohl(PyObject
*self
, PyObject
*arg
)
2608 if (PyInt_Check(arg
)) {
2609 x
= PyInt_AS_LONG(arg
);
2610 if (x
== (unsigned long) -1 && PyErr_Occurred())
2613 else if (PyLong_Check(arg
)) {
2614 x
= PyLong_AsUnsignedLong(arg
);
2615 if (x
== (unsigned long) -1 && PyErr_Occurred())
2620 /* only want the trailing 32 bits */
2621 y
= x
& 0xFFFFFFFFUL
;
2623 return PyErr_Format(PyExc_OverflowError
,
2624 "long int larger than 32 bits");
2630 return PyErr_Format(PyExc_TypeError
,
2631 "expected int/long, %s found",
2632 arg
->ob_type
->tp_name
);
2633 if (x
== (unsigned long) -1 && PyErr_Occurred())
2635 return PyInt_FromLong(ntohl(x
));
2638 PyDoc_STRVAR(ntohl_doc
,
2639 "ntohl(integer) -> integer\n\
2641 Convert a 32-bit integer from network to host byte order.");
2645 socket_htons(PyObject
*self
, PyObject
*args
)
2647 unsigned long x1
, x2
;
2649 if (!PyArg_ParseTuple(args
, "i:htons", &x1
)) {
2652 x2
= (int)htons((short)x1
);
2653 return PyInt_FromLong(x2
);
2656 PyDoc_STRVAR(htons_doc
,
2657 "htons(integer) -> integer\n\
2659 Convert a 16-bit integer from host to network byte order.");
2663 socket_htonl(PyObject
*self
, PyObject
*arg
)
2667 if (PyInt_Check(arg
)) {
2668 x
= PyInt_AS_LONG(arg
);
2669 if (x
== (unsigned long) -1 && PyErr_Occurred())
2672 else if (PyLong_Check(arg
)) {
2673 x
= PyLong_AsUnsignedLong(arg
);
2674 if (x
== (unsigned long) -1 && PyErr_Occurred())
2679 /* only want the trailing 32 bits */
2680 y
= x
& 0xFFFFFFFFUL
;
2682 return PyErr_Format(PyExc_OverflowError
,
2683 "long int larger than 32 bits");
2689 return PyErr_Format(PyExc_TypeError
,
2690 "expected int/long, %s found",
2691 arg
->ob_type
->tp_name
);
2692 return PyInt_FromLong(htonl(x
));
2695 PyDoc_STRVAR(htonl_doc
,
2696 "htonl(integer) -> integer\n\
2698 Convert a 32-bit integer from host to network byte order.");
2700 /* socket.inet_aton() and socket.inet_ntoa() functions. */
2702 PyDoc_STRVAR(inet_aton_doc
,
2703 "inet_aton(string) -> packed 32-bit IP representation\n\
2705 Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
2706 binary format used in low-level network functions.");
2709 socket_inet_aton(PyObject
*self
, PyObject
*args
)
2712 #define INADDR_NONE (-1)
2714 #ifdef HAVE_INET_ATON
2717 /* Have to use inet_addr() instead */
2718 unsigned long packed_addr
;
2722 if (!PyArg_ParseTuple(args
, "s:inet_aton", &ip_addr
))
2726 #ifdef HAVE_INET_ATON
2727 if (inet_aton(ip_addr
, &buf
))
2728 return PyString_FromStringAndSize((char *)(&buf
),
2731 PyErr_SetString(socket_error
,
2732 "illegal IP address string passed to inet_aton");
2735 #else /* ! HAVE_INET_ATON */
2736 /* XXX Problem here: inet_aton('255.255.255.255') raises
2737 an exception while it should be a valid address. */
2738 packed_addr
= inet_addr(ip_addr
);
2740 if (packed_addr
== INADDR_NONE
) { /* invalid address */
2741 PyErr_SetString(socket_error
,
2742 "illegal IP address string passed to inet_aton");
2745 return PyString_FromStringAndSize((char *) &packed_addr
,
2746 sizeof(packed_addr
));
2750 PyDoc_STRVAR(inet_ntoa_doc
,
2751 "inet_ntoa(packed_ip) -> ip_address_string\n\
2753 Convert an IP address from 32-bit packed binary format to string format");
2756 socket_inet_ntoa(PyObject
*self
, PyObject
*args
)
2760 struct in_addr packed_addr
;
2762 if (!PyArg_ParseTuple(args
, "s#:inet_ntoa", &packed_str
, &addr_len
)) {
2766 if (addr_len
!= sizeof(packed_addr
)) {
2767 PyErr_SetString(socket_error
,
2768 "packed IP wrong length for inet_ntoa");
2772 memcpy(&packed_addr
, packed_str
, addr_len
);
2774 return PyString_FromString(inet_ntoa(packed_addr
));
2777 /* Python interface to getaddrinfo(host, port). */
2781 socket_getaddrinfo(PyObject
*self
, PyObject
*args
)
2783 struct addrinfo hints
, *res
;
2784 struct addrinfo
*res0
= NULL
;
2785 PyObject
*pobj
= (PyObject
*)NULL
;
2788 int family
, socktype
, protocol
, flags
;
2790 PyObject
*all
= (PyObject
*)NULL
;
2791 PyObject
*single
= (PyObject
*)NULL
;
2793 family
= socktype
= protocol
= flags
= 0;
2795 if (!PyArg_ParseTuple(args
, "zO|iiii:getaddrinfo",
2796 &hptr
, &pobj
, &family
, &socktype
,
2797 &protocol
, &flags
)) {
2800 if (PyInt_Check(pobj
)) {
2801 PyOS_snprintf(pbuf
, sizeof(pbuf
), "%ld", PyInt_AsLong(pobj
));
2803 } else if (PyString_Check(pobj
)) {
2804 pptr
= PyString_AsString(pobj
);
2805 } else if (pobj
== Py_None
) {
2806 pptr
= (char *)NULL
;
2808 PyErr_SetString(socket_error
, "Int or String expected");
2811 memset(&hints
, 0, sizeof(hints
));
2812 hints
.ai_family
= family
;
2813 hints
.ai_socktype
= socktype
;
2814 hints
.ai_protocol
= protocol
;
2815 hints
.ai_flags
= flags
;
2816 error
= getaddrinfo(hptr
, pptr
, &hints
, &res0
);
2818 set_gaierror(error
);
2822 if ((all
= PyList_New(0)) == NULL
)
2824 for (res
= res0
; res
; res
= res
->ai_next
) {
2826 makesockaddr(-1, res
->ai_addr
, res
->ai_addrlen
);
2829 single
= Py_BuildValue("iiisO", res
->ai_family
,
2830 res
->ai_socktype
, res
->ai_protocol
,
2831 res
->ai_canonname
? res
->ai_canonname
: "",
2837 if (PyList_Append(all
, single
))
2849 return (PyObject
*)NULL
;
2852 PyDoc_STRVAR(getaddrinfo_doc
,
2853 "getaddrinfo(host, port [, family, socktype, proto, flags])\n\
2854 -> list of (family, socktype, proto, canonname, sockaddr)\n\
2856 Resolve host and port into addrinfo struct.");
2858 /* Python interface to getnameinfo(sa, flags). */
2862 socket_getnameinfo(PyObject
*self
, PyObject
*args
)
2864 PyObject
*sa
= (PyObject
*)NULL
;
2867 int port
, flowinfo
, scope_id
;
2868 char hbuf
[NI_MAXHOST
], pbuf
[NI_MAXSERV
];
2869 struct addrinfo hints
, *res
= NULL
;
2871 PyObject
*ret
= (PyObject
*)NULL
;
2873 flags
= flowinfo
= scope_id
= 0;
2874 if (!PyArg_ParseTuple(args
, "Oi:getnameinfo", &sa
, &flags
))
2876 if (!PyArg_ParseTuple(sa
, "si|ii",
2877 &hostp
, &port
, &flowinfo
, &scope_id
))
2879 PyOS_snprintf(pbuf
, sizeof(pbuf
), "%d", port
);
2880 memset(&hints
, 0, sizeof(hints
));
2881 hints
.ai_family
= AF_UNSPEC
;
2882 hints
.ai_socktype
= SOCK_DGRAM
; /* make numeric port happy */
2883 error
= getaddrinfo(hostp
, pbuf
, &hints
, &res
);
2885 set_gaierror(error
);
2889 PyErr_SetString(socket_error
,
2890 "sockaddr resolved to multiple addresses");
2893 switch (res
->ai_family
) {
2898 if (PyArg_ParseTuple(sa
, "si", &t1
, &t2
) == 0) {
2899 PyErr_SetString(socket_error
,
2900 "IPv4 sockaddr must be 2 tuple");
2908 struct sockaddr_in6
*sin6
;
2909 sin6
= (struct sockaddr_in6
*)res
->ai_addr
;
2910 sin6
->sin6_flowinfo
= flowinfo
;
2911 sin6
->sin6_scope_id
= scope_id
;
2916 error
= getnameinfo(res
->ai_addr
, res
->ai_addrlen
,
2917 hbuf
, sizeof(hbuf
), pbuf
, sizeof(pbuf
), flags
);
2919 set_gaierror(error
);
2922 ret
= Py_BuildValue("ss", hbuf
, pbuf
);
2930 PyDoc_STRVAR(getnameinfo_doc
,
2931 "getnameinfo(sockaddr, flags) --> (host, port)\n\
2933 Get host and port for a sockaddr.");
2936 /* Python API to getting and setting the default timeout value. */
2939 socket_getdefaulttimeout(PyObject
*self
)
2941 if (defaulttimeout
< 0.0) {
2946 return PyFloat_FromDouble(defaulttimeout
);
2949 PyDoc_STRVAR(getdefaulttimeout_doc
,
2950 "getdefaulttimeout() -> timeout\n\
2952 Returns the default timeout in floating seconds for new socket objects.\n\
2953 A value of None indicates that new socket objects have no timeout.\n\
2954 When the socket module is first imported, the default is None.");
2957 socket_setdefaulttimeout(PyObject
*self
, PyObject
*arg
)
2964 timeout
= PyFloat_AsDouble(arg
);
2965 if (timeout
< 0.0) {
2966 if (!PyErr_Occurred())
2967 PyErr_SetString(PyExc_ValueError
,
2968 "Timeout value out of range");
2973 defaulttimeout
= timeout
;
2979 PyDoc_STRVAR(setdefaulttimeout_doc
,
2980 "setdefaulttimeout(timeout)\n\
2982 Set the default timeout in floating seconds for new socket objects.\n\
2983 A value of None indicates that new socket objects have no timeout.\n\
2984 When the socket module is first imported, the default is None.");
2987 /* List of functions exported by this module. */
2989 static PyMethodDef socket_methods
[] = {
2990 {"gethostbyname", socket_gethostbyname
,
2991 METH_VARARGS
, gethostbyname_doc
},
2992 {"gethostbyname_ex", socket_gethostbyname_ex
,
2993 METH_VARARGS
, ghbn_ex_doc
},
2994 {"gethostbyaddr", socket_gethostbyaddr
,
2995 METH_VARARGS
, gethostbyaddr_doc
},
2996 {"gethostname", socket_gethostname
,
2997 METH_VARARGS
, gethostname_doc
},
2998 {"getservbyname", socket_getservbyname
,
2999 METH_VARARGS
, getservbyname_doc
},
3000 {"getprotobyname", socket_getprotobyname
,
3001 METH_VARARGS
,getprotobyname_doc
},
3003 {"fromfd", socket_fromfd
,
3004 METH_VARARGS
, fromfd_doc
},
3006 {"ntohs", socket_ntohs
,
3007 METH_VARARGS
, ntohs_doc
},
3008 {"ntohl", socket_ntohl
,
3010 {"htons", socket_htons
,
3011 METH_VARARGS
, htons_doc
},
3012 {"htonl", socket_htonl
,
3014 {"inet_aton", socket_inet_aton
,
3015 METH_VARARGS
, inet_aton_doc
},
3016 {"inet_ntoa", socket_inet_ntoa
,
3017 METH_VARARGS
, inet_ntoa_doc
},
3018 {"getaddrinfo", socket_getaddrinfo
,
3019 METH_VARARGS
, getaddrinfo_doc
},
3020 {"getnameinfo", socket_getnameinfo
,
3021 METH_VARARGS
, getnameinfo_doc
},
3022 {"getdefaulttimeout", (PyCFunction
)socket_getdefaulttimeout
,
3023 METH_NOARGS
, getdefaulttimeout_doc
},
3024 {"setdefaulttimeout", socket_setdefaulttimeout
,
3025 METH_O
, setdefaulttimeout_doc
},
3026 {NULL
, NULL
} /* Sentinel */
3031 #define OS_INIT_DEFINED
3039 _kernel_swi(0x43380, &r
, &r
);
3040 taskwindow
= r
.r
[0];
3049 #define OS_INIT_DEFINED
3051 /* Additional initialization and cleanup for Windows */
3065 ret
= WSAStartup(0x0101, &WSAData
);
3067 case 0: /* No error */
3069 return 1; /* Success */
3070 case WSASYSNOTREADY
:
3071 PyErr_SetString(PyExc_ImportError
,
3072 "WSAStartup failed: network not ready");
3074 case WSAVERNOTSUPPORTED
:
3078 "WSAStartup failed: requested version not supported");
3081 PyOS_snprintf(buf
, sizeof(buf
),
3082 "WSAStartup failed: error code %d", ret
);
3083 PyErr_SetString(PyExc_ImportError
, buf
);
3086 return 0; /* Failure */
3089 #endif /* MS_WINDOWS */
3093 #define OS_INIT_DEFINED
3095 /* Additional initialization for OS/2 */
3102 int rc
= sock_init();
3105 return 1; /* Success */
3108 PyOS_snprintf(reason
, sizeof(reason
),
3109 "OS/2 TCP/IP Error# %d", sock_errno());
3110 PyErr_SetString(PyExc_ImportError
, reason
);
3112 return 0; /* Failure */
3114 /* No need to initialise sockets with GCC/EMX */
3115 return 1; /* Success */
3119 #endif /* PYOS_OS2 */
3122 #ifndef OS_INIT_DEFINED
3126 return 1; /* Success */
3131 /* C API table - always add new things to the end for binary
3134 PySocketModule_APIObject PySocketModuleAPI
=
3140 /* Initialize the _socket module.
3142 This module is actually called "_socket", and there's a wrapper
3143 "socket.py" which implements some additional functionality. On some
3144 platforms (e.g. Windows and OS/2), socket.py also implements a
3145 wrapper for the socket type that provides missing functionality such
3146 as makefile(), dup() and fromfd(). The import of "_socket" may fail
3147 with an ImportError exception if os-specific initialization fails.
3148 On Windows, this does WINSOCK initialization. When WINSOCK is
3149 initialized succesfully, a call to WSACleanup() is scheduled to be
3153 PyDoc_STRVAR(socket_doc
,
3154 "Implementation module for socket operations.\n\
3156 See the socket module for documentation.");
3166 sock_type
.ob_type
= &PyType_Type
;
3167 m
= Py_InitModule3(PySocket_MODULE_NAME
,
3171 socket_error
= PyErr_NewException("socket.error", NULL
, NULL
);
3172 if (socket_error
== NULL
)
3174 Py_INCREF(socket_error
);
3175 PyModule_AddObject(m
, "error", socket_error
);
3176 socket_herror
= PyErr_NewException("socket.herror",
3177 socket_error
, NULL
);
3178 if (socket_herror
== NULL
)
3180 Py_INCREF(socket_herror
);
3181 PyModule_AddObject(m
, "herror", socket_herror
);
3182 socket_gaierror
= PyErr_NewException("socket.gaierror", socket_error
,
3184 if (socket_gaierror
== NULL
)
3186 Py_INCREF(socket_gaierror
);
3187 PyModule_AddObject(m
, "gaierror", socket_gaierror
);
3188 Py_INCREF((PyObject
*)&sock_type
);
3189 if (PyModule_AddObject(m
, "SocketType",
3190 (PyObject
*)&sock_type
) != 0)
3192 Py_INCREF((PyObject
*)&sock_type
);
3193 if (PyModule_AddObject(m
, "socket",
3194 (PyObject
*)&sock_type
) != 0)
3198 if (PyModule_AddObject(m
, PySocket_CAPI_NAME
,
3199 PyCObject_FromVoidPtr((void *)&PySocketModuleAPI
, NULL
)
3203 /* Address families (we only support AF_INET and AF_UNIX) */
3205 PyModule_AddIntConstant(m
, "AF_UNSPEC", AF_UNSPEC
);
3207 PyModule_AddIntConstant(m
, "AF_INET", AF_INET
);
3209 PyModule_AddIntConstant(m
, "AF_INET6", AF_INET6
);
3210 #endif /* AF_INET6 */
3211 #if defined(AF_UNIX) && !defined(PYOS_OS2)
3212 PyModule_AddIntConstant(m
, "AF_UNIX", AF_UNIX
);
3213 #endif /* AF_UNIX */
3215 /* Amateur Radio AX.25 */
3216 PyModule_AddIntConstant(m
, "AF_AX25", AF_AX25
);
3219 PyModule_AddIntConstant(m
, "AF_IPX", AF_IPX
); /* Novell IPX */
3223 PyModule_AddIntConstant(m
, "AF_APPLETALK", AF_APPLETALK
);
3226 /* Amateur radio NetROM */
3227 PyModule_AddIntConstant(m
, "AF_NETROM", AF_NETROM
);
3230 /* Multiprotocol bridge */
3231 PyModule_AddIntConstant(m
, "AF_BRIDGE", AF_BRIDGE
);
3234 /* Reserved for Werner's ATM */
3235 PyModule_AddIntConstant(m
, "AF_AAL5", AF_AAL5
);
3238 /* Reserved for X.25 project */
3239 PyModule_AddIntConstant(m
, "AF_X25", AF_X25
);
3242 PyModule_AddIntConstant(m
, "AF_INET6", AF_INET6
); /* IP version 6 */
3245 /* Amateur Radio X.25 PLP */
3246 PyModule_AddIntConstant(m
, "AF_ROSE", AF_ROSE
);
3248 #ifdef HAVE_NETPACKET_PACKET_H
3249 PyModule_AddIntConstant(m
, "AF_PACKET", AF_PACKET
);
3250 PyModule_AddIntConstant(m
, "PF_PACKET", PF_PACKET
);
3251 PyModule_AddIntConstant(m
, "PACKET_HOST", PACKET_HOST
);
3252 PyModule_AddIntConstant(m
, "PACKET_BROADCAST", PACKET_BROADCAST
);
3253 PyModule_AddIntConstant(m
, "PACKET_MULTICAST", PACKET_MULTICAST
);
3254 PyModule_AddIntConstant(m
, "PACKET_OTHERHOST", PACKET_OTHERHOST
);
3255 PyModule_AddIntConstant(m
, "PACKET_OUTGOING", PACKET_OUTGOING
);
3256 PyModule_AddIntConstant(m
, "PACKET_LOOPBACK", PACKET_LOOPBACK
);
3257 PyModule_AddIntConstant(m
, "PACKET_FASTROUTE", PACKET_FASTROUTE
);
3261 PyModule_AddIntConstant(m
, "SOCK_STREAM", SOCK_STREAM
);
3262 PyModule_AddIntConstant(m
, "SOCK_DGRAM", SOCK_DGRAM
);
3264 /* We have incomplete socket support. */
3265 PyModule_AddIntConstant(m
, "SOCK_RAW", SOCK_RAW
);
3266 PyModule_AddIntConstant(m
, "SOCK_SEQPACKET", SOCK_SEQPACKET
);
3267 #if defined(SOCK_RDM)
3268 PyModule_AddIntConstant(m
, "SOCK_RDM", SOCK_RDM
);
3273 PyModule_AddIntConstant(m
, "SO_DEBUG", SO_DEBUG
);
3275 #ifdef SO_ACCEPTCONN
3276 PyModule_AddIntConstant(m
, "SO_ACCEPTCONN", SO_ACCEPTCONN
);
3279 PyModule_AddIntConstant(m
, "SO_REUSEADDR", SO_REUSEADDR
);
3282 PyModule_AddIntConstant(m
, "SO_KEEPALIVE", SO_KEEPALIVE
);
3285 PyModule_AddIntConstant(m
, "SO_DONTROUTE", SO_DONTROUTE
);
3288 PyModule_AddIntConstant(m
, "SO_BROADCAST", SO_BROADCAST
);
3290 #ifdef SO_USELOOPBACK
3291 PyModule_AddIntConstant(m
, "SO_USELOOPBACK", SO_USELOOPBACK
);
3294 PyModule_AddIntConstant(m
, "SO_LINGER", SO_LINGER
);
3297 PyModule_AddIntConstant(m
, "SO_OOBINLINE", SO_OOBINLINE
);
3300 PyModule_AddIntConstant(m
, "SO_REUSEPORT", SO_REUSEPORT
);
3303 PyModule_AddIntConstant(m
, "SO_SNDBUF", SO_SNDBUF
);
3306 PyModule_AddIntConstant(m
, "SO_RCVBUF", SO_RCVBUF
);
3309 PyModule_AddIntConstant(m
, "SO_SNDLOWAT", SO_SNDLOWAT
);
3312 PyModule_AddIntConstant(m
, "SO_RCVLOWAT", SO_RCVLOWAT
);
3315 PyModule_AddIntConstant(m
, "SO_SNDTIMEO", SO_SNDTIMEO
);
3318 PyModule_AddIntConstant(m
, "SO_RCVTIMEO", SO_RCVTIMEO
);
3321 PyModule_AddIntConstant(m
, "SO_ERROR", SO_ERROR
);
3324 PyModule_AddIntConstant(m
, "SO_TYPE", SO_TYPE
);
3327 /* Maximum number of connections for "listen" */
3329 PyModule_AddIntConstant(m
, "SOMAXCONN", SOMAXCONN
);
3331 PyModule_AddIntConstant(m
, "SOMAXCONN", 5); /* Common value */
3334 /* Flags for send, recv */
3336 PyModule_AddIntConstant(m
, "MSG_OOB", MSG_OOB
);
3339 PyModule_AddIntConstant(m
, "MSG_PEEK", MSG_PEEK
);
3341 #ifdef MSG_DONTROUTE
3342 PyModule_AddIntConstant(m
, "MSG_DONTROUTE", MSG_DONTROUTE
);
3345 PyModule_AddIntConstant(m
, "MSG_DONTWAIT", MSG_DONTWAIT
);
3348 PyModule_AddIntConstant(m
, "MSG_EOR", MSG_EOR
);
3351 PyModule_AddIntConstant(m
, "MSG_TRUNC", MSG_TRUNC
);
3354 PyModule_AddIntConstant(m
, "MSG_CTRUNC", MSG_CTRUNC
);
3357 PyModule_AddIntConstant(m
, "MSG_WAITALL", MSG_WAITALL
);
3360 PyModule_AddIntConstant(m
, "MSG_BTAG", MSG_BTAG
);
3363 PyModule_AddIntConstant(m
, "MSG_ETAG", MSG_ETAG
);
3366 /* Protocol level and numbers, usable for [gs]etsockopt */
3368 PyModule_AddIntConstant(m
, "SOL_SOCKET", SOL_SOCKET
);
3371 PyModule_AddIntConstant(m
, "SOL_IP", SOL_IP
);
3373 PyModule_AddIntConstant(m
, "SOL_IP", 0);
3376 PyModule_AddIntConstant(m
, "SOL_IPX", SOL_IPX
);
3379 PyModule_AddIntConstant(m
, "SOL_AX25", SOL_AX25
);
3382 PyModule_AddIntConstant(m
, "SOL_ATALK", SOL_ATALK
);
3385 PyModule_AddIntConstant(m
, "SOL_NETROM", SOL_NETROM
);
3388 PyModule_AddIntConstant(m
, "SOL_ROSE", SOL_ROSE
);
3391 PyModule_AddIntConstant(m
, "SOL_TCP", SOL_TCP
);
3393 PyModule_AddIntConstant(m
, "SOL_TCP", 6);
3396 PyModule_AddIntConstant(m
, "SOL_UDP", SOL_UDP
);
3398 PyModule_AddIntConstant(m
, "SOL_UDP", 17);
3401 PyModule_AddIntConstant(m
, "IPPROTO_IP", IPPROTO_IP
);
3403 PyModule_AddIntConstant(m
, "IPPROTO_IP", 0);
3405 #ifdef IPPROTO_HOPOPTS
3406 PyModule_AddIntConstant(m
, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS
);
3409 PyModule_AddIntConstant(m
, "IPPROTO_ICMP", IPPROTO_ICMP
);
3411 PyModule_AddIntConstant(m
, "IPPROTO_ICMP", 1);
3414 PyModule_AddIntConstant(m
, "IPPROTO_IGMP", IPPROTO_IGMP
);
3417 PyModule_AddIntConstant(m
, "IPPROTO_GGP", IPPROTO_GGP
);
3420 PyModule_AddIntConstant(m
, "IPPROTO_IPV4", IPPROTO_IPV4
);
3423 PyModule_AddIntConstant(m
, "IPPROTO_IPIP", IPPROTO_IPIP
);
3426 PyModule_AddIntConstant(m
, "IPPROTO_TCP", IPPROTO_TCP
);
3428 PyModule_AddIntConstant(m
, "IPPROTO_TCP", 6);
3431 PyModule_AddIntConstant(m
, "IPPROTO_EGP", IPPROTO_EGP
);
3434 PyModule_AddIntConstant(m
, "IPPROTO_PUP", IPPROTO_PUP
);
3437 PyModule_AddIntConstant(m
, "IPPROTO_UDP", IPPROTO_UDP
);
3439 PyModule_AddIntConstant(m
, "IPPROTO_UDP", 17);
3442 PyModule_AddIntConstant(m
, "IPPROTO_IDP", IPPROTO_IDP
);
3444 #ifdef IPPROTO_HELLO
3445 PyModule_AddIntConstant(m
, "IPPROTO_HELLO", IPPROTO_HELLO
);
3448 PyModule_AddIntConstant(m
, "IPPROTO_ND", IPPROTO_ND
);
3451 PyModule_AddIntConstant(m
, "IPPROTO_TP", IPPROTO_TP
);
3454 PyModule_AddIntConstant(m
, "IPPROTO_IPV6", IPPROTO_IPV6
);
3456 #ifdef IPPROTO_ROUTING
3457 PyModule_AddIntConstant(m
, "IPPROTO_ROUTING", IPPROTO_ROUTING
);
3459 #ifdef IPPROTO_FRAGMENT
3460 PyModule_AddIntConstant(m
, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT
);
3463 PyModule_AddIntConstant(m
, "IPPROTO_RSVP", IPPROTO_RSVP
);
3466 PyModule_AddIntConstant(m
, "IPPROTO_GRE", IPPROTO_GRE
);
3469 PyModule_AddIntConstant(m
, "IPPROTO_ESP", IPPROTO_ESP
);
3472 PyModule_AddIntConstant(m
, "IPPROTO_AH", IPPROTO_AH
);
3474 #ifdef IPPROTO_MOBILE
3475 PyModule_AddIntConstant(m
, "IPPROTO_MOBILE", IPPROTO_MOBILE
);
3477 #ifdef IPPROTO_ICMPV6
3478 PyModule_AddIntConstant(m
, "IPPROTO_ICMPV6", IPPROTO_ICMPV6
);
3481 PyModule_AddIntConstant(m
, "IPPROTO_NONE", IPPROTO_NONE
);
3483 #ifdef IPPROTO_DSTOPTS
3484 PyModule_AddIntConstant(m
, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS
);
3487 PyModule_AddIntConstant(m
, "IPPROTO_XTP", IPPROTO_XTP
);
3490 PyModule_AddIntConstant(m
, "IPPROTO_EON", IPPROTO_EON
);
3493 PyModule_AddIntConstant(m
, "IPPROTO_PIM", IPPROTO_PIM
);
3495 #ifdef IPPROTO_IPCOMP
3496 PyModule_AddIntConstant(m
, "IPPROTO_IPCOMP", IPPROTO_IPCOMP
);
3499 PyModule_AddIntConstant(m
, "IPPROTO_VRRP", IPPROTO_VRRP
);
3502 PyModule_AddIntConstant(m
, "IPPROTO_BIP", IPPROTO_BIP
);
3506 PyModule_AddIntConstant(m
, "IPPROTO_RAW", IPPROTO_RAW
);
3508 PyModule_AddIntConstant(m
, "IPPROTO_RAW", 255);
3511 PyModule_AddIntConstant(m
, "IPPROTO_MAX", IPPROTO_MAX
);
3514 /* Some port configuration */
3515 #ifdef IPPORT_RESERVED
3516 PyModule_AddIntConstant(m
, "IPPORT_RESERVED", IPPORT_RESERVED
);
3518 PyModule_AddIntConstant(m
, "IPPORT_RESERVED", 1024);
3520 #ifdef IPPORT_USERRESERVED
3521 PyModule_AddIntConstant(m
, "IPPORT_USERRESERVED", IPPORT_USERRESERVED
);
3523 PyModule_AddIntConstant(m
, "IPPORT_USERRESERVED", 5000);
3526 /* Some reserved IP v.4 addresses */
3528 PyModule_AddIntConstant(m
, "INADDR_ANY", INADDR_ANY
);
3530 PyModule_AddIntConstant(m
, "INADDR_ANY", 0x00000000);
3532 #ifdef INADDR_BROADCAST
3533 PyModule_AddIntConstant(m
, "INADDR_BROADCAST", INADDR_BROADCAST
);
3535 PyModule_AddIntConstant(m
, "INADDR_BROADCAST", 0xffffffff);
3537 #ifdef INADDR_LOOPBACK
3538 PyModule_AddIntConstant(m
, "INADDR_LOOPBACK", INADDR_LOOPBACK
);
3540 PyModule_AddIntConstant(m
, "INADDR_LOOPBACK", 0x7F000001);
3542 #ifdef INADDR_UNSPEC_GROUP
3543 PyModule_AddIntConstant(m
, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP
);
3545 PyModule_AddIntConstant(m
, "INADDR_UNSPEC_GROUP", 0xe0000000);
3547 #ifdef INADDR_ALLHOSTS_GROUP
3548 PyModule_AddIntConstant(m
, "INADDR_ALLHOSTS_GROUP",
3549 INADDR_ALLHOSTS_GROUP
);
3551 PyModule_AddIntConstant(m
, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
3553 #ifdef INADDR_MAX_LOCAL_GROUP
3554 PyModule_AddIntConstant(m
, "INADDR_MAX_LOCAL_GROUP",
3555 INADDR_MAX_LOCAL_GROUP
);
3557 PyModule_AddIntConstant(m
, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
3560 PyModule_AddIntConstant(m
, "INADDR_NONE", INADDR_NONE
);
3562 PyModule_AddIntConstant(m
, "INADDR_NONE", 0xffffffff);
3565 /* IPv4 [gs]etsockopt options */
3567 PyModule_AddIntConstant(m
, "IP_OPTIONS", IP_OPTIONS
);
3570 PyModule_AddIntConstant(m
, "IP_HDRINCL", IP_HDRINCL
);
3573 PyModule_AddIntConstant(m
, "IP_TOS", IP_TOS
);
3576 PyModule_AddIntConstant(m
, "IP_TTL", IP_TTL
);
3579 PyModule_AddIntConstant(m
, "IP_RECVOPTS", IP_RECVOPTS
);
3581 #ifdef IP_RECVRETOPTS
3582 PyModule_AddIntConstant(m
, "IP_RECVRETOPTS", IP_RECVRETOPTS
);
3584 #ifdef IP_RECVDSTADDR
3585 PyModule_AddIntConstant(m
, "IP_RECVDSTADDR", IP_RECVDSTADDR
);
3588 PyModule_AddIntConstant(m
, "IP_RETOPTS", IP_RETOPTS
);
3590 #ifdef IP_MULTICAST_IF
3591 PyModule_AddIntConstant(m
, "IP_MULTICAST_IF", IP_MULTICAST_IF
);
3593 #ifdef IP_MULTICAST_TTL
3594 PyModule_AddIntConstant(m
, "IP_MULTICAST_TTL", IP_MULTICAST_TTL
);
3596 #ifdef IP_MULTICAST_LOOP
3597 PyModule_AddIntConstant(m
, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP
);
3599 #ifdef IP_ADD_MEMBERSHIP
3600 PyModule_AddIntConstant(m
, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP
);
3602 #ifdef IP_DROP_MEMBERSHIP
3603 PyModule_AddIntConstant(m
, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP
);
3605 #ifdef IP_DEFAULT_MULTICAST_TTL
3606 PyModule_AddIntConstant(m
, "IP_DEFAULT_MULTICAST_TTL",
3607 IP_DEFAULT_MULTICAST_TTL
);
3609 #ifdef IP_DEFAULT_MULTICAST_LOOP
3610 PyModule_AddIntConstant(m
, "IP_DEFAULT_MULTICAST_LOOP",
3611 IP_DEFAULT_MULTICAST_LOOP
);
3613 #ifdef IP_MAX_MEMBERSHIPS
3614 PyModule_AddIntConstant(m
, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS
);
3617 /* IPv6 [gs]etsockopt options, defined in RFC2553 */
3618 #ifdef IPV6_JOIN_GROUP
3619 PyModule_AddIntConstant(m
, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP
);
3621 #ifdef IPV6_LEAVE_GROUP
3622 PyModule_AddIntConstant(m
, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP
);
3624 #ifdef IPV6_MULTICAST_HOPS
3625 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS
);
3627 #ifdef IPV6_MULTICAST_IF
3628 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF
);
3630 #ifdef IPV6_MULTICAST_LOOP
3631 PyModule_AddIntConstant(m
, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP
);
3633 #ifdef IPV6_UNICAST_HOPS
3634 PyModule_AddIntConstant(m
, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS
);
3639 PyModule_AddIntConstant(m
, "TCP_NODELAY", TCP_NODELAY
);
3642 PyModule_AddIntConstant(m
, "TCP_MAXSEG", TCP_MAXSEG
);
3645 PyModule_AddIntConstant(m
, "TCP_CORK", TCP_CORK
);
3648 PyModule_AddIntConstant(m
, "TCP_KEEPIDLE", TCP_KEEPIDLE
);
3650 #ifdef TCP_KEEPINTVL
3651 PyModule_AddIntConstant(m
, "TCP_KEEPINTVL", TCP_KEEPINTVL
);
3654 PyModule_AddIntConstant(m
, "TCP_KEEPCNT", TCP_KEEPCNT
);
3657 PyModule_AddIntConstant(m
, "TCP_SYNCNT", TCP_SYNCNT
);
3660 PyModule_AddIntConstant(m
, "TCP_LINGER2", TCP_LINGER2
);
3662 #ifdef TCP_DEFER_ACCEPT
3663 PyModule_AddIntConstant(m
, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT
);
3665 #ifdef TCP_WINDOW_CLAMP
3666 PyModule_AddIntConstant(m
, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP
);
3669 PyModule_AddIntConstant(m
, "TCP_INFO", TCP_INFO
);
3672 PyModule_AddIntConstant(m
, "TCP_QUICKACK", TCP_QUICKACK
);
3678 PyModule_AddIntConstant(m
, "IPX_TYPE", IPX_TYPE
);
3681 /* get{addr,name}info parameters */
3682 #ifdef EAI_ADDRFAMILY
3683 PyModule_AddIntConstant(m
, "EAI_ADDRFAMILY", EAI_ADDRFAMILY
);
3686 PyModule_AddIntConstant(m
, "EAI_AGAIN", EAI_AGAIN
);
3689 PyModule_AddIntConstant(m
, "EAI_BADFLAGS", EAI_BADFLAGS
);
3692 PyModule_AddIntConstant(m
, "EAI_FAIL", EAI_FAIL
);
3695 PyModule_AddIntConstant(m
, "EAI_FAMILY", EAI_FAMILY
);
3698 PyModule_AddIntConstant(m
, "EAI_MEMORY", EAI_MEMORY
);
3701 PyModule_AddIntConstant(m
, "EAI_NODATA", EAI_NODATA
);
3704 PyModule_AddIntConstant(m
, "EAI_NONAME", EAI_NONAME
);
3707 PyModule_AddIntConstant(m
, "EAI_SERVICE", EAI_SERVICE
);
3710 PyModule_AddIntConstant(m
, "EAI_SOCKTYPE", EAI_SOCKTYPE
);
3713 PyModule_AddIntConstant(m
, "EAI_SYSTEM", EAI_SYSTEM
);
3716 PyModule_AddIntConstant(m
, "EAI_BADHINTS", EAI_BADHINTS
);
3719 PyModule_AddIntConstant(m
, "EAI_PROTOCOL", EAI_PROTOCOL
);
3722 PyModule_AddIntConstant(m
, "EAI_MAX", EAI_MAX
);
3725 PyModule_AddIntConstant(m
, "AI_PASSIVE", AI_PASSIVE
);
3728 PyModule_AddIntConstant(m
, "AI_CANONNAME", AI_CANONNAME
);
3730 #ifdef AI_NUMERICHOST
3731 PyModule_AddIntConstant(m
, "AI_NUMERICHOST", AI_NUMERICHOST
);
3734 PyModule_AddIntConstant(m
, "AI_MASK", AI_MASK
);
3737 PyModule_AddIntConstant(m
, "AI_ALL", AI_ALL
);
3739 #ifdef AI_V4MAPPED_CFG
3740 PyModule_AddIntConstant(m
, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG
);
3742 #ifdef AI_ADDRCONFIG
3743 PyModule_AddIntConstant(m
, "AI_ADDRCONFIG", AI_ADDRCONFIG
);
3746 PyModule_AddIntConstant(m
, "AI_V4MAPPED", AI_V4MAPPED
);
3749 PyModule_AddIntConstant(m
, "AI_DEFAULT", AI_DEFAULT
);
3752 PyModule_AddIntConstant(m
, "NI_MAXHOST", NI_MAXHOST
);
3755 PyModule_AddIntConstant(m
, "NI_MAXSERV", NI_MAXSERV
);
3758 PyModule_AddIntConstant(m
, "NI_NOFQDN", NI_NOFQDN
);
3760 #ifdef NI_NUMERICHOST
3761 PyModule_AddIntConstant(m
, "NI_NUMERICHOST", NI_NUMERICHOST
);
3764 PyModule_AddIntConstant(m
, "NI_NAMEREQD", NI_NAMEREQD
);
3766 #ifdef NI_NUMERICSERV
3767 PyModule_AddIntConstant(m
, "NI_NUMERICSERV", NI_NUMERICSERV
);
3770 PyModule_AddIntConstant(m
, "NI_DGRAM", NI_DGRAM
);
3773 /* Initialize gethostbyname lock */
3774 #ifdef USE_GETHOSTBYNAME_LOCK
3775 gethostbyname_lock
= PyThread_allocate_lock();
3780 #ifndef HAVE_INET_PTON
3782 /* Simplistic emulation code for inet_pton that only works for IPv4 */
3785 inet_pton(int af
, const char *src
, void *dst
)
3787 if (af
== AF_INET
) {
3789 packed_addr
= inet_addr(src
);
3790 if (packed_addr
== INADDR_NONE
)
3792 memcpy(dst
, &packed_addr
, 4);
3795 /* Should set errno to EAFNOSUPPORT */
3800 inet_ntop(int af
, const void *src
, char *dst
, socklen_t size
)
3802 if (af
== AF_INET
) {
3803 struct in_addr packed_addr
;
3805 /* Should set errno to ENOSPC. */
3807 memcpy(&packed_addr
, src
, sizeof(packed_addr
));
3808 return strncpy(dst
, inet_ntoa(packed_addr
), size
);
3810 /* Should set errno to EAFNOSUPPORT */