Updated for 2.1a3
[python/dscho.git] / Modules / socketmodule.c
blobdffd810ed38448eec576c4adb25f932e558d5e3b
1 /* Socket module */
3 /* SSL support based on patches by Brian E Gallew and Laszlo Kovacs */
5 /*
6 This module provides an interface to Berkeley socket IPC.
8 Limitations:
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
15 Module interface:
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
43 getsockname() method.
45 Socket methods:
47 - s.accept() --> new socket object, sockaddr
48 - s.bind(sockaddr) --> None
49 - s.close() --> 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>"
70 #include "Python.h"
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! */
77 #ifndef linux
78 #undef HAVE_GETHOSTBYNAME_R_3_ARG
79 #undef HAVE_GETHOSTBYNAME_R_5_ARG
80 #undef HAVE_GETHOSTBYNAME_R_6_ARG
81 #endif
83 #ifndef WITH_THREAD
84 #undef HAVE_GETHOSTBYNAME_R
85 #endif
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
92 #elif defined(linux)
93 /* Rely on the configure script */
94 #else
95 #undef HAVE_GETHOSTBYNAME_R
96 #endif
97 #endif
99 #if !defined(HAVE_GETHOSTBYNAME_R) && defined(WITH_THREAD) && !defined(MS_WINDOWS)
100 #define USE_GETHOSTBYNAME_LOCK
101 #endif
103 #ifdef USE_GETHOSTBYNAME_LOCK
104 #include "pythread.h"
105 #endif
107 #ifdef HAVE_UNISTD_H
108 #include <unistd.h>
109 #endif
111 #if defined(PYCC_VACPP)
112 #include <types.h>
113 #include <io.h>
114 #include <sys/ioctl.h>
115 #include <utils.h>
116 #include <ctype.h>
117 #endif
119 #if defined(PYOS_OS2)
120 #define INCL_DOS
121 #define INCL_DOSERRORS
122 #define INCL_NOPMAPI
123 #include <os2.h>
124 #endif
126 #include <sys/types.h>
128 #include <signal.h>
129 #ifndef MS_WINDOWS
130 #include <netdb.h>
131 #include <sys/socket.h>
132 #include <netinet/in.h>
133 #if !(defined(__BEOS__) || defined(__CYGWIN__))
134 #include <netinet/tcp.h>
135 #endif
137 /* Headers needed for inet_ntoa() and inet_addr() */
138 #ifdef __BEOS__
139 #include <net/netdb.h>
140 #else
141 #ifndef USE_GUSI1
142 #include <arpa/inet.h>
143 #endif
144 #endif
146 #include <fcntl.h>
147 #else
148 #include <winsock.h>
149 #include <fcntl.h>
150 #endif
151 #ifdef HAVE_SYS_UN_H
152 #include <sys/un.h>
153 #else
154 #undef AF_UNIX
155 #endif
157 #if defined(linux) && defined(AF_PACKET)
158 #include <sys/ioctl.h>
159 #include <net/if.h>
160 #include <netpacket/packet.h>
161 #endif
163 #ifndef O_NDELAY
164 #define O_NDELAY O_NONBLOCK /* For QNX only? */
165 #endif
167 #ifdef USE_GUSI1
168 /* fdopen() isn't declared in stdio.h (sigh) */
169 #include <GUSI.h>
170 #endif
172 #ifdef USE_SSL
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"
179 #endif /* USE_SSL */
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... */
186 #endif
188 /* abstract the socket file descriptor type */
189 #ifdef MS_WINDOWS
190 typedef SOCKET SOCKET_T;
191 # ifdef MS_WIN64
192 # define SIZEOF_SOCKET_T 8
193 # else
194 # define SIZEOF_SOCKET_T 4
195 # endif
196 #else
197 typedef int SOCKET_T;
198 # define SIZEOF_SOCKET_T SIZEOF_INT
199 #endif
202 #if defined(PYOS_OS2)
203 #define SOCKETCLOSE soclose
204 #define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
205 #endif
207 #ifndef SOCKETCLOSE
208 #define SOCKETCLOSE close
209 #endif
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;
216 #ifdef USE_SSL
217 static PyObject *SSLErrorObject;
218 #endif /* USE_SSL */
221 /* Convenience function to raise an error according to errno
222 and return a NULL pointer from a function. */
224 static PyObject *
225 PySocket_Err(void)
227 #ifdef MS_WINDOWS
228 int err_no = WSAGetLastError();
229 if (err_no) {
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" },
237 { WSAEWOULDBLOCK,
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" },
253 { WSAEADDRNOTAVAIL,
254 "Can't assign requested address" },
255 { WSAENETDOWN, "Network is down" },
256 { WSAENETUNREACH, "Network is unreachable" },
257 { WSAENETRESET,
258 "Network dropped connection on reset" },
259 { WSAECONNABORTED,
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" },
266 { WSAETOOMANYREFS,
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" },
280 { WSASYSNOTREADY,
281 "Network subsystem is unvailable" },
282 { WSAVERNOTSUPPORTED,
283 "WinSock version is not supported" },
284 { WSANOTINITIALISED,
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" },
290 { WSANO_RECOVERY,
291 "Unexpected server error encountered" },
292 { WSANO_DATA, "Valid name without requested data" },
293 { WSANO_ADDRESS, "No address, look for MX record" },
294 { 0, NULL }
296 PyObject *v;
297 const char *msg = "winsock error";
299 for (msgp = msgs; msgp->msg; msgp++) {
300 if (err_no == msgp->no) {
301 msg = msgp->msg;
302 break;
306 v = Py_BuildValue("(is)", err_no, msg);
307 if (v != NULL) {
308 PyErr_SetObject(PySocket_Error, v);
309 Py_DECREF(v);
311 return NULL;
313 else
314 #endif
316 #if defined(PYOS_OS2)
317 if (sock_errno() != NO_ERROR) {
318 APIRET rc;
319 ULONG msglen;
320 char outbuf[100];
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) {
327 PyObject *v;
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);
336 if (v != NULL) {
337 PyErr_SetObject(PySocket_Error, v);
338 Py_DECREF(v);
340 return NULL;
343 #endif
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. */
353 typedef struct {
354 PyObject_HEAD
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 */
359 union sock_addr {
360 struct sockaddr_in in;
361 #ifdef AF_UNIX
362 struct sockaddr_un un;
363 #endif
364 #if defined(linux) && defined(AF_PACKET)
365 struct sockaddr_ll ll;
366 #endif
367 } sock_addr;
368 } PySocketSockObject;
370 #ifdef USE_SSL
372 typedef struct {
373 PyObject_HEAD
374 PySocketSockObject *Socket; /* Socket on which we're layered */
375 PyObject *x_attr; /* Attributes dictionary */
376 SSL_CTX* ctx;
377 SSL* ssl;
378 X509* server_cert;
379 BIO* sbio;
380 char server[256];
381 char issuer[256];
383 } SSLObject;
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)
391 #endif /* USE_SSL */
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
404 in NEWOBJ()). */
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);
412 if (s != NULL) {
413 s->sock_fd = fd;
414 s->sock_family = family;
415 s->sock_type = type;
416 s->sock_proto = proto;
418 return s;
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;
426 #endif
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. */
435 static int
436 setipaddr(char* name, struct sockaddr_in * addr_ret)
438 struct hostent *hp;
439 int d1, d2, d3, d4;
440 int h_length;
441 char ch;
442 #ifdef HAVE_GETHOSTBYNAME_R
443 struct hostent hp_allocated;
444 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
445 struct hostent_data data;
446 #else
447 char buf[1001];
448 int buf_len = (sizeof buf) - 1;
449 int errnop;
450 #endif
451 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
452 int result;
453 #endif
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;
459 return 4;
461 if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
462 addr_ret->sin_addr.s_addr = INADDR_BROADCAST;
463 return 4;
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));
471 return 4;
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;
483 #endif
484 #else /* not HAVE_GETHOSTBYNAME_R */
485 #ifdef USE_GETHOSTBYNAME_LOCK
486 PyThread_acquire_lock(gethostbyname_lock, 1);
487 #endif
488 hp = gethostbyname(name);
489 #endif /* HAVE_GETHOSTBYNAME_R */
490 Py_END_ALLOW_THREADS
492 if (hp == NULL) {
493 #ifdef HAVE_HSTRERROR
494 /* Let's get real error message to return */
495 extern int h_errno;
496 PyErr_SetString(PySocket_Error, (char *)hstrerror(h_errno));
497 #else
498 PyErr_SetString(PySocket_Error, "host not found");
499 #endif
500 #ifdef USE_GETHOSTBYNAME_LOCK
501 PyThread_release_lock(gethostbyname_lock);
502 #endif
503 return -1;
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);
509 #endif
510 return h_length;
514 /* Create a string object representing an IP address.
515 This is always a string of the form 'dd.dd.dd.dd' (with variable
516 size numbers). */
518 static PyObject *
519 makeipaddr(struct sockaddr_in *addr)
521 long x = ntohl(addr->sin_addr.s_addr);
522 char buf[100];
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. */
535 /*ARGSUSED*/
536 static PyObject *
537 makesockaddr(int sockfd, struct sockaddr *addr, int addrlen)
539 if (addrlen == 0) {
540 /* No address -- may be recvfrom() from known socket */
541 Py_INCREF(Py_None);
542 return Py_None;
545 #ifdef __BEOS__
546 /* XXX: BeOS version of accept() doesn't set family correctly */
547 addr->sa_family = AF_INET;
548 #endif
550 switch (addr->sa_family) {
552 case AF_INET:
554 struct sockaddr_in *a = (struct sockaddr_in *) addr;
555 PyObject *addrobj = makeipaddr(a);
556 PyObject *ret = NULL;
557 if (addrobj) {
558 ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
559 Py_DECREF(addrobj);
561 return ret;
564 #ifdef AF_UNIX
565 case AF_UNIX:
567 struct sockaddr_un *a = (struct sockaddr_un *) addr;
568 return PyString_FromString(a->sun_path);
570 #endif
572 #if defined(linux) && defined(AF_PACKET)
573 case AF_PACKET:
575 struct sockaddr_ll *a = (struct sockaddr_ll *)addr;
576 char *ifname = "";
577 struct ifreq ifr;
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);
588 #endif
590 /* More cases here... */
592 default:
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#",
596 addr->sa_family,
597 addr->sa_data,
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
607 through len_ret. */
609 static int
610 getsockaddrarg(PySocketSockObject *s, PyObject *args,
611 struct sockaddr **addr_ret, int *len_ret)
613 switch (s->sock_family) {
615 #ifdef AF_UNIX
616 case AF_UNIX:
618 struct sockaddr_un* addr;
619 char *path;
620 int len;
621 addr = (struct sockaddr_un* )&(s->sock_addr).un;
622 if (!PyArg_Parse(args, "t#", &path, &len))
623 return 0;
624 if (len > sizeof addr->sun_path) {
625 PyErr_SetString(PySocket_Error,
626 "AF_UNIX path too long");
627 return 0;
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);
634 return 1;
636 #endif /* AF_UNIX */
638 case AF_INET:
640 struct sockaddr_in* addr;
641 char *host;
642 int port;
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);
648 return 0;
650 if (!PyArg_ParseTuple(args, "si:getsockaddrarg", &host, &port))
651 return 0;
652 if (setipaddr(host, addr) < 0)
653 return 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;
658 return 1;
661 #if defined(linux) && defined(AF_PACKET)
662 case AF_PACKET:
664 struct sockaddr_ll* addr;
665 struct ifreq ifr;
666 char *interfaceName;
667 int protoNumber;
668 int hatype = 0;
669 int pkttype = 0;
670 char *haddr;
672 if (!PyArg_ParseTuple(args, "si|iis", &interfaceName,
673 &protoNumber, &pkttype, &hatype, &haddr))
674 return 0;
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);
679 return 0;
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;
689 return 1;
691 #endif
694 /* More cases here... */
696 default:
697 PyErr_SetString(PySocket_Error, "getsockaddrarg: bad family");
698 return 0;
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
706 through len_ret. */
708 static int
709 getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
711 switch (s->sock_family) {
713 #ifdef AF_UNIX
714 case AF_UNIX:
716 *len_ret = sizeof (struct sockaddr_un);
717 return 1;
719 #endif /* AF_UNIX */
721 case AF_INET:
723 *len_ret = sizeof (struct sockaddr_in);
724 return 1;
727 #if defined(linux) && defined(AF_PACKET)
728 case AF_PACKET:
730 *len_ret = sizeof (struct sockaddr_ll);
731 return 1;
733 #endif
735 /* More cases here... */
737 default:
738 PyErr_SetString(PySocket_Error, "getsockaddrlen: bad family");
739 return 0;
745 /* s.accept() method */
747 static PyObject *
748 PySocketSock_accept(PySocketSockObject *s, PyObject *args)
750 char addrbuf[256];
751 SOCKET_T newfd;
752 socklen_t addrlen;
753 PyObject *sock = NULL;
754 PyObject *addr = NULL;
755 PyObject *res = NULL;
757 if (!PyArg_ParseTuple(args, ":accept"))
758 return NULL;
759 if (!getsockaddrlen(s, &addrlen))
760 return NULL;
761 Py_BEGIN_ALLOW_THREADS
762 newfd = accept(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
763 Py_END_ALLOW_THREADS
764 #ifdef MS_WINDOWS
765 if (newfd == INVALID_SOCKET)
766 #else
767 if (newfd < 0)
768 #endif
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,
774 s->sock_family,
775 s->sock_type,
776 s->sock_proto);
777 if (sock == NULL) {
778 SOCKETCLOSE(newfd);
779 goto finally;
781 addr = makesockaddr(s->sock_fd, (struct sockaddr *)addrbuf,
782 addrlen);
783 if (addr == NULL)
784 goto finally;
786 res = Py_BuildValue("OO", sock, addr);
788 finally:
789 Py_XDECREF(sock);
790 Py_XDECREF(addr);
791 return res;
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 */
804 static PyObject *
805 PySocketSock_setblocking(PySocketSockObject *s, PyObject *args)
807 int block;
808 #ifndef MS_WINDOWS
809 int delay_flag;
810 #endif
811 if (!PyArg_ParseTuple(args, "i:setblocking", &block))
812 return NULL;
813 Py_BEGIN_ALLOW_THREADS
814 #ifdef __BEOS__
815 block = !block;
816 setsockopt( s->sock_fd, SOL_SOCKET, SO_NONBLOCK,
817 (void *)(&block), sizeof( int ) );
818 #else
819 #ifndef MS_WINDOWS
820 #ifdef PYOS_OS2
821 block = !block;
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);
825 if (block)
826 delay_flag &= (~O_NDELAY);
827 else
828 delay_flag |= O_NDELAY;
829 fcntl (s->sock_fd, F_SETFL, delay_flag);
830 #endif /* !PYOS_OS2 */
831 #else /* MS_WINDOWS */
832 block = !block;
833 ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
834 #endif /* MS_WINDOWS */
835 #endif /* __BEOS__ */
836 Py_END_ALLOW_THREADS
838 Py_INCREF(Py_None);
839 return Py_None;
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. */
854 static PyObject *
855 PySocketSock_setsockopt(PySocketSockObject *s, PyObject *args)
857 int level;
858 int optname;
859 int res;
860 char *buf;
861 int buflen;
862 int flag;
864 if (PyArg_ParseTuple(args, "iii:setsockopt",
865 &level, &optname, &flag)) {
866 buf = (char *) &flag;
867 buflen = sizeof flag;
869 else {
870 PyErr_Clear();
871 if (!PyArg_ParseTuple(args, "iis#:setsockopt",
872 &level, &optname, &buf, &buflen))
873 return NULL;
875 res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen);
876 if (res < 0)
877 return PySocket_Err();
878 Py_INCREF(Py_None);
879 return Py_None;
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. */
894 static PyObject *
895 PySocketSock_getsockopt(PySocketSockObject *s, PyObject *args)
897 int level;
898 int optname;
899 int res;
900 PyObject *buf;
901 socklen_t buflen = 0;
903 #ifdef __BEOS__
904 /* We have incomplete socket support. */
905 PyErr_SetString( PySocket_Error, "getsockopt not supported" );
906 return NULL;
907 #else
909 if (!PyArg_ParseTuple(args, "ii|i:getsockopt",
910 &level, &optname, &buflen))
911 return NULL;
913 if (buflen == 0) {
914 int flag = 0;
915 socklen_t flagsize = sizeof flag;
916 res = getsockopt(s->sock_fd, level, optname,
917 (void *)&flag, &flagsize);
918 if (res < 0)
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");
925 return NULL;
927 buf = PyString_FromStringAndSize((char *)NULL, buflen);
928 if (buf == NULL)
929 return NULL;
930 res = getsockopt(s->sock_fd, level, optname,
931 (void *)PyString_AsString(buf), &buflen);
932 if (res < 0) {
933 Py_DECREF(buf);
934 return PySocket_Err();
936 _PyString_Resize(&buf, buflen);
937 return buf;
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 */
951 static PyObject *
952 PySocketSock_bind(PySocketSockObject *s, PyObject *args)
954 struct sockaddr *addr;
955 int addrlen;
956 int res;
957 PyObject *addro;
958 if (!PyArg_ParseTuple(args, "O:bind", &addro))
959 return NULL;
960 if (!getsockaddrarg(s, addro, &addr, &addrlen))
961 return NULL;
962 Py_BEGIN_ALLOW_THREADS
963 res = bind(s->sock_fd, addr, addrlen);
964 Py_END_ALLOW_THREADS
965 if (res < 0)
966 return PySocket_Err();
967 Py_INCREF(Py_None);
968 return Py_None;
971 static char bind_doc[] =
972 "bind(address)\n\
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]])";
979 /* s.close() method.
980 Set the file descriptor to -1 so operations tried subsequently
981 will surely fail. */
983 static PyObject *
984 PySocketSock_close(PySocketSockObject *s, PyObject *args)
986 SOCKET_T fd;
987 if (!PyArg_ParseTuple(args, ":close"))
988 return NULL;
989 if ((fd = s->sock_fd) != -1) {
990 s->sock_fd = -1;
991 Py_BEGIN_ALLOW_THREADS
992 (void) SOCKETCLOSE(fd);
993 Py_END_ALLOW_THREADS
995 Py_INCREF(Py_None);
996 return Py_None;
999 static char close_doc[] =
1000 "close()\n\
1002 Close the socket. It cannot be used after this call.";
1005 /* s.connect(sockaddr) method */
1007 static PyObject *
1008 PySocketSock_connect(PySocketSockObject *s, PyObject *args)
1010 struct sockaddr *addr;
1011 int addrlen;
1012 int res;
1013 PyObject *addro;
1014 if (!PyArg_ParseTuple(args, "O:connect", &addro))
1015 return NULL;
1016 if (!getsockaddrarg(s, addro, &addr, &addrlen))
1017 return NULL;
1018 Py_BEGIN_ALLOW_THREADS
1019 res = connect(s->sock_fd, addr, addrlen);
1020 Py_END_ALLOW_THREADS
1021 if (res < 0)
1022 return PySocket_Err();
1023 Py_INCREF(Py_None);
1024 return Py_None;
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 */
1036 static PyObject *
1037 PySocketSock_connect_ex(PySocketSockObject *s, PyObject *args)
1039 struct sockaddr *addr;
1040 int addrlen;
1041 int res;
1042 PyObject *addro;
1043 if (!PyArg_ParseTuple(args, "O:connect_ex", &addro))
1044 return NULL;
1045 if (!getsockaddrarg(s, addro, &addr, &addrlen))
1046 return NULL;
1047 Py_BEGIN_ALLOW_THREADS
1048 res = connect(s->sock_fd, addr, addrlen);
1049 Py_END_ALLOW_THREADS
1050 if (res != 0)
1051 res = errno;
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 */
1064 static PyObject *
1065 PySocketSock_fileno(PySocketSockObject *s, PyObject *args)
1067 if (!PyArg_ParseTuple(args, ":fileno"))
1068 return NULL;
1069 #if SIZEOF_SOCKET_T <= SIZEOF_LONG
1070 return PyInt_FromLong((long) s->sock_fd);
1071 #else
1072 return PyLong_FromLongLong((LONG_LONG)s->sock_fd);
1073 #endif
1076 static char fileno_doc[] =
1077 "fileno() -> integer\n\
1079 Return the integer file descriptor of the socket.";
1082 #ifndef NO_DUP
1083 /* s.dup() method */
1085 static PyObject *
1086 PySocketSock_dup(PySocketSockObject *s, PyObject *args)
1088 SOCKET_T newfd;
1089 PyObject *sock;
1090 if (!PyArg_ParseTuple(args, ":dup"))
1091 return NULL;
1092 newfd = dup(s->sock_fd);
1093 if (newfd < 0)
1094 return PySocket_Err();
1095 sock = (PyObject *) PySocketSock_New(newfd,
1096 s->sock_family,
1097 s->sock_type,
1098 s->sock_proto);
1099 if (sock == NULL)
1100 SOCKETCLOSE(newfd);
1101 return sock;
1104 static char dup_doc[] =
1105 "dup() -> socket object\n\
1107 Return a new socket object connected to the same system resource.";
1109 #endif
1112 /* s.getsockname() method */
1114 static PyObject *
1115 PySocketSock_getsockname(PySocketSockObject *s, PyObject *args)
1117 char addrbuf[256];
1118 int res;
1119 socklen_t addrlen;
1121 if (!PyArg_ParseTuple(args, ":getsockname"))
1122 return NULL;
1123 if (!getsockaddrlen(s, &addrlen))
1124 return NULL;
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
1129 if (res < 0)
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 */
1144 static PyObject *
1145 PySocketSock_getpeername(PySocketSockObject *s, PyObject *args)
1147 char addrbuf[256];
1148 int res;
1149 socklen_t addrlen;
1151 if (!PyArg_ParseTuple(args, ":getpeername"))
1152 return NULL;
1153 if (!getsockaddrlen(s, &addrlen))
1154 return NULL;
1155 Py_BEGIN_ALLOW_THREADS
1156 res = getpeername(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
1157 Py_END_ALLOW_THREADS
1158 if (res < 0)
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 */
1174 static PyObject *
1175 PySocketSock_listen(PySocketSockObject *s, PyObject *args)
1177 int backlog;
1178 int res;
1179 if (!PyArg_ParseTuple(args, "i:listen", &backlog))
1180 return NULL;
1181 Py_BEGIN_ALLOW_THREADS
1182 if (backlog < 1)
1183 backlog = 1;
1184 res = listen(s->sock_fd, backlog);
1185 Py_END_ALLOW_THREADS
1186 if (res < 0)
1187 return PySocket_Err();
1188 Py_INCREF(Py_None);
1189 return Py_None;
1192 static char listen_doc[] =
1193 "listen(backlog)\n\
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.";
1200 #ifndef NO_DUP
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
1205 of each other.)
1206 The mode argument specifies 'r' or 'w' passed to fdopen(). */
1208 static PyObject *
1209 PySocketSock_makefile(PySocketSockObject *s, PyObject *args)
1211 extern int fclose(FILE *);
1212 char *mode = "r";
1213 int bufsize = -1;
1214 #ifdef MS_WIN32
1215 intptr_t fd;
1216 #else
1217 int fd;
1218 #endif
1219 FILE *fp;
1220 PyObject *f;
1222 if (!PyArg_ParseTuple(args, "|si:makefile", &mode, &bufsize))
1223 return NULL;
1224 #ifdef MS_WIN32
1225 if (((fd = _open_osfhandle(s->sock_fd, _O_BINARY)) < 0) ||
1226 ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL))
1227 #else
1228 if ((fd = dup(s->sock_fd)) < 0 || (fp = fdopen(fd, mode)) == NULL)
1229 #endif
1231 if (fd >= 0)
1232 SOCKETCLOSE(fd);
1233 return PySocket_Err();
1235 f = PyFile_FromFile(fp, "<socket>", mode, fclose);
1236 if (f != NULL)
1237 PyFile_SetBufSize(f, bufsize);
1238 return f;
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.";
1247 #endif /* NO_DUP */
1250 /* s.recv(nbytes [,flags]) method */
1252 static PyObject *
1253 PySocketSock_recv(PySocketSockObject *s, PyObject *args)
1255 int len, n, flags = 0;
1256 PyObject *buf;
1257 if (!PyArg_ParseTuple(args, "i|i:recv", &len, &flags))
1258 return NULL;
1259 buf = PyString_FromStringAndSize((char *) 0, len);
1260 if (buf == NULL)
1261 return NULL;
1262 Py_BEGIN_ALLOW_THREADS
1263 n = recv(s->sock_fd, PyString_AsString(buf), len, flags);
1264 Py_END_ALLOW_THREADS
1265 if (n < 0) {
1266 Py_DECREF(buf);
1267 return PySocket_Err();
1269 if (n != len && _PyString_Resize(&buf, n) < 0)
1270 return NULL;
1271 return buf;
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 */
1285 static PyObject *
1286 PySocketSock_recvfrom(PySocketSockObject *s, PyObject *args)
1288 char addrbuf[256];
1289 PyObject *buf = NULL;
1290 PyObject *addr = NULL;
1291 PyObject *ret = NULL;
1293 int len, n, flags = 0;
1294 socklen_t addrlen;
1295 if (!PyArg_ParseTuple(args, "i|i:recvfrom", &len, &flags))
1296 return NULL;
1297 if (!getsockaddrlen(s, &addrlen))
1298 return NULL;
1299 buf = PyString_FromStringAndSize((char *) 0, len);
1300 if (buf == NULL)
1301 return NULL;
1302 Py_BEGIN_ALLOW_THREADS
1303 n = recvfrom(s->sock_fd, PyString_AsString(buf), len, flags,
1304 #ifndef MS_WINDOWS
1305 #if defined(PYOS_OS2)
1306 (struct sockaddr *)addrbuf, &addrlen
1307 #else
1308 (void *)addrbuf, &addrlen
1309 #endif
1310 #else
1311 (struct sockaddr *)addrbuf, &addrlen
1312 #endif
1314 Py_END_ALLOW_THREADS
1315 if (n < 0) {
1316 Py_DECREF(buf);
1317 return PySocket_Err();
1319 if (n != len && _PyString_Resize(&buf, n) < 0)
1320 return NULL;
1322 if (!(addr = makesockaddr(s->sock_fd, (struct sockaddr *)addrbuf, addrlen)))
1323 goto finally;
1325 ret = Py_BuildValue("OO", buf, addr);
1326 finally:
1327 Py_XDECREF(addr);
1328 Py_XDECREF(buf);
1329 return ret;
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 */
1340 static PyObject *
1341 PySocketSock_send(PySocketSockObject *s, PyObject *args)
1343 char *buf;
1344 int len, n, flags = 0;
1345 if (!PyArg_ParseTuple(args, "s#|i:send", &buf, &len, &flags))
1346 return NULL;
1347 Py_BEGIN_ALLOW_THREADS
1348 n = send(s->sock_fd, buf, len, flags);
1349 Py_END_ALLOW_THREADS
1350 if (n < 0)
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 */
1364 static PyObject *
1365 PySocketSock_sendto(PySocketSockObject *s, PyObject *args)
1367 PyObject *addro;
1368 char *buf;
1369 struct sockaddr *addr;
1370 int addrlen, len, n, flags;
1371 flags = 0;
1372 if (!PyArg_ParseTuple(args, "s#O:sendto", &buf, &len, &addro)) {
1373 PyErr_Clear();
1374 if (!PyArg_ParseTuple(args, "s#iO:sendto",
1375 &buf, &len, &flags, &addro))
1376 return NULL;
1378 if (!getsockaddrarg(s, addro, &addr, &addrlen))
1379 return NULL;
1380 Py_BEGIN_ALLOW_THREADS
1381 n = sendto(s->sock_fd, buf, len, flags, addr, addrlen);
1382 Py_END_ALLOW_THREADS
1383 if (n < 0)
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 */
1397 static PyObject *
1398 PySocketSock_shutdown(PySocketSockObject *s, PyObject *args)
1400 int how;
1401 int res;
1402 if (!PyArg_ParseTuple(args, "i:shutdown", &how))
1403 return NULL;
1404 Py_BEGIN_ALLOW_THREADS
1405 res = shutdown(s->sock_fd, how);
1406 Py_END_ALLOW_THREADS
1407 if (res < 0)
1408 return PySocket_Err();
1409 Py_INCREF(Py_None);
1410 return Py_None;
1413 static char shutdown_doc[] =
1414 "shutdown(flag)\n\
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,
1424 accept_doc},
1425 {"bind", (PyCFunction)PySocketSock_bind, METH_VARARGS,
1426 bind_doc},
1427 {"close", (PyCFunction)PySocketSock_close, METH_VARARGS,
1428 close_doc},
1429 {"connect", (PyCFunction)PySocketSock_connect, METH_VARARGS,
1430 connect_doc},
1431 {"connect_ex", (PyCFunction)PySocketSock_connect_ex, METH_VARARGS,
1432 connect_ex_doc},
1433 #ifndef NO_DUP
1434 {"dup", (PyCFunction)PySocketSock_dup, METH_VARARGS,
1435 dup_doc},
1436 #endif
1437 {"fileno", (PyCFunction)PySocketSock_fileno, METH_VARARGS,
1438 fileno_doc},
1439 #ifdef HAVE_GETPEERNAME
1440 {"getpeername", (PyCFunction)PySocketSock_getpeername, METH_VARARGS,
1441 getpeername_doc},
1442 #endif
1443 {"getsockname", (PyCFunction)PySocketSock_getsockname, METH_VARARGS,
1444 getsockname_doc},
1445 {"getsockopt", (PyCFunction)PySocketSock_getsockopt, METH_VARARGS,
1446 getsockopt_doc},
1447 {"listen", (PyCFunction)PySocketSock_listen, METH_VARARGS,
1448 listen_doc},
1449 #ifndef NO_DUP
1450 {"makefile", (PyCFunction)PySocketSock_makefile, METH_VARARGS,
1451 makefile_doc},
1452 #endif
1453 {"recv", (PyCFunction)PySocketSock_recv, METH_VARARGS,
1454 recv_doc},
1455 {"recvfrom", (PyCFunction)PySocketSock_recvfrom, METH_VARARGS,
1456 recvfrom_doc},
1457 {"send", (PyCFunction)PySocketSock_send, METH_VARARGS,
1458 send_doc},
1459 {"sendto", (PyCFunction)PySocketSock_sendto, METH_VARARGS,
1460 sendto_doc},
1461 {"setblocking", (PyCFunction)PySocketSock_setblocking, METH_VARARGS,
1462 setblocking_doc},
1463 {"setsockopt", (PyCFunction)PySocketSock_setsockopt, METH_VARARGS,
1464 setsockopt_doc},
1465 {"shutdown", (PyCFunction)PySocketSock_shutdown, METH_VARARGS,
1466 shutdown_doc},
1467 {NULL, NULL} /* sentinel */
1471 /* Deallocate a socket object in response to the last Py_DECREF().
1472 First close the file description. */
1474 static void
1475 PySocketSock_dealloc(PySocketSockObject *s)
1477 if (s->sock_fd != -1)
1478 (void) SOCKETCLOSE(s->sock_fd);
1479 PyObject_Del(s);
1483 /* Return a socket object's named attribute. */
1485 static PyObject *
1486 PySocketSock_getattr(PySocketSockObject *s, char *name)
1488 return Py_FindMethod(PySocketSock_methods, (PyObject *) s, name);
1492 static PyObject *
1493 PySocketSock_repr(PySocketSockObject *s)
1495 char buf[512];
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");
1503 return NULL;
1505 #endif
1506 sprintf(buf,
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 */
1518 "socket",
1519 sizeof(PySocketSockObject),
1521 (destructor)PySocketSock_dealloc, /*tp_dealloc*/
1522 0, /*tp_print*/
1523 (getattrfunc)PySocketSock_getattr, /*tp_getattr*/
1524 0, /*tp_setattr*/
1525 0, /*tp_compare*/
1526 (reprfunc)PySocketSock_repr, /*tp_repr*/
1527 0, /*tp_as_number*/
1528 0, /*tp_as_sequence*/
1529 0, /*tp_as_mapping*/
1533 /* Python interface to gethostname(). */
1535 /*ARGSUSED*/
1536 static PyObject *
1537 PySocket_gethostname(PyObject *self, PyObject *args)
1539 char buf[1024];
1540 int res;
1541 if (!PyArg_ParseTuple(args, ":gethostname"))
1542 return NULL;
1543 Py_BEGIN_ALLOW_THREADS
1544 res = gethostname(buf, (int) sizeof buf - 1);
1545 Py_END_ALLOW_THREADS
1546 if (res < 0)
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). */
1560 /*ARGSUSED*/
1561 static PyObject *
1562 PySocket_gethostbyname(PyObject *self, PyObject *args)
1564 char *name;
1565 struct sockaddr_in addrbuf;
1566 if (!PyArg_ParseTuple(args, "s:gethostbyname", &name))
1567 return NULL;
1568 if (setipaddr(name, &addrbuf) < 0)
1569 return NULL;
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 */
1581 static PyObject *
1582 gethost_common(struct hostent *h, struct sockaddr_in *addr)
1584 char **pch;
1585 PyObject *rtn_tuple = (PyObject *)NULL;
1586 PyObject *name_list = (PyObject *)NULL;
1587 PyObject *addr_list = (PyObject *)NULL;
1588 PyObject *tmp;
1589 if (h == NULL) {
1590 #ifdef HAVE_HSTRERROR
1591 /* Let's get real error message to return */
1592 extern int h_errno;
1593 PyErr_SetString(PySocket_Error, (char *)hstrerror(h_errno));
1594 #else
1595 PyErr_SetString(PySocket_Error, "host not found");
1596 #endif
1597 return NULL;
1599 if ((name_list = PyList_New(0)) == NULL)
1600 goto err;
1601 if ((addr_list = PyList_New(0)) == NULL)
1602 goto err;
1603 for (pch = h->h_aliases; *pch != NULL; pch++) {
1604 int status;
1605 tmp = PyString_FromString(*pch);
1606 if (tmp == NULL)
1607 goto err;
1608 status = PyList_Append(name_list, tmp);
1609 Py_DECREF(tmp);
1610 if (status)
1611 goto err;
1613 for (pch = h->h_addr_list; *pch != NULL; pch++) {
1614 int status;
1615 memcpy((char *) &addr->sin_addr, *pch, h->h_length);
1616 tmp = makeipaddr(addr);
1617 if (tmp == NULL)
1618 goto err;
1619 status = PyList_Append(addr_list, tmp);
1620 Py_DECREF(tmp);
1621 if (status)
1622 goto err;
1624 rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list);
1625 err:
1626 Py_XDECREF(name_list);
1627 Py_XDECREF(addr_list);
1628 return rtn_tuple;
1632 /* Python interface to gethostbyname_ex(name). */
1634 /*ARGSUSED*/
1635 static PyObject *
1636 PySocket_gethostbyname_ex(PyObject *self, PyObject *args)
1638 char *name;
1639 struct hostent *h;
1640 struct sockaddr_in addr;
1641 PyObject *ret;
1642 #ifdef HAVE_GETHOSTBYNAME_R
1643 struct hostent hp_allocated;
1644 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
1645 struct hostent_data data;
1646 #else
1647 char buf[16384];
1648 int buf_len = (sizeof buf) - 1;
1649 int errnop;
1650 #endif
1651 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
1652 int result;
1653 #endif
1654 #endif /* HAVE_GETHOSTBYNAME_R */
1655 if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name))
1656 return NULL;
1657 if (setipaddr(name, &addr) < 0)
1658 return NULL;
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;
1669 #endif
1670 #else /* not HAVE_GETHOSTBYNAME_R */
1671 #ifdef USE_GETHOSTBYNAME_LOCK
1672 PyThread_acquire_lock(gethostbyname_lock, 1);
1673 #endif
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);
1680 #endif
1681 return ret;
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). */
1693 /*ARGSUSED*/
1694 static PyObject *
1695 PySocket_gethostbyaddr(PyObject *self, PyObject *args)
1697 struct sockaddr_in addr;
1698 char *ip_num;
1699 struct hostent *h;
1700 PyObject *ret;
1701 #ifdef HAVE_GETHOSTBYNAME_R
1702 struct hostent hp_allocated;
1703 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
1704 struct hostent_data data;
1705 #else
1706 char buf[16384];
1707 int buf_len = (sizeof buf) - 1;
1708 int errnop;
1709 #endif
1710 #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
1711 int result;
1712 #endif
1713 #endif /* HAVE_GETHOSTBYNAME_R */
1715 if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num))
1716 return NULL;
1717 if (setipaddr(ip_num, &addr) < 0)
1718 return NULL;
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,
1725 &h, &errnop);
1726 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
1727 h = gethostbyaddr_r((char *)&addr.sin_addr,
1728 sizeof(addr.sin_addr),
1729 AF_INET,
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;
1737 #endif
1738 #else /* not HAVE_GETHOSTBYNAME_R */
1739 #ifdef USE_GETHOSTBYNAME_LOCK
1740 PyThread_acquire_lock(gethostbyname_lock, 1);
1741 #endif
1742 h = gethostbyaddr((char *)&addr.sin_addr,
1743 sizeof(addr.sin_addr),
1744 AF_INET);
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);
1750 #endif
1751 return ret;
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). */
1765 /*ARGSUSED*/
1766 static PyObject *
1767 PySocket_getservbyname(PyObject *self, PyObject *args)
1769 char *name, *proto;
1770 struct servent *sp;
1771 if (!PyArg_ParseTuple(args, "ss:getservbyname", &name, &proto))
1772 return NULL;
1773 Py_BEGIN_ALLOW_THREADS
1774 sp = getservbyname(name, proto);
1775 Py_END_ALLOW_THREADS
1776 if (sp == NULL) {
1777 PyErr_SetString(PySocket_Error, "service/proto not found");
1778 return NULL;
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). */
1794 /*ARGSUSED*/
1795 static PyObject *
1796 PySocket_getprotobyname(PyObject *self, PyObject *args)
1798 char *name;
1799 struct protoent *sp;
1800 #ifdef __BEOS__
1801 /* Not available in BeOS yet. - [cjh] */
1802 PyErr_SetString( PySocket_Error, "getprotobyname not supported" );
1803 return NULL;
1804 #else
1805 if (!PyArg_ParseTuple(args, "s:getprotobyname", &name))
1806 return NULL;
1807 Py_BEGIN_ALLOW_THREADS
1808 sp = getprotobyname(name);
1809 Py_END_ALLOW_THREADS
1810 if (sp == NULL) {
1811 PyErr_SetString(PySocket_Error, "protocol not found");
1812 return NULL;
1814 return PyInt_FromLong((long) sp->p_proto);
1815 #endif
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. */
1828 /*ARGSUSED*/
1829 static PyObject *
1830 PySocket_socket(PyObject *self, PyObject *args)
1832 PySocketSockObject *s;
1833 SOCKET_T fd;
1834 int family, type, proto = 0;
1835 if (!PyArg_ParseTuple(args, "ii|i:socket", &family, &type, &proto))
1836 return NULL;
1837 Py_BEGIN_ALLOW_THREADS
1838 fd = socket(family, type, proto);
1839 Py_END_ALLOW_THREADS
1840 #ifdef MS_WINDOWS
1841 if (fd == INVALID_SOCKET)
1842 #else
1843 if (fd < 0)
1844 #endif
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! */
1849 if (s == NULL)
1850 (void) SOCKETCLOSE(fd);
1851 /* From now on, ignore SIGPIPE and let the error checking
1852 do the work. */
1853 #ifdef SIGPIPE
1854 (void) signal(SIGPIPE, SIG_IGN);
1855 #endif
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.";
1869 #ifndef NO_DUP
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(). */
1874 /*ARGSUSED*/
1875 static PyObject *
1876 PySocket_fromfd(PyObject *self, PyObject *args)
1878 PySocketSockObject *s;
1879 SOCKET_T fd;
1880 int family, type, proto = 0;
1881 if (!PyArg_ParseTuple(args, "iii|i:fromfd",
1882 &fd, &family, &type, &proto))
1883 return NULL;
1884 /* Dup the fd so it and the socket can be closed independently */
1885 fd = dup(fd);
1886 if (fd < 0)
1887 return PySocket_Err();
1888 s = PySocketSock_New(fd, family, type, proto);
1889 /* From now on, ignore SIGPIPE and let the error checking
1890 do the work. */
1891 #ifdef SIGPIPE
1892 (void) signal(SIGPIPE, SIG_IGN);
1893 #endif
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().";
1903 #endif /* NO_DUP */
1906 static PyObject *
1907 PySocket_ntohs(PyObject *self, PyObject *args)
1909 int x1, x2;
1911 if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) {
1912 return NULL;
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.";
1924 static PyObject *
1925 PySocket_ntohl(PyObject *self, PyObject *args)
1927 int x1, x2;
1929 if (!PyArg_ParseTuple(args, "i:ntohl", &x1)) {
1930 return NULL;
1932 x2 = 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.";
1942 static PyObject *
1943 PySocket_htons(PyObject *self, PyObject *args)
1945 int x1, x2;
1947 if (!PyArg_ParseTuple(args, "i:htons", &x1)) {
1948 return NULL;
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.";
1960 static PyObject *
1961 PySocket_htonl(PyObject *self, PyObject *args)
1963 int x1, x2;
1965 if (!PyArg_ParseTuple(args, "i:htonl", &x1)) {
1966 return NULL;
1968 x2 = 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.";
1990 static PyObject*
1991 PySocket_inet_aton(PyObject *self, PyObject *args)
1993 #ifndef INADDR_NONE
1994 #define INADDR_NONE (-1)
1995 #endif
1997 /* Have to use inet_addr() instead */
1998 char *ip_addr;
1999 long packed_addr;
2001 if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr)) {
2002 return NULL;
2004 #ifdef USE_GUSI1
2005 packed_addr = (long)inet_addr(ip_addr).s_addr;
2006 #else
2007 packed_addr = inet_addr(ip_addr);
2008 #endif
2010 if (packed_addr == INADDR_NONE) { /* invalid address */
2011 PyErr_SetString(PySocket_Error,
2012 "illegal IP address string passed to inet_aton");
2013 return NULL;
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";
2025 static PyObject*
2026 PySocket_inet_ntoa(PyObject *self, PyObject *args)
2028 char *packed_str;
2029 int addr_len;
2030 struct in_addr packed_addr;
2032 if (!PyArg_ParseTuple(args, "s#:inet_ntoa", &packed_str, &addr_len)) {
2033 return NULL;
2036 if (addr_len != sizeof(packed_addr)) {
2037 PyErr_SetString(PySocket_Error,
2038 "packed IP wrong length for inet_ntoa");
2039 return NULL;
2042 memcpy(&packed_addr, packed_str, addr_len);
2044 return PyString_FromString(inet_ntoa(packed_addr));
2048 #ifdef USE_SSL
2050 /* This is a C function to be called for new object initialization */
2051 static SSLObject *
2052 newSSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file)
2054 SSLObject *self;
2056 self = PyObject_New(SSLObject, &SSL_Type); /* Create new object */
2057 if (self == NULL){
2058 PyErr_SetObject(SSLErrorObject,
2059 PyString_FromString("newSSLObject error"));
2060 return NULL;
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"));
2070 PyObject_Del(self);
2071 return NULL;
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"));
2079 PyObject_Del(self);
2080 return NULL;
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"));
2091 PyObject_Del(self);
2092 return NULL;
2095 if (SSL_CTX_use_certificate_chain_file(self->ctx,
2096 cert_file) < 1)
2098 PyErr_SetObject(SSLErrorObject,
2099 PyString_FromString(
2100 "SSL_CTX_use_certificate_chain_file error"));
2101 PyObject_Del(self);
2102 return NULL;
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"));
2116 PyObject_Del(self);
2117 return NULL;
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),
2123 self->server, 256);
2124 X509_NAME_oneline(X509_get_issuer_name(self->server_cert),
2125 self->issuer, 256);
2127 self->x_attr = NULL;
2128 self->Socket = Sock;
2129 Py_INCREF(self->Socket);
2130 return self;
2133 /* This is the Python function called for new object initialization */
2134 static PyObject *
2135 PySocket_ssl(PyObject *self, PyObject *args)
2137 SSLObject *rv;
2138 PySocketSockObject *Sock;
2139 char *key_file;
2140 char *cert_file;
2142 if (!PyArg_ParseTuple(args, "O!zz:ssl",
2143 &PySocketSock_Type, (PyObject*)&Sock,
2144 &key_file, &cert_file) )
2145 return NULL;
2147 rv = newSSLObject(Sock, key_file, cert_file);
2148 if ( rv == NULL )
2149 return NULL;
2150 return (PyObject *)rv;
2153 static char ssl_doc[] =
2154 "ssl(socket, keyfile, certfile) -> sslobject";
2156 static PyObject *
2157 SSL_server(SSLObject *self, PyObject *args)
2159 return PyString_FromString(self->server);
2162 static PyObject *
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 },
2176 { NULL, NULL}
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);
2187 PyObject_Del(self);
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)
2197 0, /*ob_size*/
2198 "SSL", /*tp_name*/
2199 sizeof(SSLObject), /*tp_basicsize*/
2200 0, /*tp_itemsize*/
2201 /* methods */
2202 (destructor)SSL_dealloc, /*tp_dealloc*/
2203 0, /*tp_print*/
2204 (getattrfunc)SSL_getattr, /*tp_getattr*/
2205 0, /*tp_setattr*/
2206 0, /*tp_compare*/
2207 0, /*tp_repr*/
2208 0, /*tp_as_number*/
2209 0, /*tp_as_sequence*/
2210 0, /*tp_as_mapping*/
2211 0, /*tp_hash*/
2216 static PyObject *SSL_SSLwrite(SSLObject *self, PyObject *args)
2218 char *data;
2219 size_t len;
2221 if (!PyArg_ParseTuple(args, "s#:write", &data, &len))
2222 return NULL;
2224 len = SSL_write(self->ssl, data, len);
2225 return PyInt_FromLong((long)len);
2228 static PyObject *SSL_SSLread(SSLObject *self, PyObject *args)
2230 PyObject *buf;
2231 int count = 0;
2232 int len = 1024;
2233 int res;
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);
2243 switch (res) {
2244 case SSL_ERROR_NONE:
2245 assert(count > 0);
2246 break;
2247 case SSL_ERROR_ZERO_RETURN: /* normal EOF */
2248 assert(count == 0);
2249 break;
2250 default:
2251 return PyErr_SetFromErrno(SSLErrorObject);
2254 fflush(stderr);
2256 if (count < 0) {
2257 Py_DECREF(buf);
2258 return PyErr_SetFromErrno(SSLErrorObject);
2261 if (count != len && _PyString_Resize(&buf, count) < 0)
2262 return NULL;
2263 return buf;
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},
2286 #ifndef NO_DUP
2287 {"fromfd", PySocket_fromfd,
2288 METH_VARARGS, fromfd_doc},
2289 #endif
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},
2302 #ifdef USE_SSL
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...
2314 static void
2315 insint(PyObject *d, char *name, int value)
2317 PyObject *v = PyInt_FromLong((long) value);
2318 if (!v || PyDict_SetItemString(d, name, v))
2319 PyErr_Clear();
2321 Py_XDECREF(v);
2325 #ifdef MS_WINDOWS
2327 /* Additional initialization and cleanup for NT/Windows */
2329 static void
2330 NTcleanup(void)
2332 WSACleanup();
2335 static int
2336 NTinit(void)
2338 WSADATA WSAData;
2339 int ret;
2340 char buf[100];
2341 ret = WSAStartup(0x0101, &WSAData);
2342 switch (ret) {
2343 case 0: /* no error */
2344 atexit(NTcleanup);
2345 return 1;
2346 case WSASYSNOTREADY:
2347 PyErr_SetString(PyExc_ImportError,
2348 "WSAStartup failed: network not ready");
2349 break;
2350 case WSAVERNOTSUPPORTED:
2351 case WSAEINVAL:
2352 PyErr_SetString(PyExc_ImportError,
2353 "WSAStartup failed: requested version not supported");
2354 break;
2355 default:
2356 sprintf(buf, "WSAStartup failed: error code %d", ret);
2357 PyErr_SetString(PyExc_ImportError, buf);
2358 break;
2360 return 0;
2363 #endif /* MS_WINDOWS */
2365 #if defined(PYOS_OS2)
2367 /* Additional initialization and cleanup for OS/2 */
2369 static void
2370 OS2cleanup(void)
2372 /* No cleanup is necessary for OS/2 Sockets */
2375 static int
2376 OS2init(void)
2378 char reason[64];
2379 int rc = sock_init();
2381 if (rc == 0) {
2382 atexit(OS2cleanup);
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
2397 * defined.
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\
2420 Methods:\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!)";
2444 DL_EXPORT(void)
2445 init_socket(void)
2447 PyObject *m, *d;
2448 #ifdef MS_WINDOWS
2449 if (!NTinit())
2450 return;
2451 #else
2452 #if defined(__TOS_OS2__)
2453 if (!OS2init())
2454 return;
2455 #endif /* __TOS_OS2__ */
2456 #endif /* MS_WINDOWS */
2457 #ifdef USE_SSL
2458 SSL_Type.ob_type = &PyType_Type;
2459 #endif
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)
2464 return;
2465 #ifdef USE_SSL
2466 SSL_load_error_strings();
2467 SSLeay_add_ssl_algorithms();
2468 SSLErrorObject = PyErr_NewException("socket.sslerror", NULL, NULL);
2469 if (SSLErrorObject == NULL)
2470 return;
2471 PyDict_SetItemString(d, "sslerror", SSLErrorObject);
2472 Py_INCREF(&SSL_Type);
2473 if (PyDict_SetItemString(d, "SSLType",
2474 (PyObject *)&SSL_Type) != 0)
2475 return;
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)
2483 return;
2485 /* Address families (we only support AF_INET and AF_UNIX) */
2486 #ifdef AF_UNSPEC
2487 insint(d, "AF_UNSPEC", AF_UNSPEC);
2488 #endif
2489 insint(d, "AF_INET", AF_INET);
2490 #ifdef AF_UNIX
2491 insint(d, "AF_UNIX", AF_UNIX);
2492 #endif /* AF_UNIX */
2493 #ifdef AF_AX25
2494 insint(d, "AF_AX25", AF_AX25); /* Amateur Radio AX.25 */
2495 #endif
2496 #ifdef AF_IPX
2497 insint(d, "AF_IPX", AF_IPX); /* Novell IPX */
2498 #endif
2499 #ifdef AF_APPLETALK
2500 insint(d, "AF_APPLETALK", AF_APPLETALK); /* Appletalk DDP */
2501 #endif
2502 #ifdef AF_NETROM
2503 insint(d, "AF_NETROM", AF_NETROM); /* Amateur radio NetROM */
2504 #endif
2505 #ifdef AF_BRIDGE
2506 insint(d, "AF_BRIDGE", AF_BRIDGE); /* Multiprotocol bridge */
2507 #endif
2508 #ifdef AF_AAL5
2509 insint(d, "AF_AAL5", AF_AAL5); /* Reserved for Werner's ATM */
2510 #endif
2511 #ifdef AF_X25
2512 insint(d, "AF_X25", AF_X25); /* Reserved for X.25 project */
2513 #endif
2514 #ifdef AF_INET6
2515 insint(d, "AF_INET6", AF_INET6); /* IP version 6 */
2516 #endif
2517 #ifdef AF_ROSE
2518 insint(d, "AF_ROSE", AF_ROSE); /* Amateur Radio X.25 PLP */
2519 #endif
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);
2530 #endif
2532 /* Socket types */
2533 insint(d, "SOCK_STREAM", SOCK_STREAM);
2534 insint(d, "SOCK_DGRAM", SOCK_DGRAM);
2535 #ifndef __BEOS__
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);
2540 #endif
2542 #ifdef SO_DEBUG
2543 insint(d, "SO_DEBUG", SO_DEBUG);
2544 #endif
2545 #ifdef SO_ACCEPTCONN
2546 insint(d, "SO_ACCEPTCONN", SO_ACCEPTCONN);
2547 #endif
2548 #ifdef SO_REUSEADDR
2549 insint(d, "SO_REUSEADDR", SO_REUSEADDR);
2550 #endif
2551 #ifdef SO_KEEPALIVE
2552 insint(d, "SO_KEEPALIVE", SO_KEEPALIVE);
2553 #endif
2554 #ifdef SO_DONTROUTE
2555 insint(d, "SO_DONTROUTE", SO_DONTROUTE);
2556 #endif
2557 #ifdef SO_BROADCAST
2558 insint(d, "SO_BROADCAST", SO_BROADCAST);
2559 #endif
2560 #ifdef SO_USELOOPBACK
2561 insint(d, "SO_USELOOPBACK", SO_USELOOPBACK);
2562 #endif
2563 #ifdef SO_LINGER
2564 insint(d, "SO_LINGER", SO_LINGER);
2565 #endif
2566 #ifdef SO_OOBINLINE
2567 insint(d, "SO_OOBINLINE", SO_OOBINLINE);
2568 #endif
2569 #ifdef SO_REUSEPORT
2570 insint(d, "SO_REUSEPORT", SO_REUSEPORT);
2571 #endif
2572 #ifdef SO_SNDBUF
2573 insint(d, "SO_SNDBUF", SO_SNDBUF);
2574 #endif
2575 #ifdef SO_RCVBUF
2576 insint(d, "SO_RCVBUF", SO_RCVBUF);
2577 #endif
2578 #ifdef SO_SNDLOWAT
2579 insint(d, "SO_SNDLOWAT", SO_SNDLOWAT);
2580 #endif
2581 #ifdef SO_RCVLOWAT
2582 insint(d, "SO_RCVLOWAT", SO_RCVLOWAT);
2583 #endif
2584 #ifdef SO_SNDTIMEO
2585 insint(d, "SO_SNDTIMEO", SO_SNDTIMEO);
2586 #endif
2587 #ifdef SO_RCVTIMEO
2588 insint(d, "SO_RCVTIMEO", SO_RCVTIMEO);
2589 #endif
2590 #ifdef SO_ERROR
2591 insint(d, "SO_ERROR", SO_ERROR);
2592 #endif
2593 #ifdef SO_TYPE
2594 insint(d, "SO_TYPE", SO_TYPE);
2595 #endif
2597 /* Maximum number of connections for "listen" */
2598 #ifdef SOMAXCONN
2599 insint(d, "SOMAXCONN", SOMAXCONN);
2600 #else
2601 insint(d, "SOMAXCONN", 5); /* Common value */
2602 #endif
2604 /* Flags for send, recv */
2605 #ifdef MSG_OOB
2606 insint(d, "MSG_OOB", MSG_OOB);
2607 #endif
2608 #ifdef MSG_PEEK
2609 insint(d, "MSG_PEEK", MSG_PEEK);
2610 #endif
2611 #ifdef MSG_DONTROUTE
2612 insint(d, "MSG_DONTROUTE", MSG_DONTROUTE);
2613 #endif
2614 #ifdef MSG_DONTWAIT
2615 insint(d, "MSG_DONTWAIT", MSG_DONTWAIT);
2616 #endif
2617 #ifdef MSG_EOR
2618 insint(d, "MSG_EOR", MSG_EOR);
2619 #endif
2620 #ifdef MSG_TRUNC
2621 insint(d, "MSG_TRUNC", MSG_TRUNC);
2622 #endif
2623 #ifdef MSG_CTRUNC
2624 insint(d, "MSG_CTRUNC", MSG_CTRUNC);
2625 #endif
2626 #ifdef MSG_WAITALL
2627 insint(d, "MSG_WAITALL", MSG_WAITALL);
2628 #endif
2629 #ifdef MSG_BTAG
2630 insint(d, "MSG_BTAG", MSG_BTAG);
2631 #endif
2632 #ifdef MSG_ETAG
2633 insint(d, "MSG_ETAG", MSG_ETAG);
2634 #endif
2636 /* Protocol level and numbers, usable for [gs]etsockopt */
2637 #ifdef SOL_SOCKET
2638 insint(d, "SOL_SOCKET", SOL_SOCKET);
2639 #endif
2640 #ifdef SOL_IP
2641 insint(d, "SOL_IP", SOL_IP);
2642 #else
2643 insint(d, "SOL_IP", 0);
2644 #endif
2645 #ifdef SOL_IPX
2646 insint(d, "SOL_IPX", SOL_IPX);
2647 #endif
2648 #ifdef SOL_AX25
2649 insint(d, "SOL_AX25", SOL_AX25);
2650 #endif
2651 #ifdef SOL_ATALK
2652 insint(d, "SOL_ATALK", SOL_ATALK);
2653 #endif
2654 #ifdef SOL_NETROM
2655 insint(d, "SOL_NETROM", SOL_NETROM);
2656 #endif
2657 #ifdef SOL_ROSE
2658 insint(d, "SOL_ROSE", SOL_ROSE);
2659 #endif
2660 #ifdef SOL_TCP
2661 insint(d, "SOL_TCP", SOL_TCP);
2662 #else
2663 insint(d, "SOL_TCP", 6);
2664 #endif
2665 #ifdef SOL_UDP
2666 insint(d, "SOL_UDP", SOL_UDP);
2667 #else
2668 insint(d, "SOL_UDP", 17);
2669 #endif
2670 #ifdef IPPROTO_IP
2671 insint(d, "IPPROTO_IP", IPPROTO_IP);
2672 #else
2673 insint(d, "IPPROTO_IP", 0);
2674 #endif
2675 #ifdef IPPROTO_ICMP
2676 insint(d, "IPPROTO_ICMP", IPPROTO_ICMP);
2677 #else
2678 insint(d, "IPPROTO_ICMP", 1);
2679 #endif
2680 #ifdef IPPROTO_IGMP
2681 insint(d, "IPPROTO_IGMP", IPPROTO_IGMP);
2682 #endif
2683 #ifdef IPPROTO_GGP
2684 insint(d, "IPPROTO_GGP", IPPROTO_GGP);
2685 #endif
2686 #ifdef IPPROTO_TCP
2687 insint(d, "IPPROTO_TCP", IPPROTO_TCP);
2688 #else
2689 insint(d, "IPPROTO_TCP", 6);
2690 #endif
2691 #ifdef IPPROTO_EGP
2692 insint(d, "IPPROTO_EGP", IPPROTO_EGP);
2693 #endif
2694 #ifdef IPPROTO_PUP
2695 insint(d, "IPPROTO_PUP", IPPROTO_PUP);
2696 #endif
2697 #ifdef IPPROTO_UDP
2698 insint(d, "IPPROTO_UDP", IPPROTO_UDP);
2699 #else
2700 insint(d, "IPPROTO_UDP", 17);
2701 #endif
2702 #ifdef IPPROTO_IDP
2703 insint(d, "IPPROTO_IDP", IPPROTO_IDP);
2704 #endif
2705 #ifdef IPPROTO_HELLO
2706 insint(d, "IPPROTO_HELLO", IPPROTO_HELLO);
2707 #endif
2708 #ifdef IPPROTO_ND
2709 insint(d, "IPPROTO_ND", IPPROTO_ND);
2710 #endif
2711 #ifdef IPPROTO_TP
2712 insint(d, "IPPROTO_TP", IPPROTO_TP);
2713 #endif
2714 #ifdef IPPROTO_XTP
2715 insint(d, "IPPROTO_XTP", IPPROTO_XTP);
2716 #endif
2717 #ifdef IPPROTO_EON
2718 insint(d, "IPPROTO_EON", IPPROTO_EON);
2719 #endif
2720 #ifdef IPPROTO_BIP
2721 insint(d, "IPPROTO_BIP", IPPROTO_BIP);
2722 #endif
2723 /**/
2724 #ifdef IPPROTO_RAW
2725 insint(d, "IPPROTO_RAW", IPPROTO_RAW);
2726 #else
2727 insint(d, "IPPROTO_RAW", 255);
2728 #endif
2729 #ifdef IPPROTO_MAX
2730 insint(d, "IPPROTO_MAX", IPPROTO_MAX);
2731 #endif
2733 /* Some port configuration */
2734 #ifdef IPPORT_RESERVED
2735 insint(d, "IPPORT_RESERVED", IPPORT_RESERVED);
2736 #else
2737 insint(d, "IPPORT_RESERVED", 1024);
2738 #endif
2739 #ifdef IPPORT_USERRESERVED
2740 insint(d, "IPPORT_USERRESERVED", IPPORT_USERRESERVED);
2741 #else
2742 insint(d, "IPPORT_USERRESERVED", 5000);
2743 #endif
2745 /* Some reserved IP v.4 addresses */
2746 #ifdef INADDR_ANY
2747 insint(d, "INADDR_ANY", INADDR_ANY);
2748 #else
2749 insint(d, "INADDR_ANY", 0x00000000);
2750 #endif
2751 #ifdef INADDR_BROADCAST
2752 insint(d, "INADDR_BROADCAST", INADDR_BROADCAST);
2753 #else
2754 insint(d, "INADDR_BROADCAST", 0xffffffff);
2755 #endif
2756 #ifdef INADDR_LOOPBACK
2757 insint(d, "INADDR_LOOPBACK", INADDR_LOOPBACK);
2758 #else
2759 insint(d, "INADDR_LOOPBACK", 0x7F000001);
2760 #endif
2761 #ifdef INADDR_UNSPEC_GROUP
2762 insint(d, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
2763 #else
2764 insint(d, "INADDR_UNSPEC_GROUP", 0xe0000000);
2765 #endif
2766 #ifdef INADDR_ALLHOSTS_GROUP
2767 insint(d, "INADDR_ALLHOSTS_GROUP", INADDR_ALLHOSTS_GROUP);
2768 #else
2769 insint(d, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
2770 #endif
2771 #ifdef INADDR_MAX_LOCAL_GROUP
2772 insint(d, "INADDR_MAX_LOCAL_GROUP", INADDR_MAX_LOCAL_GROUP);
2773 #else
2774 insint(d, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
2775 #endif
2776 #ifdef INADDR_NONE
2777 insint(d, "INADDR_NONE", INADDR_NONE);
2778 #else
2779 insint(d, "INADDR_NONE", 0xffffffff);
2780 #endif
2782 /* IP [gs]etsockopt options */
2783 #ifdef IP_OPTIONS
2784 insint(d, "IP_OPTIONS", IP_OPTIONS);
2785 #endif
2786 #ifdef IP_HDRINCL
2787 insint(d, "IP_HDRINCL", IP_HDRINCL);
2788 #endif
2789 #ifdef IP_TOS
2790 insint(d, "IP_TOS", IP_TOS);
2791 #endif
2792 #ifdef IP_TTL
2793 insint(d, "IP_TTL", IP_TTL);
2794 #endif
2795 #ifdef IP_RECVOPTS
2796 insint(d, "IP_RECVOPTS", IP_RECVOPTS);
2797 #endif
2798 #ifdef IP_RECVRETOPTS
2799 insint(d, "IP_RECVRETOPTS", IP_RECVRETOPTS);
2800 #endif
2801 #ifdef IP_RECVDSTADDR
2802 insint(d, "IP_RECVDSTADDR", IP_RECVDSTADDR);
2803 #endif
2804 #ifdef IP_RETOPTS
2805 insint(d, "IP_RETOPTS", IP_RETOPTS);
2806 #endif
2807 #ifdef IP_MULTICAST_IF
2808 insint(d, "IP_MULTICAST_IF", IP_MULTICAST_IF);
2809 #endif
2810 #ifdef IP_MULTICAST_TTL
2811 insint(d, "IP_MULTICAST_TTL", IP_MULTICAST_TTL);
2812 #endif
2813 #ifdef IP_MULTICAST_LOOP
2814 insint(d, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
2815 #endif
2816 #ifdef IP_ADD_MEMBERSHIP
2817 insint(d, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
2818 #endif
2819 #ifdef IP_DROP_MEMBERSHIP
2820 insint(d, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
2821 #endif
2822 #ifdef IP_DEFAULT_MULTICAST_TTL
2823 insint(d, "IP_DEFAULT_MULTICAST_TTL", IP_DEFAULT_MULTICAST_TTL);
2824 #endif
2825 #ifdef IP_DEFAULT_MULTICAST_LOOP
2826 insint(d, "IP_DEFAULT_MULTICAST_LOOP", IP_DEFAULT_MULTICAST_LOOP);
2827 #endif
2828 #ifdef IP_MAX_MEMBERSHIPS
2829 insint(d, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS);
2830 #endif
2832 /* TCP options */
2833 #ifdef TCP_NODELAY
2834 insint(d, "TCP_NODELAY", TCP_NODELAY);
2835 #endif
2836 #ifdef TCP_MAXSEG
2837 insint(d, "TCP_MAXSEG", TCP_MAXSEG);
2838 #endif
2840 /* IPX options */
2841 #ifdef IPX_TYPE
2842 insint(d, "IPX_TYPE", IPX_TYPE);
2843 #endif
2845 /* Initialize gethostbyname lock */
2846 #ifdef USE_GETHOSTBYNAME_LOCK
2847 gethostbyname_lock = PyThread_allocate_lock();
2848 #endif