3 /* SSL support based on patches by Brian E Gallew and Laszlo Kovacs */
6 This module provides an interface to Berkeley socket IPC.
10 - only AF_INET and AF_UNIX address families are supported in a
11 portable manner, though AF_PACKET is supported under Linux.
12 - no read/write operations (use send/recv or makefile instead)
13 - additional restrictions apply on Windows
17 - socket.error: exception raised for socket specific errors
18 - socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')
19 - socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])
20 - socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com')
21 - socket.getprotobyname(protocolname) --> protocol number
22 - socket.getservbyname(servicename, protocolname) --> port number
23 - socket.socket(family, type [, proto]) --> new socket object
24 - socket.ntohs(16 bit value) --> new int object
25 - socket.ntohl(32 bit value) --> new int object
26 - socket.htons(16 bit value) --> new int object
27 - socket.htonl(32 bit value) --> new int object
28 - socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
29 - socket.inet_aton(IP address) -> 32-bit packed IP representation
30 - socket.inet_ntoa(packed IP) -> IP address string
31 - socket.ssl(socket, keyfile, certfile) -> new ssl object
32 - an Internet socket address is a pair (hostname, port)
33 where hostname can be anything recognized by gethostbyname()
34 (including the dd.dd.dd.dd notation) and port is in host byte order
35 - where a hostname is returned, the dd.dd.dd.dd notation is used
36 - a UNIX domain socket address is a string specifying the pathname
37 - an AF_PACKET socket address is a tuple containing a string
38 specifying the ethernet interface and an integer specifying
39 the Ethernet protocol number to be received. For example:
40 ("eth0",0x1234). Optional 3rd,4th,5th elements in the tuple
41 specify packet-type and ha-type/addr -- these are ignored by
42 networking code, but accepted since they are returned by the
47 - s.accept() --> new socket object, sockaddr
48 - s.bind(sockaddr) --> None
50 - s.connect(sockaddr) --> None
51 - s.connect_ex(sockaddr) --> 0 or errno (handy for e.g. async connect)
52 - s.fileno() --> file descriptor
53 - s.dup() --> same as socket.fromfd(os.dup(s.fileno(), ...)
54 - s.getpeername() --> sockaddr
55 - s.getsockname() --> sockaddr
56 - s.getsockopt(level, optname[, buflen]) --> int or string
57 - s.listen(backlog) --> None
58 - s.makefile([mode[, bufsize]]) --> file object
59 - s.recv(buflen [,flags]) --> string
60 - s.recvfrom(buflen [,flags]) --> string, sockaddr
61 - s.send(string [,flags]) --> nbytes
62 - s.sendto(string, [flags,] sockaddr) --> nbytes
63 - s.setblocking(0 | 1) --> None
64 - s.setsockopt(level, optname, value) --> None
65 - s.shutdown(how) --> None
66 - repr(s) --> "<socket object, fd=%d, family=%d, type=%d, protocol=%d>"
72 /* Hacks for gethostbyname_r(). On some non-Linux platforms, the configure
73 script doesn't get this right, so we hardcode some platform checks below.
74 On the other hand, not all Linux versions agree, so there the settings
75 computed by the configure script are needed! */
78 #undef HAVE_GETHOSTBYNAME_R_3_ARG
79 #undef HAVE_GETHOSTBYNAME_R_5_ARG
80 #undef HAVE_GETHOSTBYNAME_R_6_ARG
84 #undef HAVE_GETHOSTBYNAME_R
87 #ifdef HAVE_GETHOSTBYNAME_R
88 #if defined(_AIX) || defined(__osf__)
89 #define HAVE_GETHOSTBYNAME_R_3_ARG
90 #elif defined(__sun__) || defined(__sgi)
91 #define HAVE_GETHOSTBYNAME_R_5_ARG
93 /* Rely on the configure script */
95 #undef HAVE_GETHOSTBYNAME_R
99 #if !defined(HAVE_GETHOSTBYNAME_R) && defined(WITH_THREAD) && !defined(MS_WINDOWS)
100 #define USE_GETHOSTBYNAME_LOCK
103 #ifdef USE_GETHOSTBYNAME_LOCK
104 #include "pythread.h"
111 #if defined(PYCC_VACPP)
114 #include <sys/ioctl.h>
119 #if defined(PYOS_OS2)
121 #define INCL_DOSERRORS
126 #include <sys/types.h>
131 #include <sys/socket.h>
132 #include <netinet/in.h>
133 #if !(defined(__BEOS__) || defined(__CYGWIN__))
134 #include <netinet/tcp.h>
137 /* Headers needed for inet_ntoa() and inet_addr() */
139 #include <net/netdb.h>
142 #include <arpa/inet.h>
157 #if defined(linux) && defined(AF_PACKET)
158 #include <sys/ioctl.h>
160 #include <netpacket/packet.h>
164 #define O_NDELAY O_NONBLOCK /* For QNX only? */
168 /* fdopen() isn't declared in stdio.h (sigh) */
173 #include "openssl/rsa.h"
174 #include "openssl/crypto.h"
175 #include "openssl/x509.h"
176 #include "openssl/pem.h"
177 #include "openssl/ssl.h"
178 #include "openssl/err.h"
181 #if defined(MS_WINDOWS) || defined(__BEOS__)
182 /* BeOS suffers from the same socket dichotomy as Win32... - [cjh] */
183 /* seem to be a few differences in the API */
184 #define SOCKETCLOSE closesocket
185 #define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */
188 /* abstract the socket file descriptor type */
190 typedef SOCKET SOCKET_T
;
192 # define SIZEOF_SOCKET_T 8
194 # define SIZEOF_SOCKET_T 4
197 typedef int SOCKET_T
;
198 # define SIZEOF_SOCKET_T SIZEOF_INT
202 #if defined(PYOS_OS2)
203 #define SOCKETCLOSE soclose
204 #define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
208 #define SOCKETCLOSE close
211 /* Global variable holding the exception type for errors detected
212 by this module (but not argument type or memory errors, etc.). */
214 static PyObject
*PySocket_Error
;
217 static PyObject
*SSLErrorObject
;
221 /* Convenience function to raise an error according to errno
222 and return a NULL pointer from a function. */
228 int err_no
= WSAGetLastError();
230 static struct { int no
; const char *msg
; } *msgp
, msgs
[] = {
231 { WSAEINTR
, "Interrupted system call" },
232 { WSAEBADF
, "Bad file descriptor" },
233 { WSAEACCES
, "Permission denied" },
234 { WSAEFAULT
, "Bad address" },
235 { WSAEINVAL
, "Invalid argument" },
236 { WSAEMFILE
, "Too many open files" },
238 "The socket operation could not complete "
239 "without blocking" },
240 { WSAEINPROGRESS
, "Operation now in progress" },
241 { WSAEALREADY
, "Operation already in progress" },
242 { WSAENOTSOCK
, "Socket operation on non-socket" },
243 { WSAEDESTADDRREQ
, "Destination address required" },
244 { WSAEMSGSIZE
, "Message too long" },
245 { WSAEPROTOTYPE
, "Protocol wrong type for socket" },
246 { WSAENOPROTOOPT
, "Protocol not available" },
247 { WSAEPROTONOSUPPORT
, "Protocol not supported" },
248 { WSAESOCKTNOSUPPORT
, "Socket type not supported" },
249 { WSAEOPNOTSUPP
, "Operation not supported" },
250 { WSAEPFNOSUPPORT
, "Protocol family not supported" },
251 { WSAEAFNOSUPPORT
, "Address family not supported" },
252 { WSAEADDRINUSE
, "Address already in use" },
254 "Can't assign requested address" },
255 { WSAENETDOWN
, "Network is down" },
256 { WSAENETUNREACH
, "Network is unreachable" },
258 "Network dropped connection on reset" },
260 "Software caused connection abort" },
261 { WSAECONNRESET
, "Connection reset by peer" },
262 { WSAENOBUFS
, "No buffer space available" },
263 { WSAEISCONN
, "Socket is already connected" },
264 { WSAENOTCONN
, "Socket is not connected" },
265 { WSAESHUTDOWN
, "Can't send after socket shutdown" },
267 "Too many references: can't splice" },
268 { WSAETIMEDOUT
, "Operation timed out" },
269 { WSAECONNREFUSED
, "Connection refused" },
270 { WSAELOOP
, "Too many levels of symbolic links" },
271 { WSAENAMETOOLONG
, "File name too long" },
272 { WSAEHOSTDOWN
, "Host is down" },
273 { WSAEHOSTUNREACH
, "No route to host" },
274 { WSAENOTEMPTY
, "Directory not empty" },
275 { WSAEPROCLIM
, "Too many processes" },
276 { WSAEUSERS
, "Too many users" },
277 { WSAEDQUOT
, "Disc quota exceeded" },
278 { WSAESTALE
, "Stale NFS file handle" },
279 { WSAEREMOTE
, "Too many levels of remote in path" },
281 "Network subsystem is unvailable" },
282 { WSAVERNOTSUPPORTED
,
283 "WinSock version is not supported" },
285 "Successful WSAStartup() not yet performed" },
286 { WSAEDISCON
, "Graceful shutdown in progress" },
287 /* Resolver errors */
288 { WSAHOST_NOT_FOUND
, "No such host is known" },
289 { WSATRY_AGAIN
, "Host not found, or server failed" },
291 "Unexpected server error encountered" },
292 { WSANO_DATA
, "Valid name without requested data" },
293 { WSANO_ADDRESS
, "No address, look for MX record" },
297 const char *msg
= "winsock error";
299 for (msgp
= msgs
; msgp
->msg
; msgp
++) {
300 if (err_no
== msgp
->no
) {
306 v
= Py_BuildValue("(is)", err_no
, msg
);
308 PyErr_SetObject(PySocket_Error
, v
);
316 #if defined(PYOS_OS2)
317 if (sock_errno() != NO_ERROR
) {
321 int myerrorcode
= sock_errno();
323 /* Retrieve Socket-Related Error Message from MPTN.MSG File */
324 rc
= DosGetMessage(NULL
, 0, outbuf
, sizeof(outbuf
),
325 myerrorcode
- SOCBASEERR
+ 26, "mptn.msg", &msglen
);
326 if (rc
== NO_ERROR
) {
329 outbuf
[msglen
] = '\0'; /* OS/2 Doesn't Guarantee a Terminator */
330 if (strlen(outbuf
) > 0) { /* If Non-Empty Msg, Trim CRLF */
331 char *lastc
= &outbuf
[ strlen(outbuf
)-1 ];
332 while (lastc
> outbuf
&& isspace(*lastc
))
333 *lastc
-- = '\0'; /* Trim Trailing Whitespace (CRLF) */
335 v
= Py_BuildValue("(is)", myerrorcode
, outbuf
);
337 PyErr_SetObject(PySocket_Error
, v
);
345 return PyErr_SetFromErrno(PySocket_Error
);
349 /* The object holding a socket. It holds some extra information,
350 like the address family, which is used to decode socket address
351 arguments properly. */
355 SOCKET_T sock_fd
; /* Socket file descriptor */
356 int sock_family
; /* Address family, e.g., AF_INET */
357 int sock_type
; /* Socket type, e.g., SOCK_STREAM */
358 int sock_proto
; /* Protocol type, usually 0 */
360 struct sockaddr_in in
;
362 struct sockaddr_un un
;
364 #if defined(linux) && defined(AF_PACKET)
365 struct sockaddr_ll ll
;
368 } PySocketSockObject
;
374 PySocketSockObject
*Socket
; /* Socket on which we're layered */
375 PyObject
*x_attr
; /* Attributes dictionary */
385 staticforward PyTypeObject SSL_Type
;
386 staticforward PyObject
*SSL_SSLwrite(SSLObject
*self
, PyObject
*args
);
387 staticforward PyObject
*SSL_SSLread(SSLObject
*self
, PyObject
*args
);
389 #define SSLObject_Check(v) ((v)->ob_type == &SSL_Type)
393 /* A forward reference to the Socktype type object.
394 The Socktype variable contains pointers to various functions,
395 some of which call newsockobject(), which uses Socktype, so
396 there has to be a circular reference. */
398 staticforward PyTypeObject PySocketSock_Type
;
401 /* Create a new socket object.
402 This just creates the object and initializes it.
403 If the creation fails, return NULL and set an exception (implicit
406 static PySocketSockObject
*
407 PySocketSock_New(SOCKET_T fd
, int family
, int type
, int proto
)
409 PySocketSockObject
*s
;
410 PySocketSock_Type
.ob_type
= &PyType_Type
;
411 s
= PyObject_New(PySocketSockObject
, &PySocketSock_Type
);
414 s
->sock_family
= family
;
416 s
->sock_proto
= proto
;
422 /* Lock to allow python interpreter to continue, but only allow one
423 thread to be in gethostbyname */
424 #ifdef USE_GETHOSTBYNAME_LOCK
425 PyThread_type_lock gethostbyname_lock
;
429 /* Convert a string specifying a host name or one of a few symbolic
430 names to a numeric IP address. This usually calls gethostbyname()
431 to do the work; the names "" and "<broadcast>" are special.
432 Return the length (should always be 4 bytes), or negative if
433 an error occurred; then an exception is raised. */
436 setipaddr(char* name
, struct sockaddr_in
* addr_ret
)
442 #ifdef HAVE_GETHOSTBYNAME_R
443 struct hostent hp_allocated
;
444 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
445 struct hostent_data data
;
448 int buf_len
= (sizeof buf
) - 1;
451 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
454 #endif /* HAVE_GETHOSTBYNAME_R */
456 memset((void *) addr_ret
, '\0', sizeof(*addr_ret
));
457 if (name
[0] == '\0') {
458 addr_ret
->sin_addr
.s_addr
= INADDR_ANY
;
461 if (name
[0] == '<' && strcmp(name
, "<broadcast>") == 0) {
462 addr_ret
->sin_addr
.s_addr
= INADDR_BROADCAST
;
465 if (sscanf(name
, "%d.%d.%d.%d%c", &d1
, &d2
, &d3
, &d4
, &ch
) == 4 &&
466 0 <= d1
&& d1
<= 255 && 0 <= d2
&& d2
<= 255 &&
467 0 <= d3
&& d3
<= 255 && 0 <= d4
&& d4
<= 255) {
468 addr_ret
->sin_addr
.s_addr
= htonl(
469 ((long) d1
<< 24) | ((long) d2
<< 16) |
470 ((long) d3
<< 8) | ((long) d4
<< 0));
473 Py_BEGIN_ALLOW_THREADS
474 #ifdef HAVE_GETHOSTBYNAME_R
475 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
476 result
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
, &hp
, &errnop
);
477 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
478 hp
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
, &errnop
);
479 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
480 memset((void *) &data
, '\0', sizeof(data
));
481 result
= gethostbyname_r(name
, &hp_allocated
, &data
);
482 hp
= (result
!= 0) ? NULL
: &hp_allocated
;
484 #else /* not HAVE_GETHOSTBYNAME_R */
485 #ifdef USE_GETHOSTBYNAME_LOCK
486 PyThread_acquire_lock(gethostbyname_lock
, 1);
488 hp
= gethostbyname(name
);
489 #endif /* HAVE_GETHOSTBYNAME_R */
493 #ifdef HAVE_HSTRERROR
494 /* Let's get real error message to return */
496 PyErr_SetString(PySocket_Error
, (char *)hstrerror(h_errno
));
498 PyErr_SetString(PySocket_Error
, "host not found");
500 #ifdef USE_GETHOSTBYNAME_LOCK
501 PyThread_release_lock(gethostbyname_lock
);
505 memcpy((char *) &addr_ret
->sin_addr
, hp
->h_addr
, hp
->h_length
);
506 h_length
= hp
->h_length
;
507 #ifdef USE_GETHOSTBYNAME_LOCK
508 PyThread_release_lock(gethostbyname_lock
);
514 /* Create a string object representing an IP address.
515 This is always a string of the form 'dd.dd.dd.dd' (with variable
519 makeipaddr(struct sockaddr_in
*addr
)
521 long x
= ntohl(addr
->sin_addr
.s_addr
);
523 sprintf(buf
, "%d.%d.%d.%d",
524 (int) (x
>>24) & 0xff, (int) (x
>>16) & 0xff,
525 (int) (x
>> 8) & 0xff, (int) (x
>> 0) & 0xff);
526 return PyString_FromString(buf
);
530 /* Create an object representing the given socket address,
531 suitable for passing it back to bind(), connect() etc.
532 The family field of the sockaddr structure is inspected
533 to determine what kind of address it really is. */
537 makesockaddr(int sockfd
, struct sockaddr
*addr
, int addrlen
)
540 /* No address -- may be recvfrom() from known socket */
546 /* XXX: BeOS version of accept() doesn't set family correctly */
547 addr
->sa_family
= AF_INET
;
550 switch (addr
->sa_family
) {
554 struct sockaddr_in
*a
= (struct sockaddr_in
*) addr
;
555 PyObject
*addrobj
= makeipaddr(a
);
556 PyObject
*ret
= NULL
;
558 ret
= Py_BuildValue("Oi", addrobj
, ntohs(a
->sin_port
));
567 struct sockaddr_un
*a
= (struct sockaddr_un
*) addr
;
568 return PyString_FromString(a
->sun_path
);
572 #if defined(linux) && defined(AF_PACKET)
575 struct sockaddr_ll
*a
= (struct sockaddr_ll
*)addr
;
578 /* need to look up interface name give index */
579 if (a
->sll_ifindex
) {
580 ifr
.ifr_ifindex
= a
->sll_ifindex
;
581 if (ioctl(sockfd
, SIOCGIFNAME
, &ifr
) == 0)
582 ifname
= ifr
.ifr_name
;
584 return Py_BuildValue("shbhs#", ifname
, ntohs(a
->sll_protocol
),
585 a
->sll_pkttype
, a
->sll_hatype
,
586 a
->sll_addr
, a
->sll_halen
);
590 /* More cases here... */
593 /* If we don't know the address family, don't raise an
594 exception -- return it as a tuple. */
595 return Py_BuildValue("is#",
598 sizeof(addr
->sa_data
));
604 /* Parse a socket address argument according to the socket object's
605 address family. Return 1 if the address was in the proper format,
606 0 of not. The address is returned through addr_ret, its length
610 getsockaddrarg(PySocketSockObject
*s
, PyObject
*args
,
611 struct sockaddr
**addr_ret
, int *len_ret
)
613 switch (s
->sock_family
) {
618 struct sockaddr_un
* addr
;
621 addr
= (struct sockaddr_un
* )&(s
->sock_addr
).un
;
622 if (!PyArg_Parse(args
, "t#", &path
, &len
))
624 if (len
> sizeof addr
->sun_path
) {
625 PyErr_SetString(PySocket_Error
,
626 "AF_UNIX path too long");
629 addr
->sun_family
= AF_UNIX
;
630 memcpy(addr
->sun_path
, path
, len
);
631 addr
->sun_path
[len
] = 0;
632 *addr_ret
= (struct sockaddr
*) addr
;
633 *len_ret
= len
+ sizeof(*addr
) - sizeof(addr
->sun_path
);
640 struct sockaddr_in
* addr
;
643 addr
=(struct sockaddr_in
*)&(s
->sock_addr
).in
;
644 if (!PyTuple_Check(args
)) {
645 PyErr_Format(PyExc_TypeError
,
646 "getsockaddrarg: AF_INET address must be tuple, not %.500s",
647 args
->ob_type
->tp_name
);
650 if (!PyArg_ParseTuple(args
, "si:getsockaddrarg", &host
, &port
))
652 if (setipaddr(host
, addr
) < 0)
654 addr
->sin_family
= AF_INET
;
655 addr
->sin_port
= htons((short)port
);
656 *addr_ret
= (struct sockaddr
*) addr
;
657 *len_ret
= sizeof *addr
;
661 #if defined(linux) && defined(AF_PACKET)
664 struct sockaddr_ll
* addr
;
672 if (!PyArg_ParseTuple(args
, "si|iis", &interfaceName
,
673 &protoNumber
, &pkttype
, &hatype
, &haddr
))
675 strncpy(ifr
.ifr_name
, interfaceName
, sizeof(ifr
.ifr_name
));
676 ifr
.ifr_name
[(sizeof(ifr
.ifr_name
))-1] = '\0';
677 if (ioctl(s
->sock_fd
, SIOCGIFINDEX
, &ifr
) < 0) {
678 PyErr_SetFromErrno(PySocket_Error
);
681 addr
= &(s
->sock_addr
.ll
);
682 addr
->sll_family
= AF_PACKET
;
683 addr
->sll_protocol
= htons((short)protoNumber
);
684 addr
->sll_ifindex
= ifr
.ifr_ifindex
;
685 addr
->sll_pkttype
= pkttype
;
686 addr
->sll_hatype
= hatype
;
687 *addr_ret
= (struct sockaddr
*) addr
;
688 *len_ret
= sizeof *addr
;
694 /* More cases here... */
697 PyErr_SetString(PySocket_Error
, "getsockaddrarg: bad family");
704 /* Get the address length according to the socket object's address family.
705 Return 1 if the family is known, 0 otherwise. The length is returned
709 getsockaddrlen(PySocketSockObject
*s
, socklen_t
*len_ret
)
711 switch (s
->sock_family
) {
716 *len_ret
= sizeof (struct sockaddr_un
);
723 *len_ret
= sizeof (struct sockaddr_in
);
727 #if defined(linux) && defined(AF_PACKET)
730 *len_ret
= sizeof (struct sockaddr_ll
);
735 /* More cases here... */
738 PyErr_SetString(PySocket_Error
, "getsockaddrlen: bad family");
745 /* s.accept() method */
748 PySocketSock_accept(PySocketSockObject
*s
, PyObject
*args
)
753 PyObject
*sock
= NULL
;
754 PyObject
*addr
= NULL
;
755 PyObject
*res
= NULL
;
757 if (!PyArg_ParseTuple(args
, ":accept"))
759 if (!getsockaddrlen(s
, &addrlen
))
761 Py_BEGIN_ALLOW_THREADS
762 newfd
= accept(s
->sock_fd
, (struct sockaddr
*) addrbuf
, &addrlen
);
765 if (newfd
== INVALID_SOCKET
)
769 return PySocket_Err();
771 /* Create the new object with unspecified family,
772 to avoid calls to bind() etc. on it. */
773 sock
= (PyObject
*) PySocketSock_New(newfd
,
781 addr
= makesockaddr(s
->sock_fd
, (struct sockaddr
*)addrbuf
,
786 res
= Py_BuildValue("OO", sock
, addr
);
794 static char accept_doc
[] =
795 "accept() -> (socket object, address info)\n\
797 Wait for an incoming connection. Return a new socket representing the\n\
798 connection, and the address of the client. For IP sockets, the address\n\
799 info is a pair (hostaddr, port).";
802 /* s.setblocking(1 | 0) method */
805 PySocketSock_setblocking(PySocketSockObject
*s
, PyObject
*args
)
811 if (!PyArg_ParseTuple(args
, "i:setblocking", &block
))
813 Py_BEGIN_ALLOW_THREADS
816 setsockopt( s
->sock_fd
, SOL_SOCKET
, SO_NONBLOCK
,
817 (void *)(&block
), sizeof( int ) );
822 ioctl(s
->sock_fd
, FIONBIO
, (caddr_t
)&block
, sizeof(block
));
823 #else /* !PYOS_OS2 */
824 delay_flag
= fcntl (s
->sock_fd
, F_GETFL
, 0);
826 delay_flag
&= (~O_NDELAY
);
828 delay_flag
|= O_NDELAY
;
829 fcntl (s
->sock_fd
, F_SETFL
, delay_flag
);
830 #endif /* !PYOS_OS2 */
831 #else /* MS_WINDOWS */
833 ioctlsocket(s
->sock_fd
, FIONBIO
, (u_long
*)&block
);
834 #endif /* MS_WINDOWS */
835 #endif /* __BEOS__ */
842 static char setblocking_doc
[] =
843 "setblocking(flag)\n\
845 Set the socket to blocking (flag is true) or non-blocking (false).\n\
846 This uses the FIONBIO ioctl with the O_NDELAY flag.";
849 /* s.setsockopt() method.
850 With an integer third argument, sets an integer option.
851 With a string third argument, sets an option from a buffer;
852 use optional built-in module 'struct' to encode the string. */
855 PySocketSock_setsockopt(PySocketSockObject
*s
, PyObject
*args
)
864 if (PyArg_ParseTuple(args
, "iii:setsockopt",
865 &level
, &optname
, &flag
)) {
866 buf
= (char *) &flag
;
867 buflen
= sizeof flag
;
871 if (!PyArg_ParseTuple(args
, "iis#:setsockopt",
872 &level
, &optname
, &buf
, &buflen
))
875 res
= setsockopt(s
->sock_fd
, level
, optname
, (void *)buf
, buflen
);
877 return PySocket_Err();
882 static char setsockopt_doc
[] =
883 "setsockopt(level, option, value)\n\
885 Set a socket option. See the Unix manual for level and option.\n\
886 The value argument can either be an integer or a string.";
889 /* s.getsockopt() method.
890 With two arguments, retrieves an integer option.
891 With a third integer argument, retrieves a string buffer of that size;
892 use optional built-in module 'struct' to decode the string. */
895 PySocketSock_getsockopt(PySocketSockObject
*s
, PyObject
*args
)
901 socklen_t buflen
= 0;
904 /* We have incomplete socket support. */
905 PyErr_SetString( PySocket_Error
, "getsockopt not supported" );
909 if (!PyArg_ParseTuple(args
, "ii|i:getsockopt",
910 &level
, &optname
, &buflen
))
915 socklen_t flagsize
= sizeof flag
;
916 res
= getsockopt(s
->sock_fd
, level
, optname
,
917 (void *)&flag
, &flagsize
);
919 return PySocket_Err();
920 return PyInt_FromLong(flag
);
922 if (buflen
<= 0 || buflen
> 1024) {
923 PyErr_SetString(PySocket_Error
,
924 "getsockopt buflen out of range");
927 buf
= PyString_FromStringAndSize((char *)NULL
, buflen
);
930 res
= getsockopt(s
->sock_fd
, level
, optname
,
931 (void *)PyString_AsString(buf
), &buflen
);
934 return PySocket_Err();
936 _PyString_Resize(&buf
, buflen
);
938 #endif /* __BEOS__ */
941 static char getsockopt_doc
[] =
942 "getsockopt(level, option[, buffersize]) -> value\n\
944 Get a socket option. See the Unix manual for level and option.\n\
945 If a nonzero buffersize argument is given, the return value is a\n\
946 string of that length; otherwise it is an integer.";
949 /* s.bind(sockaddr) method */
952 PySocketSock_bind(PySocketSockObject
*s
, PyObject
*args
)
954 struct sockaddr
*addr
;
958 if (!PyArg_ParseTuple(args
, "O:bind", &addro
))
960 if (!getsockaddrarg(s
, addro
, &addr
, &addrlen
))
962 Py_BEGIN_ALLOW_THREADS
963 res
= bind(s
->sock_fd
, addr
, addrlen
);
966 return PySocket_Err();
971 static char bind_doc
[] =
974 Bind the socket to a local address. For IP sockets, the address is a\n\
975 pair (host, port); the host must refer to the local host. For raw packet\n\
976 sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])";
980 Set the file descriptor to -1 so operations tried subsequently
984 PySocketSock_close(PySocketSockObject
*s
, PyObject
*args
)
987 if (!PyArg_ParseTuple(args
, ":close"))
989 if ((fd
= s
->sock_fd
) != -1) {
991 Py_BEGIN_ALLOW_THREADS
992 (void) SOCKETCLOSE(fd
);
999 static char close_doc
[] =
1002 Close the socket. It cannot be used after this call.";
1005 /* s.connect(sockaddr) method */
1008 PySocketSock_connect(PySocketSockObject
*s
, PyObject
*args
)
1010 struct sockaddr
*addr
;
1014 if (!PyArg_ParseTuple(args
, "O:connect", &addro
))
1016 if (!getsockaddrarg(s
, addro
, &addr
, &addrlen
))
1018 Py_BEGIN_ALLOW_THREADS
1019 res
= connect(s
->sock_fd
, addr
, addrlen
);
1020 Py_END_ALLOW_THREADS
1022 return PySocket_Err();
1027 static char connect_doc
[] =
1028 "connect(address)\n\
1030 Connect the socket to a remote address. For IP sockets, the address\n\
1031 is a pair (host, port).";
1034 /* s.connect_ex(sockaddr) method */
1037 PySocketSock_connect_ex(PySocketSockObject
*s
, PyObject
*args
)
1039 struct sockaddr
*addr
;
1043 if (!PyArg_ParseTuple(args
, "O:connect_ex", &addro
))
1045 if (!getsockaddrarg(s
, addro
, &addr
, &addrlen
))
1047 Py_BEGIN_ALLOW_THREADS
1048 res
= connect(s
->sock_fd
, addr
, addrlen
);
1049 Py_END_ALLOW_THREADS
1052 return PyInt_FromLong((long) res
);
1055 static char connect_ex_doc
[] =
1056 "connect_ex(address)\n\
1058 This is like connect(address), but returns an error code (the errno value)\n\
1059 instead of raising an exception when an error occurs.";
1062 /* s.fileno() method */
1065 PySocketSock_fileno(PySocketSockObject
*s
, PyObject
*args
)
1067 if (!PyArg_ParseTuple(args
, ":fileno"))
1069 #if SIZEOF_SOCKET_T <= SIZEOF_LONG
1070 return PyInt_FromLong((long) s
->sock_fd
);
1072 return PyLong_FromLongLong((LONG_LONG
)s
->sock_fd
);
1076 static char fileno_doc
[] =
1077 "fileno() -> integer\n\
1079 Return the integer file descriptor of the socket.";
1083 /* s.dup() method */
1086 PySocketSock_dup(PySocketSockObject
*s
, PyObject
*args
)
1090 if (!PyArg_ParseTuple(args
, ":dup"))
1092 newfd
= dup(s
->sock_fd
);
1094 return PySocket_Err();
1095 sock
= (PyObject
*) PySocketSock_New(newfd
,
1104 static char dup_doc
[] =
1105 "dup() -> socket object\n\
1107 Return a new socket object connected to the same system resource.";
1112 /* s.getsockname() method */
1115 PySocketSock_getsockname(PySocketSockObject
*s
, PyObject
*args
)
1121 if (!PyArg_ParseTuple(args
, ":getsockname"))
1123 if (!getsockaddrlen(s
, &addrlen
))
1125 memset(addrbuf
, 0, addrlen
);
1126 Py_BEGIN_ALLOW_THREADS
1127 res
= getsockname(s
->sock_fd
, (struct sockaddr
*) addrbuf
, &addrlen
);
1128 Py_END_ALLOW_THREADS
1130 return PySocket_Err();
1131 return makesockaddr(s
->sock_fd
, (struct sockaddr
*) addrbuf
, addrlen
);
1134 static char getsockname_doc
[] =
1135 "getsockname() -> address info\n\
1137 Return the address of the local endpoint. For IP sockets, the address\n\
1138 info is a pair (hostaddr, port).";
1141 #ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
1142 /* s.getpeername() method */
1145 PySocketSock_getpeername(PySocketSockObject
*s
, PyObject
*args
)
1151 if (!PyArg_ParseTuple(args
, ":getpeername"))
1153 if (!getsockaddrlen(s
, &addrlen
))
1155 Py_BEGIN_ALLOW_THREADS
1156 res
= getpeername(s
->sock_fd
, (struct sockaddr
*) addrbuf
, &addrlen
);
1157 Py_END_ALLOW_THREADS
1159 return PySocket_Err();
1160 return makesockaddr(s
->sock_fd
, (struct sockaddr
*) addrbuf
, addrlen
);
1163 static char getpeername_doc
[] =
1164 "getpeername() -> address info\n\
1166 Return the address of the remote endpoint. For IP sockets, the address\n\
1167 info is a pair (hostaddr, port).";
1169 #endif /* HAVE_GETPEERNAME */
1172 /* s.listen(n) method */
1175 PySocketSock_listen(PySocketSockObject
*s
, PyObject
*args
)
1179 if (!PyArg_ParseTuple(args
, "i:listen", &backlog
))
1181 Py_BEGIN_ALLOW_THREADS
1184 res
= listen(s
->sock_fd
, backlog
);
1185 Py_END_ALLOW_THREADS
1187 return PySocket_Err();
1192 static char listen_doc
[] =
1195 Enable a server to accept connections. The backlog argument must be at\n\
1196 least 1; it specifies the number of unaccepted connection that the system\n\
1197 will allow before refusing new connections.";
1201 /* s.makefile(mode) method.
1202 Create a new open file object referring to a dupped version of
1203 the socket's file descriptor. (The dup() call is necessary so
1204 that the open file and socket objects may be closed independent
1206 The mode argument specifies 'r' or 'w' passed to fdopen(). */
1209 PySocketSock_makefile(PySocketSockObject
*s
, PyObject
*args
)
1211 extern int fclose(FILE *);
1222 if (!PyArg_ParseTuple(args
, "|si:makefile", &mode
, &bufsize
))
1225 if (((fd
= _open_osfhandle(s
->sock_fd
, _O_BINARY
)) < 0) ||
1226 ((fd
= dup(fd
)) < 0) || ((fp
= fdopen(fd
, mode
)) == NULL
))
1228 if ((fd
= dup(s
->sock_fd
)) < 0 || (fp
= fdopen(fd
, mode
)) == NULL
)
1233 return PySocket_Err();
1235 f
= PyFile_FromFile(fp
, "<socket>", mode
, fclose
);
1237 PyFile_SetBufSize(f
, bufsize
);
1241 static char makefile_doc
[] =
1242 "makefile([mode[, buffersize]]) -> file object\n\
1244 Return a regular file object corresponding to the socket.\n\
1245 The mode and buffersize arguments are as for the built-in open() function.";
1250 /* s.recv(nbytes [,flags]) method */
1253 PySocketSock_recv(PySocketSockObject
*s
, PyObject
*args
)
1255 int len
, n
, flags
= 0;
1257 if (!PyArg_ParseTuple(args
, "i|i:recv", &len
, &flags
))
1259 buf
= PyString_FromStringAndSize((char *) 0, len
);
1262 Py_BEGIN_ALLOW_THREADS
1263 n
= recv(s
->sock_fd
, PyString_AsString(buf
), len
, flags
);
1264 Py_END_ALLOW_THREADS
1267 return PySocket_Err();
1269 if (n
!= len
&& _PyString_Resize(&buf
, n
) < 0)
1274 static char recv_doc
[] =
1275 "recv(buffersize[, flags]) -> data\n\
1277 Receive up to buffersize bytes from the socket. For the optional flags\n\
1278 argument, see the Unix manual. When no data is available, block until\n\
1279 at least one byte is available or until the remote end is closed. When\n\
1280 the remote end is closed and all data is read, return the empty string.";
1283 /* s.recvfrom(nbytes [,flags]) method */
1286 PySocketSock_recvfrom(PySocketSockObject
*s
, PyObject
*args
)
1289 PyObject
*buf
= NULL
;
1290 PyObject
*addr
= NULL
;
1291 PyObject
*ret
= NULL
;
1293 int len
, n
, flags
= 0;
1295 if (!PyArg_ParseTuple(args
, "i|i:recvfrom", &len
, &flags
))
1297 if (!getsockaddrlen(s
, &addrlen
))
1299 buf
= PyString_FromStringAndSize((char *) 0, len
);
1302 Py_BEGIN_ALLOW_THREADS
1303 n
= recvfrom(s
->sock_fd
, PyString_AsString(buf
), len
, flags
,
1305 #if defined(PYOS_OS2)
1306 (struct sockaddr
*)addrbuf
, &addrlen
1308 (void *)addrbuf
, &addrlen
1311 (struct sockaddr
*)addrbuf
, &addrlen
1314 Py_END_ALLOW_THREADS
1317 return PySocket_Err();
1319 if (n
!= len
&& _PyString_Resize(&buf
, n
) < 0)
1322 if (!(addr
= makesockaddr(s
->sock_fd
, (struct sockaddr
*)addrbuf
, addrlen
)))
1325 ret
= Py_BuildValue("OO", buf
, addr
);
1332 static char recvfrom_doc
[] =
1333 "recvfrom(buffersize[, flags]) -> (data, address info)\n\
1335 Like recv(buffersize, flags) but also return the sender's address info.";
1338 /* s.send(data [,flags]) method */
1341 PySocketSock_send(PySocketSockObject
*s
, PyObject
*args
)
1344 int len
, n
, flags
= 0;
1345 if (!PyArg_ParseTuple(args
, "s#|i:send", &buf
, &len
, &flags
))
1347 Py_BEGIN_ALLOW_THREADS
1348 n
= send(s
->sock_fd
, buf
, len
, flags
);
1349 Py_END_ALLOW_THREADS
1351 return PySocket_Err();
1352 return PyInt_FromLong((long)n
);
1355 static char send_doc
[] =
1356 "send(data[, flags])\n\
1358 Send a data string to the socket. For the optional flags\n\
1359 argument, see the Unix manual.";
1362 /* s.sendto(data, [flags,] sockaddr) method */
1365 PySocketSock_sendto(PySocketSockObject
*s
, PyObject
*args
)
1369 struct sockaddr
*addr
;
1370 int addrlen
, len
, n
, flags
;
1372 if (!PyArg_ParseTuple(args
, "s#O:sendto", &buf
, &len
, &addro
)) {
1374 if (!PyArg_ParseTuple(args
, "s#iO:sendto",
1375 &buf
, &len
, &flags
, &addro
))
1378 if (!getsockaddrarg(s
, addro
, &addr
, &addrlen
))
1380 Py_BEGIN_ALLOW_THREADS
1381 n
= sendto(s
->sock_fd
, buf
, len
, flags
, addr
, addrlen
);
1382 Py_END_ALLOW_THREADS
1384 return PySocket_Err();
1385 return PyInt_FromLong((long)n
);
1388 static char sendto_doc
[] =
1389 "sendto(data[, flags], address)\n\
1391 Like send(data, flags) but allows specifying the destination address.\n\
1392 For IP sockets, the address is a pair (hostaddr, port).";
1395 /* s.shutdown(how) method */
1398 PySocketSock_shutdown(PySocketSockObject
*s
, PyObject
*args
)
1402 if (!PyArg_ParseTuple(args
, "i:shutdown", &how
))
1404 Py_BEGIN_ALLOW_THREADS
1405 res
= shutdown(s
->sock_fd
, how
);
1406 Py_END_ALLOW_THREADS
1408 return PySocket_Err();
1413 static char shutdown_doc
[] =
1416 Shut down the reading side of the socket (flag == 0), the writing side\n\
1417 of the socket (flag == 1), or both ends (flag == 2).";
1420 /* List of methods for socket objects */
1422 static PyMethodDef PySocketSock_methods
[] = {
1423 {"accept", (PyCFunction
)PySocketSock_accept
, METH_VARARGS
,
1425 {"bind", (PyCFunction
)PySocketSock_bind
, METH_VARARGS
,
1427 {"close", (PyCFunction
)PySocketSock_close
, METH_VARARGS
,
1429 {"connect", (PyCFunction
)PySocketSock_connect
, METH_VARARGS
,
1431 {"connect_ex", (PyCFunction
)PySocketSock_connect_ex
, METH_VARARGS
,
1434 {"dup", (PyCFunction
)PySocketSock_dup
, METH_VARARGS
,
1437 {"fileno", (PyCFunction
)PySocketSock_fileno
, METH_VARARGS
,
1439 #ifdef HAVE_GETPEERNAME
1440 {"getpeername", (PyCFunction
)PySocketSock_getpeername
, METH_VARARGS
,
1443 {"getsockname", (PyCFunction
)PySocketSock_getsockname
, METH_VARARGS
,
1445 {"getsockopt", (PyCFunction
)PySocketSock_getsockopt
, METH_VARARGS
,
1447 {"listen", (PyCFunction
)PySocketSock_listen
, METH_VARARGS
,
1450 {"makefile", (PyCFunction
)PySocketSock_makefile
, METH_VARARGS
,
1453 {"recv", (PyCFunction
)PySocketSock_recv
, METH_VARARGS
,
1455 {"recvfrom", (PyCFunction
)PySocketSock_recvfrom
, METH_VARARGS
,
1457 {"send", (PyCFunction
)PySocketSock_send
, METH_VARARGS
,
1459 {"sendto", (PyCFunction
)PySocketSock_sendto
, METH_VARARGS
,
1461 {"setblocking", (PyCFunction
)PySocketSock_setblocking
, METH_VARARGS
,
1463 {"setsockopt", (PyCFunction
)PySocketSock_setsockopt
, METH_VARARGS
,
1465 {"shutdown", (PyCFunction
)PySocketSock_shutdown
, METH_VARARGS
,
1467 {NULL
, NULL
} /* sentinel */
1471 /* Deallocate a socket object in response to the last Py_DECREF().
1472 First close the file description. */
1475 PySocketSock_dealloc(PySocketSockObject
*s
)
1477 if (s
->sock_fd
!= -1)
1478 (void) SOCKETCLOSE(s
->sock_fd
);
1483 /* Return a socket object's named attribute. */
1486 PySocketSock_getattr(PySocketSockObject
*s
, char *name
)
1488 return Py_FindMethod(PySocketSock_methods
, (PyObject
*) s
, name
);
1493 PySocketSock_repr(PySocketSockObject
*s
)
1496 #if SIZEOF_SOCKET_T > SIZEOF_LONG
1497 if (s
->sock_fd
> LONG_MAX
) {
1498 /* this can occur on Win64, and actually there is a special
1499 ugly printf formatter for decimal pointer length integer
1500 printing, only bother if necessary*/
1501 PyErr_SetString(PyExc_OverflowError
,
1502 "no printf formatter to display the socket descriptor in decimal");
1507 "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
1508 (long)s
->sock_fd
, s
->sock_family
, s
->sock_type
, s
->sock_proto
);
1509 return PyString_FromString(buf
);
1513 /* Type object for socket objects. */
1515 static PyTypeObject PySocketSock_Type
= {
1516 PyObject_HEAD_INIT(0) /* Must fill in type value later */
1519 sizeof(PySocketSockObject
),
1521 (destructor
)PySocketSock_dealloc
, /*tp_dealloc*/
1523 (getattrfunc
)PySocketSock_getattr
, /*tp_getattr*/
1526 (reprfunc
)PySocketSock_repr
, /*tp_repr*/
1528 0, /*tp_as_sequence*/
1529 0, /*tp_as_mapping*/
1533 /* Python interface to gethostname(). */
1537 PySocket_gethostname(PyObject
*self
, PyObject
*args
)
1541 if (!PyArg_ParseTuple(args
, ":gethostname"))
1543 Py_BEGIN_ALLOW_THREADS
1544 res
= gethostname(buf
, (int) sizeof buf
- 1);
1545 Py_END_ALLOW_THREADS
1547 return PySocket_Err();
1548 buf
[sizeof buf
- 1] = '\0';
1549 return PyString_FromString(buf
);
1552 static char gethostname_doc
[] =
1553 "gethostname() -> string\n\
1555 Return the current host name.";
1558 /* Python interface to gethostbyname(name). */
1562 PySocket_gethostbyname(PyObject
*self
, PyObject
*args
)
1565 struct sockaddr_in addrbuf
;
1566 if (!PyArg_ParseTuple(args
, "s:gethostbyname", &name
))
1568 if (setipaddr(name
, &addrbuf
) < 0)
1570 return makeipaddr(&addrbuf
);
1573 static char gethostbyname_doc
[] =
1574 "gethostbyname(host) -> address\n\
1576 Return the IP address (a string of the form '255.255.255.255') for a host.";
1579 /* Convenience function common to gethostbyname_ex and gethostbyaddr */
1582 gethost_common(struct hostent
*h
, struct sockaddr_in
*addr
)
1585 PyObject
*rtn_tuple
= (PyObject
*)NULL
;
1586 PyObject
*name_list
= (PyObject
*)NULL
;
1587 PyObject
*addr_list
= (PyObject
*)NULL
;
1590 #ifdef HAVE_HSTRERROR
1591 /* Let's get real error message to return */
1593 PyErr_SetString(PySocket_Error
, (char *)hstrerror(h_errno
));
1595 PyErr_SetString(PySocket_Error
, "host not found");
1599 if ((name_list
= PyList_New(0)) == NULL
)
1601 if ((addr_list
= PyList_New(0)) == NULL
)
1603 for (pch
= h
->h_aliases
; *pch
!= NULL
; pch
++) {
1605 tmp
= PyString_FromString(*pch
);
1608 status
= PyList_Append(name_list
, tmp
);
1613 for (pch
= h
->h_addr_list
; *pch
!= NULL
; pch
++) {
1615 memcpy((char *) &addr
->sin_addr
, *pch
, h
->h_length
);
1616 tmp
= makeipaddr(addr
);
1619 status
= PyList_Append(addr_list
, tmp
);
1624 rtn_tuple
= Py_BuildValue("sOO", h
->h_name
, name_list
, addr_list
);
1626 Py_XDECREF(name_list
);
1627 Py_XDECREF(addr_list
);
1632 /* Python interface to gethostbyname_ex(name). */
1636 PySocket_gethostbyname_ex(PyObject
*self
, PyObject
*args
)
1640 struct sockaddr_in addr
;
1642 #ifdef HAVE_GETHOSTBYNAME_R
1643 struct hostent hp_allocated
;
1644 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
1645 struct hostent_data data
;
1648 int buf_len
= (sizeof buf
) - 1;
1651 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
1654 #endif /* HAVE_GETHOSTBYNAME_R */
1655 if (!PyArg_ParseTuple(args
, "s:gethostbyname_ex", &name
))
1657 if (setipaddr(name
, &addr
) < 0)
1659 Py_BEGIN_ALLOW_THREADS
1660 #ifdef HAVE_GETHOSTBYNAME_R
1661 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
1662 result
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
, &h
, &errnop
);
1663 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
1664 h
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
, &errnop
);
1665 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
1666 memset((void *) &data
, '\0', sizeof(data
));
1667 result
= gethostbyname_r(name
, &hp_allocated
, &data
);
1668 h
= (result
!= 0) ? NULL
: &hp_allocated
;
1670 #else /* not HAVE_GETHOSTBYNAME_R */
1671 #ifdef USE_GETHOSTBYNAME_LOCK
1672 PyThread_acquire_lock(gethostbyname_lock
, 1);
1674 h
= gethostbyname(name
);
1675 #endif /* HAVE_GETHOSTBYNAME_R */
1676 Py_END_ALLOW_THREADS
1677 ret
= gethost_common(h
, &addr
);
1678 #ifdef USE_GETHOSTBYNAME_LOCK
1679 PyThread_release_lock(gethostbyname_lock
);
1684 static char ghbn_ex_doc
[] =
1685 "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
1687 Return the true host name, a list of aliases, and a list of IP addresses,\n\
1688 for a host. The host argument is a string giving a host name or IP number.";
1691 /* Python interface to gethostbyaddr(IP). */
1695 PySocket_gethostbyaddr(PyObject
*self
, PyObject
*args
)
1697 struct sockaddr_in addr
;
1701 #ifdef HAVE_GETHOSTBYNAME_R
1702 struct hostent hp_allocated
;
1703 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
1704 struct hostent_data data
;
1707 int buf_len
= (sizeof buf
) - 1;
1710 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
1713 #endif /* HAVE_GETHOSTBYNAME_R */
1715 if (!PyArg_ParseTuple(args
, "s:gethostbyaddr", &ip_num
))
1717 if (setipaddr(ip_num
, &addr
) < 0)
1719 Py_BEGIN_ALLOW_THREADS
1720 #ifdef HAVE_GETHOSTBYNAME_R
1721 #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
1722 result
= gethostbyaddr_r((char *)&addr
.sin_addr
,
1723 sizeof(addr
.sin_addr
),
1724 AF_INET
, &hp_allocated
, buf
, buf_len
,
1726 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
1727 h
= gethostbyaddr_r((char *)&addr
.sin_addr
,
1728 sizeof(addr
.sin_addr
),
1730 &hp_allocated
, buf
, buf_len
, &errnop
);
1731 #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
1732 memset((void *) &data
, '\0', sizeof(data
));
1733 result
= gethostbyaddr_r((char *)&addr
.sin_addr
,
1734 sizeof(addr
.sin_addr
),
1735 AF_INET
, &hp_allocated
, &data
);
1736 h
= (result
!= 0) ? NULL
: &hp_allocated
;
1738 #else /* not HAVE_GETHOSTBYNAME_R */
1739 #ifdef USE_GETHOSTBYNAME_LOCK
1740 PyThread_acquire_lock(gethostbyname_lock
, 1);
1742 h
= gethostbyaddr((char *)&addr
.sin_addr
,
1743 sizeof(addr
.sin_addr
),
1745 #endif /* HAVE_GETHOSTBYNAME_R */
1746 Py_END_ALLOW_THREADS
1747 ret
= gethost_common(h
, &addr
);
1748 #ifdef USE_GETHOSTBYNAME_LOCK
1749 PyThread_release_lock(gethostbyname_lock
);
1754 static char gethostbyaddr_doc
[] =
1755 "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
1757 Return the true host name, a list of aliases, and a list of IP addresses,\n\
1758 for a host. The host argument is a string giving a host name or IP number.";
1761 /* Python interface to getservbyname(name).
1762 This only returns the port number, since the other info is already
1763 known or not useful (like the list of aliases). */
1767 PySocket_getservbyname(PyObject
*self
, PyObject
*args
)
1771 if (!PyArg_ParseTuple(args
, "ss:getservbyname", &name
, &proto
))
1773 Py_BEGIN_ALLOW_THREADS
1774 sp
= getservbyname(name
, proto
);
1775 Py_END_ALLOW_THREADS
1777 PyErr_SetString(PySocket_Error
, "service/proto not found");
1780 return PyInt_FromLong((long) ntohs(sp
->s_port
));
1783 static char getservbyname_doc
[] =
1784 "getservbyname(servicename, protocolname) -> integer\n\
1786 Return a port number from a service name and protocol name.\n\
1787 The protocol name should be 'tcp' or 'udp'.";
1790 /* Python interface to getprotobyname(name).
1791 This only returns the protocol number, since the other info is
1792 already known or not useful (like the list of aliases). */
1796 PySocket_getprotobyname(PyObject
*self
, PyObject
*args
)
1799 struct protoent
*sp
;
1801 /* Not available in BeOS yet. - [cjh] */
1802 PyErr_SetString( PySocket_Error
, "getprotobyname not supported" );
1805 if (!PyArg_ParseTuple(args
, "s:getprotobyname", &name
))
1807 Py_BEGIN_ALLOW_THREADS
1808 sp
= getprotobyname(name
);
1809 Py_END_ALLOW_THREADS
1811 PyErr_SetString(PySocket_Error
, "protocol not found");
1814 return PyInt_FromLong((long) sp
->p_proto
);
1818 static char getprotobyname_doc
[] =
1819 "getprotobyname(name) -> integer\n\
1821 Return the protocol number for the named protocol. (Rarely used.)";
1824 /* Python interface to socket(family, type, proto).
1825 The third (protocol) argument is optional.
1826 Return a new socket object. */
1830 PySocket_socket(PyObject
*self
, PyObject
*args
)
1832 PySocketSockObject
*s
;
1834 int family
, type
, proto
= 0;
1835 if (!PyArg_ParseTuple(args
, "ii|i:socket", &family
, &type
, &proto
))
1837 Py_BEGIN_ALLOW_THREADS
1838 fd
= socket(family
, type
, proto
);
1839 Py_END_ALLOW_THREADS
1841 if (fd
== INVALID_SOCKET
)
1845 return PySocket_Err();
1846 s
= PySocketSock_New(fd
, family
, type
, proto
);
1847 /* If the object can't be created, don't forget to close the
1848 file descriptor again! */
1850 (void) SOCKETCLOSE(fd
);
1851 /* From now on, ignore SIGPIPE and let the error checking
1854 (void) signal(SIGPIPE
, SIG_IGN
);
1856 return (PyObject
*) s
;
1859 static char socket_doc
[] =
1860 "socket(family, type[, proto]) -> socket object\n\
1862 Open a socket of the given type. The family argument specifies the\n\
1863 address family; it is normally AF_INET, sometimes AF_UNIX.\n\
1864 The type argument specifies whether this is a stream (SOCK_STREAM)\n\
1865 or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0,\n\
1866 specifying the default protocol.";
1870 /* Create a socket object from a numeric file description.
1871 Useful e.g. if stdin is a socket.
1872 Additional arguments as for socket(). */
1876 PySocket_fromfd(PyObject
*self
, PyObject
*args
)
1878 PySocketSockObject
*s
;
1880 int family
, type
, proto
= 0;
1881 if (!PyArg_ParseTuple(args
, "iii|i:fromfd",
1882 &fd
, &family
, &type
, &proto
))
1884 /* Dup the fd so it and the socket can be closed independently */
1887 return PySocket_Err();
1888 s
= PySocketSock_New(fd
, family
, type
, proto
);
1889 /* From now on, ignore SIGPIPE and let the error checking
1892 (void) signal(SIGPIPE
, SIG_IGN
);
1894 return (PyObject
*) s
;
1897 static char fromfd_doc
[] =
1898 "fromfd(fd, family, type[, proto]) -> socket object\n\
1900 Create a socket object from the given file descriptor.\n\
1901 The remaining arguments are the same as for socket().";
1907 PySocket_ntohs(PyObject
*self
, PyObject
*args
)
1911 if (!PyArg_ParseTuple(args
, "i:ntohs", &x1
)) {
1914 x2
= (int)ntohs((short)x1
);
1915 return PyInt_FromLong(x2
);
1918 static char ntohs_doc
[] =
1919 "ntohs(integer) -> integer\n\
1921 Convert a 16-bit integer from network to host byte order.";
1925 PySocket_ntohl(PyObject
*self
, PyObject
*args
)
1929 if (!PyArg_ParseTuple(args
, "i:ntohl", &x1
)) {
1933 return PyInt_FromLong(x2
);
1936 static char ntohl_doc
[] =
1937 "ntohl(integer) -> integer\n\
1939 Convert a 32-bit integer from network to host byte order.";
1943 PySocket_htons(PyObject
*self
, PyObject
*args
)
1947 if (!PyArg_ParseTuple(args
, "i:htons", &x1
)) {
1950 x2
= (int)htons((short)x1
);
1951 return PyInt_FromLong(x2
);
1954 static char htons_doc
[] =
1955 "htons(integer) -> integer\n\
1957 Convert a 16-bit integer from host to network byte order.";
1961 PySocket_htonl(PyObject
*self
, PyObject
*args
)
1965 if (!PyArg_ParseTuple(args
, "i:htonl", &x1
)) {
1969 return PyInt_FromLong(x2
);
1972 static char htonl_doc
[] =
1973 "htonl(integer) -> integer\n\
1975 Convert a 32-bit integer from host to network byte order.";
1978 * socket.inet_aton() and socket.inet_ntoa() functions
1980 * written 20 Aug 1999 by Ben Gertzfield <che@debian.org> <- blame him!
1984 static char inet_aton_doc
[] =
1985 "inet_aton(string) -> packed 32-bit IP representation\n\
1987 Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
1988 binary format used in low-level network functions.";
1991 PySocket_inet_aton(PyObject
*self
, PyObject
*args
)
1994 #define INADDR_NONE (-1)
1997 /* Have to use inet_addr() instead */
2001 if (!PyArg_ParseTuple(args
, "s:inet_aton", &ip_addr
)) {
2005 packed_addr
= (long)inet_addr(ip_addr
).s_addr
;
2007 packed_addr
= inet_addr(ip_addr
);
2010 if (packed_addr
== INADDR_NONE
) { /* invalid address */
2011 PyErr_SetString(PySocket_Error
,
2012 "illegal IP address string passed to inet_aton");
2016 return PyString_FromStringAndSize((char *) &packed_addr
,
2017 sizeof(packed_addr
));
2020 static char inet_ntoa_doc
[] =
2021 "inet_ntoa(packed_ip) -> ip_address_string\n\
2023 Convert an IP address from 32-bit packed binary format to string format";
2026 PySocket_inet_ntoa(PyObject
*self
, PyObject
*args
)
2030 struct in_addr packed_addr
;
2032 if (!PyArg_ParseTuple(args
, "s#:inet_ntoa", &packed_str
, &addr_len
)) {
2036 if (addr_len
!= sizeof(packed_addr
)) {
2037 PyErr_SetString(PySocket_Error
,
2038 "packed IP wrong length for inet_ntoa");
2042 memcpy(&packed_addr
, packed_str
, addr_len
);
2044 return PyString_FromString(inet_ntoa(packed_addr
));
2050 /* This is a C function to be called for new object initialization */
2052 newSSLObject(PySocketSockObject
*Sock
, char *key_file
, char *cert_file
)
2056 self
= PyObject_New(SSLObject
, &SSL_Type
); /* Create new object */
2058 PyErr_SetObject(SSLErrorObject
,
2059 PyString_FromString("newSSLObject error"));
2062 memset(self
->server
, '\0', sizeof(char) * 256);
2063 memset(self
->issuer
, '\0', sizeof(char) * 256);
2065 self
->x_attr
= PyDict_New();
2066 self
->ctx
= SSL_CTX_new(SSLv23_method()); /* Set up context */
2067 if (self
->ctx
== NULL
) {
2068 PyErr_SetObject(SSLErrorObject
,
2069 PyString_FromString("SSL_CTX_new error"));
2074 if ( (key_file
&& !cert_file
) || (!key_file
&& cert_file
) )
2076 PyErr_SetObject(SSLErrorObject
,
2077 PyString_FromString(
2078 "Both the key & certificate files must be specified"));
2083 if (key_file
&& cert_file
)
2085 if (SSL_CTX_use_PrivateKey_file(self
->ctx
, key_file
,
2086 SSL_FILETYPE_PEM
) < 1)
2088 PyErr_SetObject(SSLErrorObject
,
2089 PyString_FromString(
2090 "SSL_CTX_use_PrivateKey_file error"));
2095 if (SSL_CTX_use_certificate_chain_file(self
->ctx
,
2098 PyErr_SetObject(SSLErrorObject
,
2099 PyString_FromString(
2100 "SSL_CTX_use_certificate_chain_file error"));
2106 SSL_CTX_set_verify(self
->ctx
,
2107 SSL_VERIFY_NONE
, NULL
); /* set verify lvl */
2108 self
->ssl
= SSL_new(self
->ctx
); /* New ssl struct */
2109 SSL_set_fd(self
->ssl
, Sock
->sock_fd
); /* Set the socket for SSL */
2110 SSL_set_connect_state(self
->ssl
);
2112 if ((SSL_connect(self
->ssl
)) == -1) {
2113 /* Actually negotiate SSL connection */
2114 PyErr_SetObject(SSLErrorObject
,
2115 PyString_FromString("SSL_connect error"));
2119 self
->ssl
->debug
= 1;
2121 if ((self
->server_cert
= SSL_get_peer_certificate(self
->ssl
))) {
2122 X509_NAME_oneline(X509_get_subject_name(self
->server_cert
),
2124 X509_NAME_oneline(X509_get_issuer_name(self
->server_cert
),
2127 self
->x_attr
= NULL
;
2128 self
->Socket
= Sock
;
2129 Py_INCREF(self
->Socket
);
2133 /* This is the Python function called for new object initialization */
2135 PySocket_ssl(PyObject
*self
, PyObject
*args
)
2138 PySocketSockObject
*Sock
;
2142 if (!PyArg_ParseTuple(args
, "O!zz:ssl",
2143 &PySocketSock_Type
, (PyObject
*)&Sock
,
2144 &key_file
, &cert_file
) )
2147 rv
= newSSLObject(Sock
, key_file
, cert_file
);
2150 return (PyObject
*)rv
;
2153 static char ssl_doc
[] =
2154 "ssl(socket, keyfile, certfile) -> sslobject";
2157 SSL_server(SSLObject
*self
, PyObject
*args
)
2159 return PyString_FromString(self
->server
);
2163 SSL_issuer(SSLObject
*self
, PyObject
*args
)
2165 return PyString_FromString(self
->issuer
);
2169 /* SSL object methods */
2171 static PyMethodDef SSLMethods
[] = {
2172 { "write", (PyCFunction
)SSL_SSLwrite
, 1 },
2173 { "read", (PyCFunction
)SSL_SSLread
, 1 },
2174 { "server", (PyCFunction
)SSL_server
, 1 },
2175 { "issuer", (PyCFunction
)SSL_issuer
, 1 },
2179 static void SSL_dealloc(SSLObject
*self
)
2181 if (self
->server_cert
) /* Possible not to have one? */
2182 X509_free (self
->server_cert
);
2183 SSL_CTX_free(self
->ctx
);
2184 SSL_free(self
->ssl
);
2185 Py_XDECREF(self
->x_attr
);
2186 Py_XDECREF(self
->Socket
);
2190 static PyObject
*SSL_getattr(SSLObject
*self
, char *name
)
2192 return Py_FindMethod(SSLMethods
, (PyObject
*)self
, name
);
2195 staticforward PyTypeObject SSL_Type
= {
2196 PyObject_HEAD_INIT(NULL
)
2199 sizeof(SSLObject
), /*tp_basicsize*/
2202 (destructor
)SSL_dealloc
, /*tp_dealloc*/
2204 (getattrfunc
)SSL_getattr
, /*tp_getattr*/
2209 0, /*tp_as_sequence*/
2210 0, /*tp_as_mapping*/
2216 static PyObject
*SSL_SSLwrite(SSLObject
*self
, PyObject
*args
)
2221 if (!PyArg_ParseTuple(args
, "s#:write", &data
, &len
))
2224 len
= SSL_write(self
->ssl
, data
, len
);
2225 return PyInt_FromLong((long)len
);
2228 static PyObject
*SSL_SSLread(SSLObject
*self
, PyObject
*args
)
2235 PyArg_ParseTuple(args
, "|i:read", &len
);
2237 if (!(buf
= PyString_FromStringAndSize((char *) 0, len
)))
2238 return NULL
; /* Error object should already be set */
2240 count
= SSL_read(self
->ssl
, PyString_AsString(buf
), len
);
2241 res
= SSL_get_error(self
->ssl
, count
);
2244 case SSL_ERROR_NONE
:
2247 case SSL_ERROR_ZERO_RETURN
: /* normal EOF */
2251 return PyErr_SetFromErrno(SSLErrorObject
);
2258 return PyErr_SetFromErrno(SSLErrorObject
);
2261 if (count
!= len
&& _PyString_Resize(&buf
, count
) < 0)
2266 #endif /* USE_SSL */
2269 /* List of functions exported by this module. */
2271 static PyMethodDef PySocket_methods
[] = {
2272 {"gethostbyname", PySocket_gethostbyname
,
2273 METH_VARARGS
, gethostbyname_doc
},
2274 {"gethostbyname_ex", PySocket_gethostbyname_ex
,
2275 METH_VARARGS
, ghbn_ex_doc
},
2276 {"gethostbyaddr", PySocket_gethostbyaddr
,
2277 METH_VARARGS
, gethostbyaddr_doc
},
2278 {"gethostname", PySocket_gethostname
,
2279 METH_VARARGS
, gethostname_doc
},
2280 {"getservbyname", PySocket_getservbyname
,
2281 METH_VARARGS
, getservbyname_doc
},
2282 {"getprotobyname", PySocket_getprotobyname
,
2283 METH_VARARGS
,getprotobyname_doc
},
2284 {"socket", PySocket_socket
,
2285 METH_VARARGS
, socket_doc
},
2287 {"fromfd", PySocket_fromfd
,
2288 METH_VARARGS
, fromfd_doc
},
2290 {"ntohs", PySocket_ntohs
,
2291 METH_VARARGS
, ntohs_doc
},
2292 {"ntohl", PySocket_ntohl
,
2293 METH_VARARGS
, ntohl_doc
},
2294 {"htons", PySocket_htons
,
2295 METH_VARARGS
, htons_doc
},
2296 {"htonl", PySocket_htonl
,
2297 METH_VARARGS
, htonl_doc
},
2298 {"inet_aton", PySocket_inet_aton
,
2299 METH_VARARGS
, inet_aton_doc
},
2300 {"inet_ntoa", PySocket_inet_ntoa
,
2301 METH_VARARGS
, inet_ntoa_doc
},
2303 {"ssl", PySocket_ssl
,
2304 METH_VARARGS
, ssl_doc
},
2305 #endif /* USE_SSL */
2306 {NULL
, NULL
} /* Sentinel */
2310 /* Convenience routine to export an integer value.
2312 * Errors are silently ignored, for better or for worse...
2315 insint(PyObject
*d
, char *name
, int value
)
2317 PyObject
*v
= PyInt_FromLong((long) value
);
2318 if (!v
|| PyDict_SetItemString(d
, name
, v
))
2327 /* Additional initialization and cleanup for NT/Windows */
2341 ret
= WSAStartup(0x0101, &WSAData
);
2343 case 0: /* no error */
2346 case WSASYSNOTREADY
:
2347 PyErr_SetString(PyExc_ImportError
,
2348 "WSAStartup failed: network not ready");
2350 case WSAVERNOTSUPPORTED
:
2352 PyErr_SetString(PyExc_ImportError
,
2353 "WSAStartup failed: requested version not supported");
2356 sprintf(buf
, "WSAStartup failed: error code %d", ret
);
2357 PyErr_SetString(PyExc_ImportError
, buf
);
2363 #endif /* MS_WINDOWS */
2365 #if defined(PYOS_OS2)
2367 /* Additional initialization and cleanup for OS/2 */
2372 /* No cleanup is necessary for OS/2 Sockets */
2379 int rc
= sock_init();
2383 return 1; /* Indicate Success */
2386 sprintf(reason
, "OS/2 TCP/IP Error# %d", sock_errno());
2387 PyErr_SetString(PyExc_ImportError
, reason
);
2389 return 0; /* Indicate Failure */
2392 #endif /* PYOS_OS2 */
2394 /* Initialize this module.
2395 * This is called when the first 'import socket' is done,
2396 * via a table in config.c, if config.c is compiled with USE_SOCKET
2399 * For MS_WINDOWS (which means any Windows variant), this module
2400 * is actually called "_socket", and there's a wrapper "socket.py"
2401 * which implements some missing functionality (such as makefile(),
2402 * dup() and fromfd()). The import of "_socket" may fail with an
2403 * ImportError exception if initialization of WINSOCK fails. When
2404 * WINSOCK is initialized succesfully, a call to WSACleanup() is
2405 * scheduled to be made at exit time.
2407 * For OS/2, this module is also called "_socket" and uses a wrapper
2408 * "socket.py" which implements that functionality that is missing
2409 * when PC operating systems don't put socket descriptors in the
2410 * operating system's filesystem layer.
2413 static char module_doc
[] =
2414 "Implementation module for socket operations. See the socket module\n\
2415 for documentation.";
2417 static char sockettype_doc
[] =
2418 "A socket represents one endpoint of a network connection.\n\
2422 accept() -- accept a connection, returning new socket and client address\n\
2423 bind() -- bind the socket to a local address\n\
2424 close() -- close the socket\n\
2425 connect() -- connect the socket to a remote address\n\
2426 connect_ex() -- connect, return an error code instead of an exception \n\
2427 dup() -- return a new socket object identical to the current one (*)\n\
2428 fileno() -- return underlying file descriptor\n\
2429 getpeername() -- return remote address (*)\n\
2430 getsockname() -- return local address\n\
2431 getsockopt() -- get socket options\n\
2432 listen() -- start listening for incoming connections\n\
2433 makefile() -- return a file object corresponding tot the socket (*)\n\
2434 recv() -- receive data\n\
2435 recvfrom() -- receive data and sender's address\n\
2436 send() -- send data\n\
2437 sendto() -- send data to a given address\n\
2438 setblocking() -- set or clear the blocking I/O flag\n\
2439 setsockopt() -- set socket options\n\
2440 shutdown() -- shut down traffic in one or both directions\n\
2442 (*) not available on all platforms!)";
2452 #if defined(__TOS_OS2__)
2455 #endif /* __TOS_OS2__ */
2456 #endif /* MS_WINDOWS */
2458 SSL_Type
.ob_type
= &PyType_Type
;
2460 m
= Py_InitModule3("_socket", PySocket_methods
, module_doc
);
2461 d
= PyModule_GetDict(m
);
2462 PySocket_Error
= PyErr_NewException("socket.error", NULL
, NULL
);
2463 if (PySocket_Error
== NULL
)
2466 SSL_load_error_strings();
2467 SSLeay_add_ssl_algorithms();
2468 SSLErrorObject
= PyErr_NewException("socket.sslerror", NULL
, NULL
);
2469 if (SSLErrorObject
== NULL
)
2471 PyDict_SetItemString(d
, "sslerror", SSLErrorObject
);
2472 Py_INCREF(&SSL_Type
);
2473 if (PyDict_SetItemString(d
, "SSLType",
2474 (PyObject
*)&SSL_Type
) != 0)
2476 #endif /* USE_SSL */
2477 PyDict_SetItemString(d
, "error", PySocket_Error
);
2478 PySocketSock_Type
.ob_type
= &PyType_Type
;
2479 PySocketSock_Type
.tp_doc
= sockettype_doc
;
2480 Py_INCREF(&PySocketSock_Type
);
2481 if (PyDict_SetItemString(d
, "SocketType",
2482 (PyObject
*)&PySocketSock_Type
) != 0)
2485 /* Address families (we only support AF_INET and AF_UNIX) */
2487 insint(d
, "AF_UNSPEC", AF_UNSPEC
);
2489 insint(d
, "AF_INET", AF_INET
);
2491 insint(d
, "AF_UNIX", AF_UNIX
);
2492 #endif /* AF_UNIX */
2494 insint(d
, "AF_AX25", AF_AX25
); /* Amateur Radio AX.25 */
2497 insint(d
, "AF_IPX", AF_IPX
); /* Novell IPX */
2500 insint(d
, "AF_APPLETALK", AF_APPLETALK
); /* Appletalk DDP */
2503 insint(d
, "AF_NETROM", AF_NETROM
); /* Amateur radio NetROM */
2506 insint(d
, "AF_BRIDGE", AF_BRIDGE
); /* Multiprotocol bridge */
2509 insint(d
, "AF_AAL5", AF_AAL5
); /* Reserved for Werner's ATM */
2512 insint(d
, "AF_X25", AF_X25
); /* Reserved for X.25 project */
2515 insint(d
, "AF_INET6", AF_INET6
); /* IP version 6 */
2518 insint(d
, "AF_ROSE", AF_ROSE
); /* Amateur Radio X.25 PLP */
2520 #if defined(linux) && defined(AF_PACKET)
2521 insint(d
, "AF_PACKET", AF_PACKET
);
2522 insint(d
, "PF_PACKET", PF_PACKET
);
2523 insint(d
, "PACKET_HOST", PACKET_HOST
);
2524 insint(d
, "PACKET_BROADCAST", PACKET_BROADCAST
);
2525 insint(d
, "PACKET_MULTICAST", PACKET_MULTICAST
);
2526 insint(d
, "PACKET_OTHERHOST", PACKET_OTHERHOST
);
2527 insint(d
, "PACKET_OUTGOING", PACKET_OUTGOING
);
2528 insint(d
, "PACKET_LOOPBACK", PACKET_LOOPBACK
);
2529 insint(d
, "PACKET_FASTROUTE", PACKET_FASTROUTE
);
2533 insint(d
, "SOCK_STREAM", SOCK_STREAM
);
2534 insint(d
, "SOCK_DGRAM", SOCK_DGRAM
);
2536 /* We have incomplete socket support. */
2537 insint(d
, "SOCK_RAW", SOCK_RAW
);
2538 insint(d
, "SOCK_SEQPACKET", SOCK_SEQPACKET
);
2539 insint(d
, "SOCK_RDM", SOCK_RDM
);
2543 insint(d
, "SO_DEBUG", SO_DEBUG
);
2545 #ifdef SO_ACCEPTCONN
2546 insint(d
, "SO_ACCEPTCONN", SO_ACCEPTCONN
);
2549 insint(d
, "SO_REUSEADDR", SO_REUSEADDR
);
2552 insint(d
, "SO_KEEPALIVE", SO_KEEPALIVE
);
2555 insint(d
, "SO_DONTROUTE", SO_DONTROUTE
);
2558 insint(d
, "SO_BROADCAST", SO_BROADCAST
);
2560 #ifdef SO_USELOOPBACK
2561 insint(d
, "SO_USELOOPBACK", SO_USELOOPBACK
);
2564 insint(d
, "SO_LINGER", SO_LINGER
);
2567 insint(d
, "SO_OOBINLINE", SO_OOBINLINE
);
2570 insint(d
, "SO_REUSEPORT", SO_REUSEPORT
);
2573 insint(d
, "SO_SNDBUF", SO_SNDBUF
);
2576 insint(d
, "SO_RCVBUF", SO_RCVBUF
);
2579 insint(d
, "SO_SNDLOWAT", SO_SNDLOWAT
);
2582 insint(d
, "SO_RCVLOWAT", SO_RCVLOWAT
);
2585 insint(d
, "SO_SNDTIMEO", SO_SNDTIMEO
);
2588 insint(d
, "SO_RCVTIMEO", SO_RCVTIMEO
);
2591 insint(d
, "SO_ERROR", SO_ERROR
);
2594 insint(d
, "SO_TYPE", SO_TYPE
);
2597 /* Maximum number of connections for "listen" */
2599 insint(d
, "SOMAXCONN", SOMAXCONN
);
2601 insint(d
, "SOMAXCONN", 5); /* Common value */
2604 /* Flags for send, recv */
2606 insint(d
, "MSG_OOB", MSG_OOB
);
2609 insint(d
, "MSG_PEEK", MSG_PEEK
);
2611 #ifdef MSG_DONTROUTE
2612 insint(d
, "MSG_DONTROUTE", MSG_DONTROUTE
);
2615 insint(d
, "MSG_DONTWAIT", MSG_DONTWAIT
);
2618 insint(d
, "MSG_EOR", MSG_EOR
);
2621 insint(d
, "MSG_TRUNC", MSG_TRUNC
);
2624 insint(d
, "MSG_CTRUNC", MSG_CTRUNC
);
2627 insint(d
, "MSG_WAITALL", MSG_WAITALL
);
2630 insint(d
, "MSG_BTAG", MSG_BTAG
);
2633 insint(d
, "MSG_ETAG", MSG_ETAG
);
2636 /* Protocol level and numbers, usable for [gs]etsockopt */
2638 insint(d
, "SOL_SOCKET", SOL_SOCKET
);
2641 insint(d
, "SOL_IP", SOL_IP
);
2643 insint(d
, "SOL_IP", 0);
2646 insint(d
, "SOL_IPX", SOL_IPX
);
2649 insint(d
, "SOL_AX25", SOL_AX25
);
2652 insint(d
, "SOL_ATALK", SOL_ATALK
);
2655 insint(d
, "SOL_NETROM", SOL_NETROM
);
2658 insint(d
, "SOL_ROSE", SOL_ROSE
);
2661 insint(d
, "SOL_TCP", SOL_TCP
);
2663 insint(d
, "SOL_TCP", 6);
2666 insint(d
, "SOL_UDP", SOL_UDP
);
2668 insint(d
, "SOL_UDP", 17);
2671 insint(d
, "IPPROTO_IP", IPPROTO_IP
);
2673 insint(d
, "IPPROTO_IP", 0);
2676 insint(d
, "IPPROTO_ICMP", IPPROTO_ICMP
);
2678 insint(d
, "IPPROTO_ICMP", 1);
2681 insint(d
, "IPPROTO_IGMP", IPPROTO_IGMP
);
2684 insint(d
, "IPPROTO_GGP", IPPROTO_GGP
);
2687 insint(d
, "IPPROTO_TCP", IPPROTO_TCP
);
2689 insint(d
, "IPPROTO_TCP", 6);
2692 insint(d
, "IPPROTO_EGP", IPPROTO_EGP
);
2695 insint(d
, "IPPROTO_PUP", IPPROTO_PUP
);
2698 insint(d
, "IPPROTO_UDP", IPPROTO_UDP
);
2700 insint(d
, "IPPROTO_UDP", 17);
2703 insint(d
, "IPPROTO_IDP", IPPROTO_IDP
);
2705 #ifdef IPPROTO_HELLO
2706 insint(d
, "IPPROTO_HELLO", IPPROTO_HELLO
);
2709 insint(d
, "IPPROTO_ND", IPPROTO_ND
);
2712 insint(d
, "IPPROTO_TP", IPPROTO_TP
);
2715 insint(d
, "IPPROTO_XTP", IPPROTO_XTP
);
2718 insint(d
, "IPPROTO_EON", IPPROTO_EON
);
2721 insint(d
, "IPPROTO_BIP", IPPROTO_BIP
);
2725 insint(d
, "IPPROTO_RAW", IPPROTO_RAW
);
2727 insint(d
, "IPPROTO_RAW", 255);
2730 insint(d
, "IPPROTO_MAX", IPPROTO_MAX
);
2733 /* Some port configuration */
2734 #ifdef IPPORT_RESERVED
2735 insint(d
, "IPPORT_RESERVED", IPPORT_RESERVED
);
2737 insint(d
, "IPPORT_RESERVED", 1024);
2739 #ifdef IPPORT_USERRESERVED
2740 insint(d
, "IPPORT_USERRESERVED", IPPORT_USERRESERVED
);
2742 insint(d
, "IPPORT_USERRESERVED", 5000);
2745 /* Some reserved IP v.4 addresses */
2747 insint(d
, "INADDR_ANY", INADDR_ANY
);
2749 insint(d
, "INADDR_ANY", 0x00000000);
2751 #ifdef INADDR_BROADCAST
2752 insint(d
, "INADDR_BROADCAST", INADDR_BROADCAST
);
2754 insint(d
, "INADDR_BROADCAST", 0xffffffff);
2756 #ifdef INADDR_LOOPBACK
2757 insint(d
, "INADDR_LOOPBACK", INADDR_LOOPBACK
);
2759 insint(d
, "INADDR_LOOPBACK", 0x7F000001);
2761 #ifdef INADDR_UNSPEC_GROUP
2762 insint(d
, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP
);
2764 insint(d
, "INADDR_UNSPEC_GROUP", 0xe0000000);
2766 #ifdef INADDR_ALLHOSTS_GROUP
2767 insint(d
, "INADDR_ALLHOSTS_GROUP", INADDR_ALLHOSTS_GROUP
);
2769 insint(d
, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
2771 #ifdef INADDR_MAX_LOCAL_GROUP
2772 insint(d
, "INADDR_MAX_LOCAL_GROUP", INADDR_MAX_LOCAL_GROUP
);
2774 insint(d
, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
2777 insint(d
, "INADDR_NONE", INADDR_NONE
);
2779 insint(d
, "INADDR_NONE", 0xffffffff);
2782 /* IP [gs]etsockopt options */
2784 insint(d
, "IP_OPTIONS", IP_OPTIONS
);
2787 insint(d
, "IP_HDRINCL", IP_HDRINCL
);
2790 insint(d
, "IP_TOS", IP_TOS
);
2793 insint(d
, "IP_TTL", IP_TTL
);
2796 insint(d
, "IP_RECVOPTS", IP_RECVOPTS
);
2798 #ifdef IP_RECVRETOPTS
2799 insint(d
, "IP_RECVRETOPTS", IP_RECVRETOPTS
);
2801 #ifdef IP_RECVDSTADDR
2802 insint(d
, "IP_RECVDSTADDR", IP_RECVDSTADDR
);
2805 insint(d
, "IP_RETOPTS", IP_RETOPTS
);
2807 #ifdef IP_MULTICAST_IF
2808 insint(d
, "IP_MULTICAST_IF", IP_MULTICAST_IF
);
2810 #ifdef IP_MULTICAST_TTL
2811 insint(d
, "IP_MULTICAST_TTL", IP_MULTICAST_TTL
);
2813 #ifdef IP_MULTICAST_LOOP
2814 insint(d
, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP
);
2816 #ifdef IP_ADD_MEMBERSHIP
2817 insint(d
, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP
);
2819 #ifdef IP_DROP_MEMBERSHIP
2820 insint(d
, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP
);
2822 #ifdef IP_DEFAULT_MULTICAST_TTL
2823 insint(d
, "IP_DEFAULT_MULTICAST_TTL", IP_DEFAULT_MULTICAST_TTL
);
2825 #ifdef IP_DEFAULT_MULTICAST_LOOP
2826 insint(d
, "IP_DEFAULT_MULTICAST_LOOP", IP_DEFAULT_MULTICAST_LOOP
);
2828 #ifdef IP_MAX_MEMBERSHIPS
2829 insint(d
, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS
);
2834 insint(d
, "TCP_NODELAY", TCP_NODELAY
);
2837 insint(d
, "TCP_MAXSEG", TCP_MAXSEG
);
2842 insint(d
, "IPX_TYPE", IPX_TYPE
);
2845 /* Initialize gethostbyname lock */
2846 #ifdef USE_GETHOSTBYNAME_LOCK
2847 gethostbyname_lock
= PyThread_allocate_lock();