Fix an amazing number of typos & malformed sentences reported by Detlef
[python/dscho.git] / Modules / socketmodule.c
blobab0014c79c7bb8181ffa6bcd3a9f97e4a8fb6b86
1 /***********************************************************
2 Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
3 The Netherlands.
5 All Rights Reserved
7 Permission to use, copy, modify, and distribute this software and its
8 documentation for any purpose and without fee is hereby granted,
9 provided that the above copyright notice appear in all copies and that
10 both that copyright notice and this permission notice appear in
11 supporting documentation, and that the names of Stichting Mathematisch
12 Centrum or CWI or Corporation for National Research Initiatives or
13 CNRI not be used in advertising or publicity pertaining to
14 distribution of the software without specific, written prior
15 permission.
17 While CWI is the initial source for this software, a modified version
18 is made available by the Corporation for National Research Initiatives
19 (CNRI) at the Internet address ftp://ftp.python.org.
21 STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
22 REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
23 MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
24 CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
25 DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
26 PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
27 TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
28 PERFORMANCE OF THIS SOFTWARE.
30 ******************************************************************/
32 /* Socket module */
35 This module provides an interface to Berkeley socket IPC.
37 Limitations:
39 - only AF_INET and AF_UNIX address families are supported
40 - no read/write operations (use send/recv or makefile instead)
41 - additional restrictions apply on Windows
43 Module interface:
45 - socket.error: exception raised for socket specific errors
46 - socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')
47 - socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])
48 - socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com')
49 - socket.getprotobyname(protocolname) --> protocol number
50 - socket.getservbyname(servicename, protocolname) --> port number
51 - socket.socket(family, type [, proto]) --> new socket object
52 - socket.ntohs(16 bit value) --> new int object
53 - socket.ntohl(32 bit value) --> new int object
54 - socket.htons(16 bit value) --> new int object
55 - socket.htonl(32 bit value) --> new int object
56 - socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
57 - an Internet socket address is a pair (hostname, port)
58 where hostname can be anything recognized by gethostbyname()
59 (including the dd.dd.dd.dd notation) and port is in host byte order
60 - where a hostname is returned, the dd.dd.dd.dd notation is used
61 - a UNIX domain socket address is a string specifying the pathname
63 Socket methods:
65 - s.accept() --> new socket object, sockaddr
66 - s.bind(sockaddr) --> None
67 - s.close() --> None
68 - s.connect(sockaddr) --> None
69 - s.connect_ex(sockaddr) --> 0 or errno (handy for e.g. async connect)
70 - s.fileno() --> file descriptor
71 - s.dup() --> same as socket.fromfd(os.dup(s.fileno(), ...)
72 - s.getpeername() --> sockaddr
73 - s.getsockname() --> sockaddr
74 - s.getsockopt(level, optname[, buflen]) --> int or string
75 - s.listen(backlog) --> None
76 - s.makefile([mode[, bufsize]]) --> file object
77 - s.recv(buflen [,flags]) --> string
78 - s.recvfrom(buflen [,flags]) --> string, sockaddr
79 - s.send(string [,flags]) --> nbytes
80 - s.sendto(string, [flags,] sockaddr) --> nbytes
81 - s.setblocking(0 | 1) --> None
82 - s.setsockopt(level, optname, value) --> None
83 - s.shutdown(how) --> None
84 - repr(s) --> "<socket object, fd=%d, family=%d, type=%d, protocol=%d>"
88 #include "Python.h"
89 #if defined(WITH_THREAD) && !defined(HAVE_GETHOSTBYNAME_R) && !defined(MS_WINDOWS)
90 #include "pythread.h"
91 #endif
93 #ifdef HAVE_UNISTD_H
94 #include <unistd.h>
95 #endif
97 #if !defined(MS_WINDOWS) && !defined(PYOS_OS2) && !defined(__BEOS__)
98 extern int gethostname(); /* For Solaris, at least */
99 #endif
101 #if defined(PYCC_VACPP)
102 #include <types.h>
103 #include <io.h>
104 #include <sys/ioctl.h>
105 #include <utils.h>
106 #include <ctype.h>
107 #endif
109 #if defined(PYOS_OS2)
110 #define INCL_DOS
111 #define INCL_DOSERRORS
112 #define INCL_NOPMAPI
113 #include <os2.h>
114 #endif
116 #if defined(__BEOS__)
117 /* It's in the libs, but not the headers... - [cjh] */
118 int shutdown( int, int );
119 #endif
121 #include <sys/types.h>
122 #include "mytime.h"
124 #include <signal.h>
125 #ifndef MS_WINDOWS
126 #include <netdb.h>
127 #include <sys/socket.h>
128 #include <netinet/in.h>
129 #include <fcntl.h>
130 #else
131 #include <winsock.h>
132 #include <fcntl.h>
133 #endif
134 #ifdef HAVE_SYS_UN_H
135 #include <sys/un.h>
136 #else
137 #undef AF_UNIX
138 #endif
140 #ifndef O_NDELAY
141 #define O_NDELAY O_NONBLOCK /* For QNX only? */
142 #endif
144 #ifdef USE_GUSI
145 /* fdopen() isn't declared in stdio.h (sigh) */
146 #include <GUSI.h>
147 #endif
150 /* Here we have some hacks to choose between K&R or ANSI style function
151 definitions. For NT to build this as an extension module (ie, DLL)
152 it must be compiled by the C++ compiler, as it takes the address of
153 a static data item exported from the main Python DLL.
155 #if defined(MS_WINDOWS) || defined(__BEOS__)
156 /* BeOS suffers from the same socket dichotomy as Win32... - [cjh] */
157 /* seem to be a few differences in the API */
158 #define close closesocket
159 #define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */
160 #define FORCE_ANSI_FUNC_DEFS
161 #endif
163 #if defined(PYOS_OS2)
164 #define close soclose
165 #define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
166 #define FORCE_ANSI_FUNC_DEFS
167 #endif
169 #ifdef FORCE_ANSI_FUNC_DEFS
170 #define BUILD_FUNC_DEF_1( fnname, arg1type, arg1name ) \
171 fnname( arg1type arg1name )
173 #define BUILD_FUNC_DEF_2( fnname, arg1type, arg1name, arg2type, arg2name ) \
174 fnname( arg1type arg1name, arg2type arg2name )
176 #define BUILD_FUNC_DEF_3( fnname, arg1type, arg1name, arg2type, arg2name , arg3type, arg3name ) \
177 fnname( arg1type arg1name, arg2type arg2name, arg3type arg3name )
179 #define BUILD_FUNC_DEF_4( fnname, arg1type, arg1name, arg2type, arg2name , arg3type, arg3name, arg4type, arg4name ) \
180 fnname( arg1type arg1name, arg2type arg2name, arg3type arg3name, arg4type arg4name )
182 #else /* !FORCE_ANSI_FN_DEFS */
183 #define BUILD_FUNC_DEF_1( fnname, arg1type, arg1name ) \
184 fnname( arg1name ) \
185 arg1type arg1name;
187 #define BUILD_FUNC_DEF_2( fnname, arg1type, arg1name, arg2type, arg2name ) \
188 fnname( arg1name, arg2name ) \
189 arg1type arg1name; \
190 arg2type arg2name;
192 #define BUILD_FUNC_DEF_3( fnname, arg1type, arg1name, arg2type, arg2name, arg3type, arg3name ) \
193 fnname( arg1name, arg2name, arg3name ) \
194 arg1type arg1name; \
195 arg2type arg2name; \
196 arg3type arg3name;
198 #define BUILD_FUNC_DEF_4( fnname, arg1type, arg1name, arg2type, arg2name, arg3type, arg3name, arg4type, arg4name ) \
199 fnname( arg1name, arg2name, arg3name, arg4name ) \
200 arg1type arg1name; \
201 arg2type arg2name; \
202 arg3type arg3name; \
203 arg4type arg4name;
205 #endif /* !FORCE_ANSI_FN_DEFS */
207 /* Global variable holding the exception type for errors detected
208 by this module (but not argument type or memory errors, etc.). */
210 static PyObject *PySocket_Error;
213 /* Convenience function to raise an error according to errno
214 and return a NULL pointer from a function. */
216 static PyObject *
217 PySocket_Err()
219 #ifdef MS_WINDOWS
220 if (WSAGetLastError()) {
221 PyObject *v;
222 v = Py_BuildValue("(is)", WSAGetLastError(), "winsock error");
223 if (v != NULL) {
224 PyErr_SetObject(PySocket_Error, v);
225 Py_DECREF(v);
227 return NULL;
229 else
230 #endif
232 #if defined(PYOS_OS2)
233 if (sock_errno() != NO_ERROR) {
234 APIRET rc;
235 ULONG msglen;
236 char outbuf[100];
237 int myerrorcode = sock_errno();
239 /* Retrieve Socket-Related Error Message from MPTN.MSG File */
240 rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf),
241 myerrorcode - SOCBASEERR + 26, "mptn.msg", &msglen);
242 if (rc == NO_ERROR) {
243 PyObject *v;
245 outbuf[msglen] = '\0'; /* OS/2 Doesn't Guarantee a Terminator */
246 if (strlen(outbuf) > 0) { /* If Non-Empty Msg, Trim CRLF */
247 char *lastc = &outbuf[ strlen(outbuf)-1 ];
248 while (lastc > outbuf && isspace(*lastc))
249 *lastc-- = '\0'; /* Trim Trailing Whitespace (CRLF) */
251 v = Py_BuildValue("(is)", myerrorcode, outbuf);
252 if (v != NULL) {
253 PyErr_SetObject(PySocket_Error, v);
254 Py_DECREF(v);
256 return NULL;
259 #endif
261 return PyErr_SetFromErrno(PySocket_Error);
265 /* The object holding a socket. It holds some extra information,
266 like the address family, which is used to decode socket address
267 arguments properly. */
269 typedef struct {
270 PyObject_HEAD
271 int sock_fd; /* Socket file descriptor */
272 int sock_family; /* Address family, e.g., AF_INET */
273 int sock_type; /* Socket type, e.g., SOCK_STREAM */
274 int sock_proto; /* Protocol type, usually 0 */
275 union sock_addr {
276 struct sockaddr_in in;
277 #ifdef AF_UNIX
278 struct sockaddr_un un;
279 #endif
280 } sock_addr;
281 } PySocketSockObject;
284 /* A forward reference to the Socktype type object.
285 The Socktype variable contains pointers to various functions,
286 some of which call newsockobject(), which uses Socktype, so
287 there has to be a circular reference. */
289 staticforward PyTypeObject PySocketSock_Type;
292 /* Create a new socket object.
293 This just creates the object and initializes it.
294 If the creation fails, return NULL and set an exception (implicit
295 in NEWOBJ()). */
297 static PySocketSockObject *
298 BUILD_FUNC_DEF_4(PySocketSock_New,int,fd, int,family, int,type, int,proto)
300 PySocketSockObject *s;
301 PySocketSock_Type.ob_type = &PyType_Type;
302 s = PyObject_NEW(PySocketSockObject, &PySocketSock_Type);
303 if (s != NULL) {
304 s->sock_fd = fd;
305 s->sock_family = family;
306 s->sock_type = type;
307 s->sock_proto = proto;
309 return s;
313 /* Lock to allow python interpreter to continue, but only allow one
314 thread to be in gethostbyname */
315 #if defined(WITH_THREAD) && !defined(HAVE_GETHOSTBYNAME_R) && !defined(MS_WINDOWS)
316 PyThread_type_lock gethostbyname_lock;
317 #endif
320 /* Convert a string specifying a host name or one of a few symbolic
321 names to a numeric IP address. This usually calls gethostbyname()
322 to do the work; the names "" and "<broadcast>" are special.
323 Return the length (should always be 4 bytes), or negative if
324 an error occurred; then an exception is raised. */
326 static int
327 BUILD_FUNC_DEF_2(setipaddr, char*,name, struct sockaddr_in *,addr_ret)
329 struct hostent *hp;
330 int d1, d2, d3, d4;
331 char ch;
332 #ifdef HAVE_GETHOSTBYNAME_R
333 struct hostent hp_allocated;
334 char buf[1001];
335 int buf_len = (sizeof buf) - 1;
336 int errnop;
337 #endif /* HAVE_GETHOSTBYNAME_R */
339 memset((void *) addr_ret, '\0', sizeof(*addr_ret));
340 if (name[0] == '\0') {
341 addr_ret->sin_addr.s_addr = INADDR_ANY;
342 return 4;
344 if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
345 addr_ret->sin_addr.s_addr = INADDR_BROADCAST;
346 return 4;
348 if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 &&
349 0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 &&
350 0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) {
351 addr_ret->sin_addr.s_addr = htonl(
352 ((long) d1 << 24) | ((long) d2 << 16) |
353 ((long) d3 << 8) | ((long) d4 << 0));
354 return 4;
356 Py_BEGIN_ALLOW_THREADS
357 #ifdef HAVE_GETHOSTBYNAME_R
358 hp = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
359 #else /* not HAVE_GETHOSTBYNAME_R */
360 #if defined(WITH_THREAD) && !defined(MS_WINDOWS)
361 PyThread_acquire_lock(gethostbyname_lock,1);
362 #endif
363 hp = gethostbyname(name);
364 #if defined(WITH_THREAD) && !defined(MS_WINDOWS)
365 PyThread_release_lock(gethostbyname_lock);
366 #endif
367 #endif /* HAVE_GETHOSTBYNAME_R */
368 Py_END_ALLOW_THREADS
370 if (hp == NULL) {
371 #ifdef HAVE_HSTRERROR
372 /* Let's get real error message to return */
373 extern int h_errno;
374 PyErr_SetString(PySocket_Error, (char *)hstrerror(h_errno));
375 #else
376 PyErr_SetString(PySocket_Error, "host not found");
377 #endif
378 return -1;
380 memcpy((char *) &addr_ret->sin_addr, hp->h_addr, hp->h_length);
381 return hp->h_length;
385 /* Create a string object representing an IP address.
386 This is always a string of the form 'dd.dd.dd.dd' (with variable
387 size numbers). */
389 static PyObject *
390 BUILD_FUNC_DEF_1(makeipaddr, struct sockaddr_in *,addr)
392 long x = ntohl(addr->sin_addr.s_addr);
393 char buf[100];
394 sprintf(buf, "%d.%d.%d.%d",
395 (int) (x>>24) & 0xff, (int) (x>>16) & 0xff,
396 (int) (x>> 8) & 0xff, (int) (x>> 0) & 0xff);
397 return PyString_FromString(buf);
401 /* Create an object representing the given socket address,
402 suitable for passing it back to bind(), connect() etc.
403 The family field of the sockaddr structure is inspected
404 to determine what kind of address it really is. */
406 /*ARGSUSED*/
407 static PyObject *
408 BUILD_FUNC_DEF_2(makesockaddr,struct sockaddr *,addr, int,addrlen)
410 if (addrlen == 0) {
411 /* No address -- may be recvfrom() from known socket */
412 Py_INCREF(Py_None);
413 return Py_None;
416 #ifdef __BEOS__
417 /* XXX: BeOS version of accept() doesn't set family coreectly */
418 addr->sa_family = AF_INET;
419 #endif
421 switch (addr->sa_family) {
423 case AF_INET:
425 struct sockaddr_in *a = (struct sockaddr_in *) addr;
426 PyObject *addrobj = makeipaddr(a);
427 PyObject *ret = NULL;
428 if (addrobj) {
429 ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
430 Py_DECREF(addrobj);
432 return ret;
435 #ifdef AF_UNIX
436 case AF_UNIX:
438 struct sockaddr_un *a = (struct sockaddr_un *) addr;
439 return PyString_FromString(a->sun_path);
441 #endif /* AF_UNIX */
443 /* More cases here... */
445 default:
446 /* If we don't know the address family, don't raise an
447 exception -- return it as a tuple. */
448 return Py_BuildValue("is#",
449 addr->sa_family,
450 addr->sa_data,
451 sizeof(addr->sa_data));
457 /* Parse a socket address argument according to the socket object's
458 address family. Return 1 if the address was in the proper format,
459 0 of not. The address is returned through addr_ret, its length
460 through len_ret. */
462 static int
463 BUILD_FUNC_DEF_4(
464 getsockaddrarg,PySocketSockObject *,s, PyObject *,args, struct sockaddr **,addr_ret, int *,len_ret)
466 switch (s->sock_family) {
468 #ifdef AF_UNIX
469 case AF_UNIX:
471 struct sockaddr_un* addr;
472 char *path;
473 int len;
474 addr = (struct sockaddr_un* )&(s->sock_addr).un;
475 if (!PyArg_Parse(args, "t#", &path, &len))
476 return 0;
477 if (len > sizeof addr->sun_path) {
478 PyErr_SetString(PySocket_Error,
479 "AF_UNIX path too long");
480 return 0;
482 addr->sun_family = AF_UNIX;
483 memcpy(addr->sun_path, path, len);
484 addr->sun_path[len] = 0;
485 *addr_ret = (struct sockaddr *) addr;
486 *len_ret = len + sizeof(*addr) - sizeof(addr->sun_path);
487 return 1;
489 #endif /* AF_UNIX */
491 case AF_INET:
493 struct sockaddr_in* addr;
494 char *host;
495 int port;
496 addr=(struct sockaddr_in*)&(s->sock_addr).in;
497 if (!PyArg_Parse(args, "(si)", &host, &port))
498 return 0;
499 if (setipaddr(host, addr) < 0)
500 return 0;
501 addr->sin_family = AF_INET;
502 addr->sin_port = htons((short)port);
503 *addr_ret = (struct sockaddr *) addr;
504 *len_ret = sizeof *addr;
505 return 1;
508 /* More cases here... */
510 default:
511 PyErr_SetString(PySocket_Error, "getsockaddrarg: bad family");
512 return 0;
518 /* Get the address length according to the socket object's address family.
519 Return 1 if the family is known, 0 otherwise. The length is returned
520 through len_ret. */
522 static int
523 BUILD_FUNC_DEF_2(getsockaddrlen,PySocketSockObject *,s, int *,len_ret)
525 switch (s->sock_family) {
527 #ifdef AF_UNIX
528 case AF_UNIX:
530 *len_ret = sizeof (struct sockaddr_un);
531 return 1;
533 #endif /* AF_UNIX */
535 case AF_INET:
537 *len_ret = sizeof (struct sockaddr_in);
538 return 1;
541 /* More cases here... */
543 default:
544 PyErr_SetString(PySocket_Error, "getsockaddrarg: bad family");
545 return 0;
551 /* s.accept() method */
553 static PyObject *
554 BUILD_FUNC_DEF_2(PySocketSock_accept,PySocketSockObject *,s, PyObject *,args)
556 char addrbuf[256];
557 int addrlen, newfd;
558 PyObject *sock = NULL;
559 PyObject *addr = NULL;
560 PyObject *res = NULL;
562 if (!PyArg_NoArgs(args))
563 return NULL;
564 if (!getsockaddrlen(s, &addrlen))
565 return NULL;
566 Py_BEGIN_ALLOW_THREADS
567 newfd = accept(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
568 Py_END_ALLOW_THREADS
569 if (newfd < 0)
570 return PySocket_Err();
572 /* Create the new object with unspecified family,
573 to avoid calls to bind() etc. on it. */
574 sock = (PyObject *) PySocketSock_New(newfd,
575 s->sock_family,
576 s->sock_type,
577 s->sock_proto);
578 if (sock == NULL) {
579 close(newfd);
580 goto finally;
582 if (!(addr = makesockaddr((struct sockaddr *) addrbuf, addrlen)))
583 goto finally;
585 if (!(res = Py_BuildValue("OO", sock, addr)))
586 goto finally;
588 finally:
589 Py_XDECREF(sock);
590 Py_XDECREF(addr);
591 return res;
594 static char accept_doc[] =
595 "accept() -> (socket object, address info)\n\
597 Wait for an incoming connection. Return a new socket representing the\n\
598 connection, and the address of the client. For IP sockets, the address\n\
599 info is a pair (hostaddr, port).";
602 /* s.setblocking(1 | 0) method */
604 static PyObject *
605 BUILD_FUNC_DEF_2(PySocketSock_setblocking,PySocketSockObject*,s,PyObject*,args)
607 int block;
608 #ifndef MS_WINDOWS
609 int delay_flag;
610 #endif
611 if (!PyArg_Parse(args, "i", &block))
612 return NULL;
613 Py_BEGIN_ALLOW_THREADS
614 #ifdef __BEOS__
615 block = !block;
616 setsockopt( s->sock_fd, SOL_SOCKET, SO_NONBLOCK,
617 (void *)(&block), sizeof( int ) );
618 #else
619 #ifndef MS_WINDOWS
620 #ifdef PYOS_OS2
621 block = !block;
622 ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block));
623 #else /* !PYOS_OS2 */
624 delay_flag = fcntl (s->sock_fd, F_GETFL, 0);
625 if (block)
626 delay_flag &= (~O_NDELAY);
627 else
628 delay_flag |= O_NDELAY;
629 fcntl (s->sock_fd, F_SETFL, delay_flag);
630 #endif /* !PYOS_OS2 */
631 #else /* MS_WINDOWS */
632 block = !block;
633 ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
634 #endif /* MS_WINDOWS */
635 #endif /* __BEOS__ */
636 Py_END_ALLOW_THREADS
638 Py_INCREF(Py_None);
639 return Py_None;
642 static char setblocking_doc[] =
643 "setblocking(flag)\n\
645 Set the socket to blocking (flag is true) or non-blocking (false).\n\
646 This uses the FIONBIO ioctl with the O_NDELAY flag.";
649 /* s.setsockopt() method.
650 With an integer third argument, sets an integer option.
651 With a string third argument, sets an option from a buffer;
652 use optional built-in module 'struct' to encode the string. */
654 static PyObject *
655 BUILD_FUNC_DEF_2(PySocketSock_setsockopt,PySocketSockObject *,s, PyObject *,args)
657 int level;
658 int optname;
659 int res;
660 char *buf;
661 int buflen;
662 int flag;
664 if (PyArg_Parse(args, "(iii)", &level, &optname, &flag)) {
665 buf = (char *) &flag;
666 buflen = sizeof flag;
668 else {
669 PyErr_Clear();
670 if (!PyArg_Parse(args, "(iis#)", &level, &optname,
671 &buf, &buflen))
672 return NULL;
674 res = setsockopt(s->sock_fd, level, optname, (ANY *)buf, buflen);
675 if (res < 0)
676 return PySocket_Err();
677 Py_INCREF(Py_None);
678 return Py_None;
681 static char setsockopt_doc[] =
682 "setsockopt(level, option, value)\n\
684 Set a socket option. See the Unix manual for level and option.\n\
685 The value argument can either be an integer or a string.";
688 /* s.getsockopt() method.
689 With two arguments, retrieves an integer option.
690 With a third integer argument, retrieves a string buffer of that size;
691 use optional built-in module 'struct' to decode the string. */
693 static PyObject *
694 BUILD_FUNC_DEF_2(PySocketSock_getsockopt,PySocketSockObject *,s, PyObject *,args)
696 int level;
697 int optname;
698 int res;
699 PyObject *buf;
700 int buflen = 0;
702 #ifdef __BEOS__
703 /* We have incomplete socket support. */
704 PyErr_SetString( PySocket_Error, "getsockopt not supported" );
705 return NULL;
706 #else
708 if (!PyArg_ParseTuple(args, "ii|i", &level, &optname, &buflen))
709 return NULL;
711 if (buflen == 0) {
712 int flag = 0;
713 int flagsize = sizeof flag;
714 res = getsockopt(s->sock_fd, level, optname,
715 (ANY *)&flag, &flagsize);
716 if (res < 0)
717 return PySocket_Err();
718 return PyInt_FromLong(flag);
720 if (buflen <= 0 || buflen > 1024) {
721 PyErr_SetString(PySocket_Error,
722 "getsockopt buflen out of range");
723 return NULL;
725 buf = PyString_FromStringAndSize((char *)NULL, buflen);
726 if (buf == NULL)
727 return NULL;
728 res = getsockopt(s->sock_fd, level, optname,
729 (ANY *)PyString_AsString(buf), &buflen);
730 if (res < 0) {
731 Py_DECREF(buf);
732 return PySocket_Err();
734 _PyString_Resize(&buf, buflen);
735 return buf;
736 #endif /* __BEOS__ */
739 static char getsockopt_doc[] =
740 "getsockopt(level, option[, buffersize]) -> value\n\
742 Get a socket option. See the Unix manual for level and option.\n\
743 If a nonzero buffersize argument is given, the return value is a\n\
744 string of that length; otherwise it is an integer.";
747 /* s.bind(sockaddr) method */
749 static PyObject *
750 BUILD_FUNC_DEF_2(PySocketSock_bind,PySocketSockObject *,s, PyObject *,args)
752 struct sockaddr *addr;
753 int addrlen;
754 int res;
755 if (!getsockaddrarg(s, args, &addr, &addrlen))
756 return NULL;
757 Py_BEGIN_ALLOW_THREADS
758 res = bind(s->sock_fd, addr, addrlen);
759 Py_END_ALLOW_THREADS
760 if (res < 0)
761 return PySocket_Err();
762 Py_INCREF(Py_None);
763 return Py_None;
766 static char bind_doc[] =
767 "bind(address)\n\
769 Bind the socket to a local address. For IP sockets, the address is a\n\
770 pair (host, port); the host must refer to the local host.";
773 /* s.close() method.
774 Set the file descriptor to -1 so operations tried subsequently
775 will surely fail. */
777 static PyObject *
778 BUILD_FUNC_DEF_2(PySocketSock_close,PySocketSockObject *,s, PyObject *,args)
780 if (!PyArg_NoArgs(args))
781 return NULL;
782 if (s->sock_fd != -1) {
783 Py_BEGIN_ALLOW_THREADS
784 (void) close(s->sock_fd);
785 Py_END_ALLOW_THREADS
787 s->sock_fd = -1;
788 Py_INCREF(Py_None);
789 return Py_None;
792 static char close_doc[] =
793 "close()\n\
795 Close the socket. It cannot be used after this call.";
798 /* s.connect(sockaddr) method */
800 static PyObject *
801 BUILD_FUNC_DEF_2(PySocketSock_connect,PySocketSockObject *,s, PyObject *,args)
803 struct sockaddr *addr;
804 int addrlen;
805 int res;
806 if (!getsockaddrarg(s, args, &addr, &addrlen))
807 return NULL;
808 Py_BEGIN_ALLOW_THREADS
809 res = connect(s->sock_fd, addr, addrlen);
810 Py_END_ALLOW_THREADS
811 if (res < 0)
812 return PySocket_Err();
813 Py_INCREF(Py_None);
814 return Py_None;
817 static char connect_doc[] =
818 "connect(address)\n\
820 Connect the socket to a remote address. For IP sockets, the address\n\
821 is a pair (host, port).";
824 /* s.connect_ex(sockaddr) method */
826 static PyObject *
827 BUILD_FUNC_DEF_2(PySocketSock_connect_ex,PySocketSockObject *,s, PyObject *,args)
829 struct sockaddr *addr;
830 int addrlen;
831 int res;
832 if (!getsockaddrarg(s, args, &addr, &addrlen))
833 return NULL;
834 Py_BEGIN_ALLOW_THREADS
835 res = connect(s->sock_fd, addr, addrlen);
836 Py_END_ALLOW_THREADS
837 if (res != 0)
838 res = errno;
839 return PyInt_FromLong((long) res);
842 static char connect_ex_doc[] =
843 "connect_ex(address)\n\
845 This is like connect(address), but returns an error code (the errno value)\n\
846 instead of raising an exception when an error occurs.";
849 /* s.fileno() method */
851 static PyObject *
852 BUILD_FUNC_DEF_2(PySocketSock_fileno,PySocketSockObject *,s, PyObject *,args)
854 if (!PyArg_NoArgs(args))
855 return NULL;
856 return PyInt_FromLong((long) s->sock_fd);
859 static char fileno_doc[] =
860 "fileno() -> integer\n\
862 Return the integer file descriptor of the socket.";
865 #ifndef NO_DUP
866 /* s.dup() method */
868 static PyObject *
869 BUILD_FUNC_DEF_2(PySocketSock_dup,PySocketSockObject *,s, PyObject *,args)
871 int newfd;
872 PyObject *sock;
873 if (!PyArg_NoArgs(args))
874 return NULL;
875 newfd = dup(s->sock_fd);
876 if (newfd < 0)
877 return PySocket_Err();
878 sock = (PyObject *) PySocketSock_New(newfd,
879 s->sock_family,
880 s->sock_type,
881 s->sock_proto);
882 if (sock == NULL)
883 close(newfd);
884 return sock;
887 static char dup_doc[] =
888 "dup() -> socket object\n\
890 Return a new socket object connected to the same system resource.";
892 #endif
895 /* s.getsockname() method */
897 static PyObject *
898 BUILD_FUNC_DEF_2(PySocketSock_getsockname,PySocketSockObject *,s, PyObject *,args)
900 char addrbuf[256];
901 int addrlen, res;
902 if (!PyArg_NoArgs(args))
903 return NULL;
904 if (!getsockaddrlen(s, &addrlen))
905 return NULL;
906 memset(addrbuf, 0, addrlen);
907 Py_BEGIN_ALLOW_THREADS
908 res = getsockname(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
909 Py_END_ALLOW_THREADS
910 if (res < 0)
911 return PySocket_Err();
912 return makesockaddr((struct sockaddr *) addrbuf, addrlen);
915 static char getsockname_doc[] =
916 "getsockname() -> address info\n\
918 Return the address of the local endpoint. For IP sockets, the address\n\
919 info is a pair (hostaddr, port).";
922 #ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
923 /* s.getpeername() method */
925 static PyObject *
926 BUILD_FUNC_DEF_2(PySocketSock_getpeername,PySocketSockObject *,s, PyObject *,args)
928 char addrbuf[256];
929 int addrlen, res;
930 if (!PyArg_NoArgs(args))
931 return NULL;
932 if (!getsockaddrlen(s, &addrlen))
933 return NULL;
934 Py_BEGIN_ALLOW_THREADS
935 res = getpeername(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
936 Py_END_ALLOW_THREADS
937 if (res < 0)
938 return PySocket_Err();
939 return makesockaddr((struct sockaddr *) addrbuf, addrlen);
942 static char getpeername_doc[] =
943 "getpeername() -> address info\n\
945 Return the address of the remote endpoint. For IP sockets, the address\n\
946 info is a pair (hostaddr, port).";
948 #endif /* HAVE_GETPEERNAME */
951 /* s.listen(n) method */
953 static PyObject *
954 BUILD_FUNC_DEF_2(PySocketSock_listen,PySocketSockObject *,s, PyObject *,args)
956 int backlog;
957 int res;
958 if (!PyArg_Parse(args, "i", &backlog))
959 return NULL;
960 Py_BEGIN_ALLOW_THREADS
961 if (backlog < 1)
962 backlog = 1;
963 res = listen(s->sock_fd, backlog);
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 listen_doc[] =
972 "listen(backlog)\n\
974 Enable a server to accept connections. The backlog argument must be at\n\
975 least 1; it specifies the number of unaccepted connection that the system\n\
976 will allow before refusing new connections.";
979 #ifndef NO_DUP
980 /* s.makefile(mode) method.
981 Create a new open file object referring to a dupped version of
982 the socket's file descriptor. (The dup() call is necessary so
983 that the open file and socket objects may be closed independent
984 of each other.)
985 The mode argument specifies 'r' or 'w' passed to fdopen(). */
987 static PyObject *
988 BUILD_FUNC_DEF_2(PySocketSock_makefile,PySocketSockObject *,s, PyObject *,args)
990 extern int fclose Py_PROTO((FILE *));
991 char *mode = "r";
992 int bufsize = -1;
993 int fd;
994 FILE *fp;
995 PyObject *f;
997 if (!PyArg_ParseTuple(args, "|si", &mode, &bufsize))
998 return NULL;
999 #ifdef MS_WIN32
1000 if (((fd = _open_osfhandle(s->sock_fd, _O_BINARY)) < 0) ||
1001 ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL))
1002 #else
1003 if ((fd = dup(s->sock_fd)) < 0 || (fp = fdopen(fd, mode)) == NULL)
1004 #endif
1006 if (fd >= 0)
1007 close(fd);
1008 return PySocket_Err();
1010 f = PyFile_FromFile(fp, "<socket>", mode, fclose);
1011 if (f != NULL)
1012 PyFile_SetBufSize(f, bufsize);
1013 return f;
1016 static char makefile_doc[] =
1017 "makefile([mode[, buffersize]]) -> file object\n\
1019 Return a regular file object corresponding to the socket.\n\
1020 The mode and buffersize arguments are as for the built-in open() function.";
1022 #endif /* NO_DUP */
1025 /* s.recv(nbytes [,flags]) method */
1027 static PyObject *
1028 BUILD_FUNC_DEF_2(PySocketSock_recv,PySocketSockObject *,s, PyObject *,args)
1030 int len, n, flags = 0;
1031 PyObject *buf;
1032 if (!PyArg_ParseTuple(args, "i|i", &len, &flags))
1033 return NULL;
1034 buf = PyString_FromStringAndSize((char *) 0, len);
1035 if (buf == NULL)
1036 return NULL;
1037 Py_BEGIN_ALLOW_THREADS
1038 n = recv(s->sock_fd, PyString_AsString(buf), len, flags);
1039 Py_END_ALLOW_THREADS
1040 if (n < 0) {
1041 Py_DECREF(buf);
1042 return PySocket_Err();
1044 if (n != len && _PyString_Resize(&buf, n) < 0)
1045 return NULL;
1046 return buf;
1049 static char recv_doc[] =
1050 "recv(buffersize[, flags]) -> data\n\
1052 Receive up to buffersize bytes from the socket. For the optional flags\n\
1053 argument, see the Unix manual. When no data is available, block until\n\
1054 at least one byte is available or until the remote end is closed. When\n\
1055 the remote end is closed and all data is read, return the empty string.";
1058 /* s.recvfrom(nbytes [,flags]) method */
1060 static PyObject *
1061 BUILD_FUNC_DEF_2(PySocketSock_recvfrom,PySocketSockObject *,s, PyObject *,args)
1063 char addrbuf[256];
1064 PyObject *buf = NULL;
1065 PyObject *addr = NULL;
1066 PyObject *ret = NULL;
1068 int addrlen, len, n, flags = 0;
1069 if (!PyArg_ParseTuple(args, "i|i", &len, &flags))
1070 return NULL;
1071 if (!getsockaddrlen(s, &addrlen))
1072 return NULL;
1073 buf = PyString_FromStringAndSize((char *) 0, len);
1074 if (buf == NULL)
1075 return NULL;
1076 Py_BEGIN_ALLOW_THREADS
1077 n = recvfrom(s->sock_fd, PyString_AsString(buf), len, flags,
1078 #ifndef MS_WINDOWS
1079 #if defined(PYOS_OS2)
1080 (struct sockaddr *)addrbuf, &addrlen
1081 #else
1082 (ANY *)addrbuf, &addrlen
1083 #endif
1084 #else
1085 (struct sockaddr *)addrbuf, &addrlen
1086 #endif
1088 Py_END_ALLOW_THREADS
1089 if (n < 0) {
1090 Py_DECREF(buf);
1091 return PySocket_Err();
1093 if (n != len && _PyString_Resize(&buf, n) < 0)
1094 return NULL;
1096 if (!(addr = makesockaddr((struct sockaddr *)addrbuf, addrlen)))
1097 goto finally;
1099 ret = Py_BuildValue("OO", buf, addr);
1100 finally:
1101 Py_XDECREF(addr);
1102 Py_XDECREF(buf);
1103 return ret;
1106 static char recvfrom_doc[] =
1107 "recvfrom(buffersize[, flags]) -> (data, address info)\n\
1109 Like recv(buffersize, flags) but also return the sender's address info.";
1112 /* s.send(data [,flags]) method */
1114 static PyObject *
1115 BUILD_FUNC_DEF_2(PySocketSock_send,PySocketSockObject *,s, PyObject *,args)
1117 char *buf;
1118 int len, n, flags = 0;
1119 if (!PyArg_ParseTuple(args, "s#|i", &buf, &len, &flags))
1120 return NULL;
1121 Py_BEGIN_ALLOW_THREADS
1122 n = send(s->sock_fd, buf, len, flags);
1123 Py_END_ALLOW_THREADS
1124 if (n < 0)
1125 return PySocket_Err();
1126 return PyInt_FromLong((long)n);
1129 static char send_doc[] =
1130 "send(data[, flags])\n\
1132 Send a data string to the socket. For the optional flags\n\
1133 argument, see the Unix manual.";
1136 /* s.sendto(data, [flags,] sockaddr) method */
1138 static PyObject *
1139 BUILD_FUNC_DEF_2(PySocketSock_sendto,PySocketSockObject *,s, PyObject *,args)
1141 PyObject *addro;
1142 char *buf;
1143 struct sockaddr *addr;
1144 int addrlen, len, n, flags;
1145 flags = 0;
1146 if (!PyArg_Parse(args, "(s#O)", &buf, &len, &addro)) {
1147 PyErr_Clear();
1148 if (!PyArg_Parse(args, "(s#iO)", &buf, &len, &flags, &addro))
1149 return NULL;
1151 if (!getsockaddrarg(s, addro, &addr, &addrlen))
1152 return NULL;
1153 Py_BEGIN_ALLOW_THREADS
1154 n = sendto(s->sock_fd, buf, len, flags, addr, addrlen);
1155 Py_END_ALLOW_THREADS
1156 if (n < 0)
1157 return PySocket_Err();
1158 return PyInt_FromLong((long)n);
1161 static char sendto_doc[] =
1162 "sendto(data[, flags], address)\n\
1164 Like send(data, flags) but allows specifying the destination address.\n\
1165 For IP sockets, the address is a pair (hostaddr, port).";
1168 /* s.shutdown(how) method */
1170 static PyObject *
1171 BUILD_FUNC_DEF_2(PySocketSock_shutdown,PySocketSockObject *,s, PyObject *,args)
1173 int how;
1174 int res;
1175 if (!PyArg_Parse(args, "i", &how))
1176 return NULL;
1177 Py_BEGIN_ALLOW_THREADS
1178 res = shutdown(s->sock_fd, how);
1179 Py_END_ALLOW_THREADS
1180 if (res < 0)
1181 return PySocket_Err();
1182 Py_INCREF(Py_None);
1183 return Py_None;
1186 static char shutdown_doc[] =
1187 "shutdown(flag)\n\
1189 Shut down the reading side of the socket (flag == 0), the writing side\n\
1190 of the socket (flag == 1), or both ends (flag == 2).";
1193 /* List of methods for socket objects */
1195 static PyMethodDef PySocketSock_methods[] = {
1196 {"accept", (PyCFunction)PySocketSock_accept, 0,
1197 accept_doc},
1198 {"bind", (PyCFunction)PySocketSock_bind, 0,
1199 bind_doc},
1200 {"close", (PyCFunction)PySocketSock_close, 0,
1201 close_doc},
1202 {"connect", (PyCFunction)PySocketSock_connect, 0,
1203 connect_doc},
1204 {"connect_ex", (PyCFunction)PySocketSock_connect_ex, 0,
1205 connect_ex_doc},
1206 #ifndef NO_DUP
1207 {"dup", (PyCFunction)PySocketSock_dup, 0,
1208 dup_doc},
1209 #endif
1210 {"fileno", (PyCFunction)PySocketSock_fileno, 0,
1211 fileno_doc},
1212 #ifdef HAVE_GETPEERNAME
1213 {"getpeername", (PyCFunction)PySocketSock_getpeername, 0,
1214 getpeername_doc},
1215 #endif
1216 {"getsockname", (PyCFunction)PySocketSock_getsockname, 0,
1217 getsockname_doc},
1218 {"getsockopt", (PyCFunction)PySocketSock_getsockopt, 1,
1219 getsockopt_doc},
1220 {"listen", (PyCFunction)PySocketSock_listen, 0,
1221 listen_doc},
1222 #ifndef NO_DUP
1223 {"makefile", (PyCFunction)PySocketSock_makefile, 1,
1224 makefile_doc},
1225 #endif
1226 {"recv", (PyCFunction)PySocketSock_recv, 1,
1227 recv_doc},
1228 {"recvfrom", (PyCFunction)PySocketSock_recvfrom, 1,
1229 recvfrom_doc},
1230 {"send", (PyCFunction)PySocketSock_send, 1,
1231 send_doc},
1232 {"sendto", (PyCFunction)PySocketSock_sendto, 0,
1233 sendto_doc},
1234 {"setblocking", (PyCFunction)PySocketSock_setblocking, 0,
1235 setblocking_doc},
1236 {"setsockopt", (PyCFunction)PySocketSock_setsockopt, 0,
1237 setsockopt_doc},
1238 {"shutdown", (PyCFunction)PySocketSock_shutdown, 0,
1239 shutdown_doc},
1240 {NULL, NULL} /* sentinel */
1244 /* Deallocate a socket object in response to the last Py_DECREF().
1245 First close the file description. */
1247 static void
1248 BUILD_FUNC_DEF_1(PySocketSock_dealloc,PySocketSockObject *,s)
1250 (void) close(s->sock_fd);
1251 PyMem_DEL(s);
1255 /* Return a socket object's named attribute. */
1257 static PyObject *
1258 BUILD_FUNC_DEF_2(PySocketSock_getattr,PySocketSockObject *,s, char *,name)
1260 return Py_FindMethod(PySocketSock_methods, (PyObject *) s, name);
1264 static PyObject *
1265 BUILD_FUNC_DEF_1(PySocketSock_repr,PySocketSockObject *,s)
1267 char buf[512];
1268 sprintf(buf,
1269 "<socket object, fd=%d, family=%d, type=%d, protocol=%d>",
1270 s->sock_fd, s->sock_family, s->sock_type, s->sock_proto);
1271 return PyString_FromString(buf);
1275 /* Type object for socket objects. */
1277 static PyTypeObject PySocketSock_Type = {
1278 PyObject_HEAD_INIT(0) /* Must fill in type value later */
1280 "socket",
1281 sizeof(PySocketSockObject),
1283 (destructor)PySocketSock_dealloc, /*tp_dealloc*/
1284 0, /*tp_print*/
1285 (getattrfunc)PySocketSock_getattr, /*tp_getattr*/
1286 0, /*tp_setattr*/
1287 0, /*tp_compare*/
1288 (reprfunc)PySocketSock_repr, /*tp_repr*/
1289 0, /*tp_as_number*/
1290 0, /*tp_as_sequence*/
1291 0, /*tp_as_mapping*/
1295 /* Python interface to gethostname(). */
1297 /*ARGSUSED*/
1298 static PyObject *
1299 BUILD_FUNC_DEF_2(PySocket_gethostname,PyObject *,self, PyObject *,args)
1301 char buf[1024];
1302 int res;
1303 if (!PyArg_NoArgs(args))
1304 return NULL;
1305 Py_BEGIN_ALLOW_THREADS
1306 res = gethostname(buf, (int) sizeof buf - 1);
1307 Py_END_ALLOW_THREADS
1308 if (res < 0)
1309 return PySocket_Err();
1310 buf[sizeof buf - 1] = '\0';
1311 return PyString_FromString(buf);
1314 static char gethostname_doc[] =
1315 "gethostname() -> string\n\
1317 Return the current host name.";
1320 /* Python interface to gethostbyname(name). */
1322 /*ARGSUSED*/
1323 static PyObject *
1324 BUILD_FUNC_DEF_2(PySocket_gethostbyname,PyObject *,self, PyObject *,args)
1326 char *name;
1327 struct sockaddr_in addrbuf;
1328 if (!PyArg_Parse(args, "s", &name))
1329 return NULL;
1330 if (setipaddr(name, &addrbuf) < 0)
1331 return NULL;
1332 return makeipaddr(&addrbuf);
1335 static char gethostbyname_doc[] =
1336 "gethostbyname(host) -> address\n\
1338 Return the IP address (a string of the form '255.255.255.255') for a host.";
1341 /* Convenience function common to gethostbyname_ex and gethostbyaddr */
1343 static PyObject *
1344 gethost_common(h, addr)
1345 struct hostent *h;
1346 struct sockaddr_in *addr;
1348 char **pch;
1349 PyObject *rtn_tuple = (PyObject *)NULL;
1350 PyObject *name_list = (PyObject *)NULL;
1351 PyObject *addr_list = (PyObject *)NULL;
1352 PyObject *tmp;
1353 if (h == NULL) {
1354 #ifdef HAVE_HSTRERROR
1355 /* Let's get real error message to return */
1356 extern int h_errno;
1357 PyErr_SetString(PySocket_Error, (char *)hstrerror(h_errno));
1358 #else
1359 PyErr_SetString(PySocket_Error, "host not found");
1360 #endif
1361 return NULL;
1363 if ((name_list = PyList_New(0)) == NULL)
1364 goto err;
1365 if ((addr_list = PyList_New(0)) == NULL)
1366 goto err;
1367 for (pch = h->h_aliases; *pch != NULL; pch++) {
1368 int status;
1369 tmp = PyString_FromString(*pch);
1370 if (tmp == NULL)
1371 goto err;
1372 status = PyList_Append(name_list, tmp);
1373 Py_DECREF(tmp);
1374 if (status)
1375 goto err;
1377 for (pch = h->h_addr_list; *pch != NULL; pch++) {
1378 int status;
1379 memcpy((char *) &addr->sin_addr, *pch, h->h_length);
1380 tmp = makeipaddr(addr);
1381 if (tmp == NULL)
1382 goto err;
1383 status = PyList_Append(addr_list, tmp);
1384 Py_DECREF(tmp);
1385 if (status)
1386 goto err;
1388 rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list);
1389 err:
1390 Py_XDECREF(name_list);
1391 Py_XDECREF(addr_list);
1392 return rtn_tuple;
1396 /* Python interface to gethostbyname_ex(name). */
1398 /*ARGSUSED*/
1399 static PyObject *
1400 BUILD_FUNC_DEF_2(PySocket_gethostbyname_ex,PyObject *,self, PyObject *,args)
1402 char *name;
1403 struct hostent *h;
1404 struct sockaddr_in addr;
1405 #ifdef HAVE_GETHOSTBYNAME_R
1406 struct hostent hp_allocated;
1407 char buf[16384];
1408 int buf_len = (sizeof buf) - 1;
1409 int errnop;
1410 #endif /* HAVE_GETHOSTBYNAME_R */
1411 if (!PyArg_Parse(args, "s", &name))
1412 return NULL;
1413 if (setipaddr(name, &addr) < 0)
1414 return NULL;
1415 Py_BEGIN_ALLOW_THREADS
1416 #ifdef HAVE_GETHOSTBYNAME_R
1417 h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
1418 #else /* not HAVE_GETHOSTBYNAME_R */
1419 #if defined(WITH_THREAD) && !defined(MS_WINDOWS)
1420 PyThread_acquire_lock(gethostbyname_lock,1);
1421 #endif
1422 h = gethostbyname(name);
1423 #if defined(WITH_THREAD) && !defined(MS_WINDOWS)
1424 PyThread_release_lock(gethostbyname_lock);
1425 #endif
1426 #endif /* HAVE_GETHOSTBYNAME_R */
1427 Py_END_ALLOW_THREADS
1428 return gethost_common(h,&addr);
1431 static char ghbn_ex_doc[] =
1432 "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
1434 Return the true host name, a list of aliases, and a list of IP addresses,\n\
1435 for a host. The host argument is a string giving a host name or IP number.";
1438 /* Python interface to gethostbyaddr(IP). */
1440 /*ARGSUSED*/
1441 static PyObject *
1442 BUILD_FUNC_DEF_2(PySocket_gethostbyaddr,PyObject *,self, PyObject *, args)
1444 struct sockaddr_in addr;
1445 char *ip_num;
1446 struct hostent *h;
1447 #ifdef HAVE_GETHOSTBYNAME_R
1448 struct hostent hp_allocated;
1449 char buf[16384];
1450 int buf_len = (sizeof buf) - 1;
1451 int errnop;
1452 #endif /* HAVE_GETHOSTBYNAME_R */
1454 if (!PyArg_Parse(args, "s", &ip_num))
1455 return NULL;
1456 if (setipaddr(ip_num, &addr) < 0)
1457 return NULL;
1458 Py_BEGIN_ALLOW_THREADS
1459 #ifdef HAVE_GETHOSTBYNAME_R
1460 h = gethostbyaddr_r((char *)&addr.sin_addr,
1461 sizeof(addr.sin_addr),
1462 AF_INET,
1463 &hp_allocated, buf, buf_len, &errnop);
1464 #else /* not HAVE_GETHOSTBYNAME_R */
1465 #if defined(WITH_THREAD) && !defined(MS_WINDOWS)
1466 PyThread_acquire_lock(gethostbyname_lock,1);
1467 #endif
1468 h = gethostbyaddr((char *)&addr.sin_addr,
1469 sizeof(addr.sin_addr),
1470 AF_INET);
1471 #if defined(WITH_THREAD) && !defined(MS_WINDOWS)
1472 PyThread_release_lock(gethostbyname_lock);
1473 #endif
1474 #endif /* HAVE_GETHOSTBYNAME_R */
1475 Py_END_ALLOW_THREADS
1476 return gethost_common(h,&addr);
1479 static char gethostbyaddr_doc[] =
1480 "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
1482 Return the true host name, a list of aliases, and a list of IP addresses,\n\
1483 for a host. The host argument is a string giving a host name or IP number.";
1486 /* Python interface to getservbyname(name).
1487 This only returns the port number, since the other info is already
1488 known or not useful (like the list of aliases). */
1490 /*ARGSUSED*/
1491 static PyObject *
1492 BUILD_FUNC_DEF_2(PySocket_getservbyname,PyObject *,self, PyObject *,args)
1494 char *name, *proto;
1495 struct servent *sp;
1496 if (!PyArg_Parse(args, "(ss)", &name, &proto))
1497 return NULL;
1498 Py_BEGIN_ALLOW_THREADS
1499 sp = getservbyname(name, proto);
1500 Py_END_ALLOW_THREADS
1501 if (sp == NULL) {
1502 PyErr_SetString(PySocket_Error, "service/proto not found");
1503 return NULL;
1505 return PyInt_FromLong((long) ntohs(sp->s_port));
1508 static char getservbyname_doc[] =
1509 "getservbyname(servicename, protocolname) -> integer\n\
1511 Return a port number from a service name and protocol name.\n\
1512 The protocol name should be 'tcp' or 'udp'.";
1515 /* Python interface to getprotobyname(name).
1516 This only returns the protocol number, since the other info is
1517 already known or not useful (like the list of aliases). */
1519 /*ARGSUSED*/
1520 static PyObject *
1521 BUILD_FUNC_DEF_2(PySocket_getprotobyname,PyObject *,self, PyObject *,args)
1523 char *name;
1524 struct protoent *sp;
1525 #ifdef __BEOS__
1526 /* Not available in BeOS yet. - [cjh] */
1527 PyErr_SetString( PySocket_Error, "getprotobyname not supported" );
1528 return NULL;
1529 #else
1530 if (!PyArg_Parse(args, "s", &name))
1531 return NULL;
1532 Py_BEGIN_ALLOW_THREADS
1533 sp = getprotobyname(name);
1534 Py_END_ALLOW_THREADS
1535 if (sp == NULL) {
1536 PyErr_SetString(PySocket_Error, "protocol not found");
1537 return NULL;
1539 return PyInt_FromLong((long) sp->p_proto);
1540 #endif
1543 static char getprotobyname_doc[] =
1544 "getprotobyname(name) -> integer\n\
1546 Return the protocol number for the named protocol. (Rarely used.)";
1549 /* Python interface to socket(family, type, proto).
1550 The third (protocol) argument is optional.
1551 Return a new socket object. */
1553 /*ARGSUSED*/
1554 static PyObject *
1555 BUILD_FUNC_DEF_2(PySocket_socket,PyObject *,self, PyObject *,args)
1557 PySocketSockObject *s;
1558 #ifdef MS_WINDOWS
1559 SOCKET fd;
1560 #else
1561 int fd;
1562 #endif
1563 int family, type, proto = 0;
1564 if (!PyArg_ParseTuple(args, "ii|i", &family, &type, &proto))
1565 return NULL;
1566 Py_BEGIN_ALLOW_THREADS
1567 fd = socket(family, type, proto);
1568 Py_END_ALLOW_THREADS
1569 #ifdef MS_WINDOWS
1570 if (fd == INVALID_SOCKET)
1571 #else
1572 if (fd < 0)
1573 #endif
1574 return PySocket_Err();
1575 s = PySocketSock_New(fd, family, type, proto);
1576 /* If the object can't be created, don't forget to close the
1577 file descriptor again! */
1578 if (s == NULL)
1579 (void) close(fd);
1580 /* From now on, ignore SIGPIPE and let the error checking
1581 do the work. */
1582 #ifdef SIGPIPE
1583 (void) signal(SIGPIPE, SIG_IGN);
1584 #endif
1585 return (PyObject *) s;
1588 static char socket_doc[] =
1589 "socket(family, type[, proto]) -> socket object\n\
1591 Open a socket of the given type. The family argument specifies the\n\
1592 address family; it is normally AF_INET, sometimes AF_UNIX.\n\
1593 The type argument specifies whether this is a stream (SOCK_STREAM)\n\
1594 or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0,\n\
1595 specifying the default protocol.";
1598 #ifndef NO_DUP
1599 /* Create a socket object from a numeric file description.
1600 Useful e.g. if stdin is a socket.
1601 Additional arguments as for socket(). */
1603 /*ARGSUSED*/
1604 static PyObject *
1605 BUILD_FUNC_DEF_2(PySocket_fromfd,PyObject *,self, PyObject *,args)
1607 PySocketSockObject *s;
1608 int fd, family, type, proto = 0;
1609 if (!PyArg_ParseTuple(args, "iii|i", &fd, &family, &type, &proto))
1610 return NULL;
1611 /* Dup the fd so it and the socket can be closed independently */
1612 fd = dup(fd);
1613 if (fd < 0)
1614 return PySocket_Err();
1615 s = PySocketSock_New(fd, family, type, proto);
1616 /* From now on, ignore SIGPIPE and let the error checking
1617 do the work. */
1618 #ifdef SIGPIPE
1619 (void) signal(SIGPIPE, SIG_IGN);
1620 #endif
1621 return (PyObject *) s;
1624 static char fromfd_doc[] =
1625 "fromfd(fd, family, type[, proto]) -> socket object\n\
1627 Create a socket object from the given file descriptor.\n\
1628 The remaining arguments are the same as for socket().";
1630 #endif /* NO_DUP */
1633 static PyObject *
1634 BUILD_FUNC_DEF_2(PySocket_ntohs, PyObject *, self, PyObject *, args)
1636 int x1, x2;
1638 if (!PyArg_Parse(args, "i", &x1)) {
1639 return NULL;
1641 x2 = (int)ntohs((short)x1);
1642 return PyInt_FromLong(x2);
1645 static char ntohs_doc[] =
1646 "ntohs(integer) -> integer\n\
1648 Convert a 16-bit integer from network to host byte order.";
1651 static PyObject *
1652 BUILD_FUNC_DEF_2(PySocket_ntohl, PyObject *, self, PyObject *, args)
1654 int x1, x2;
1656 if (!PyArg_Parse(args, "i", &x1)) {
1657 return NULL;
1659 x2 = ntohl(x1);
1660 return PyInt_FromLong(x2);
1663 static char ntohl_doc[] =
1664 "ntohl(integer) -> integer\n\
1666 Convert a 32-bit integer from network to host byte order.";
1669 static PyObject *
1670 BUILD_FUNC_DEF_2(PySocket_htons, PyObject *, self, PyObject *, args)
1672 int x1, x2;
1674 if (!PyArg_Parse(args, "i", &x1)) {
1675 return NULL;
1677 x2 = (int)htons((short)x1);
1678 return PyInt_FromLong(x2);
1681 static char htons_doc[] =
1682 "htons(integer) -> integer\n\
1684 Convert a 16-bit integer from host to network byte order.";
1687 static PyObject *
1688 BUILD_FUNC_DEF_2(PySocket_htonl, PyObject *, self, PyObject *, args)
1690 int x1, x2;
1692 if (!PyArg_Parse(args, "i", &x1)) {
1693 return NULL;
1695 x2 = htonl(x1);
1696 return PyInt_FromLong(x2);
1699 static char htonl_doc[] =
1700 "htonl(integer) -> integer\n\
1702 Convert a 32-bit integer from host to network byte order.";
1705 /* List of functions exported by this module. */
1707 static PyMethodDef PySocket_methods[] = {
1708 {"gethostbyname", PySocket_gethostbyname, 0, gethostbyname_doc},
1709 {"gethostbyname_ex", PySocket_gethostbyname_ex, 0, ghbn_ex_doc},
1710 {"gethostbyaddr", PySocket_gethostbyaddr, 0, gethostbyaddr_doc},
1711 {"gethostname", PySocket_gethostname, 0, gethostname_doc},
1712 {"getservbyname", PySocket_getservbyname, 0, getservbyname_doc},
1713 {"getprotobyname", PySocket_getprotobyname, 0,getprotobyname_doc},
1714 {"socket", PySocket_socket, 1, socket_doc},
1715 #ifndef NO_DUP
1716 {"fromfd", PySocket_fromfd, 1, fromfd_doc},
1717 #endif
1718 {"ntohs", PySocket_ntohs, 0, ntohs_doc},
1719 {"ntohl", PySocket_ntohl, 0, ntohl_doc},
1720 {"htons", PySocket_htons, 0, htons_doc},
1721 {"htonl", PySocket_htonl, 0, htonl_doc},
1722 {NULL, NULL} /* Sentinel */
1726 /* Convenience routine to export an integer value.
1728 * Errors are silently ignored, for better or for worse...
1730 static void
1731 BUILD_FUNC_DEF_3(insint,PyObject *,d, char *,name, int,value)
1733 PyObject *v = PyInt_FromLong((long) value);
1734 if (!v || PyDict_SetItemString(d, name, v))
1735 PyErr_Clear();
1737 Py_XDECREF(v);
1741 #ifdef MS_WINDOWS
1743 /* Additional initialization and cleanup for NT/Windows */
1745 static void
1746 NTcleanup()
1748 WSACleanup();
1751 static int
1752 NTinit()
1754 WSADATA WSAData;
1755 int ret;
1756 char buf[100];
1757 ret = WSAStartup(0x0101, &WSAData);
1758 switch (ret) {
1759 case 0: /* no error */
1760 atexit(NTcleanup);
1761 return 1;
1762 case WSASYSNOTREADY:
1763 PyErr_SetString(PyExc_ImportError,
1764 "WSAStartup failed: network not ready");
1765 break;
1766 case WSAVERNOTSUPPORTED:
1767 case WSAEINVAL:
1768 PyErr_SetString(PyExc_ImportError,
1769 "WSAStartup failed: requested version not supported");
1770 break;
1771 default:
1772 sprintf(buf, "WSAStartup failed: error code %d", ret);
1773 PyErr_SetString(PyExc_ImportError, buf);
1774 break;
1776 return 0;
1779 #endif /* MS_WINDOWS */
1781 #if defined(PYOS_OS2)
1783 /* Additional initialization and cleanup for OS/2 */
1785 static void
1786 OS2cleanup()
1788 /* No cleanup is necessary for OS/2 Sockets */
1791 static int
1792 OS2init()
1794 char reason[64];
1795 int rc = sock_init();
1797 if (rc == 0) {
1798 atexit(OS2cleanup);
1799 return 1; /* Indicate Success */
1802 sprintf(reason, "OS/2 TCP/IP Error# %d", sock_errno());
1803 PyErr_SetString(PyExc_ImportError, reason);
1805 return 0; /* Indicate Failure */
1808 #endif /* PYOS_OS2 */
1811 /* Initialize this module.
1812 * This is called when the first 'import socket' is done,
1813 * via a table in config.c, if config.c is compiled with USE_SOCKET
1814 * defined.
1816 * For MS_WINDOWS (which means any Windows variant), this module
1817 * is actually called "_socket", and there's a wrapper "socket.py"
1818 * which implements some missing functionality (such as makefile(),
1819 * dup() and fromfd()). The import of "_socket" may fail with an
1820 * ImportError exception if initialization of WINSOCK fails. When
1821 * WINSOCK is initialized succesfully, a call to WSACleanup() is
1822 * scheduled to be made at exit time.
1824 * For OS/2, this module is also called "_socket" and uses a wrapper
1825 * "socket.py" which implements that functionality that is missing
1826 * when PC operating systems don't put socket descriptors in the
1827 * operating system's filesystem layer.
1830 static char module_doc[] =
1831 "This module provides socket operations and some related functions.\n\
1832 On Unix, it supports IP (Internet Protocol) and Unix domain sockets.\n\
1833 On other systems, it only supports IP.\n\
1835 Functions:\n\
1837 socket() -- create a new socket object\n\
1838 fromfd() -- create a socket object from an open file descriptor (*)\n\
1839 gethostname() -- return the current hostname\n\
1840 gethostbyname() -- map a hostname to its IP number\n\
1841 gethostbyaddr() -- map an IP number or hostname to DNS info\n\
1842 getservbyname() -- map a service name and a protocol name to a port number\n\
1843 getprotobyname() -- mape a protocol name (e.g. 'tcp') to a number\n\
1844 ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order\n\
1845 htons(), htonl() -- convert 16, 32 bit int from host to network byte order\n\
1847 (*) not available on all platforms!)\n\
1849 Special objects:\n\
1851 SocketType -- type object for socket objects\n\
1852 error -- exception raised for I/O errors\n\
1854 Integer constants:\n\
1856 AF_INET, AF_UNIX -- socket domains (first argument to socket() call)\n\
1857 SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument)\n\
1859 Many other constants may be defined; these may be used in calls to\n\
1860 the setsockopt() and getsockopt() methods.\n\
1863 static char sockettype_doc[] =
1864 "A socket represents one endpoint of a network connection.\n\
1866 Methods:\n\
1868 accept() -- accept a connection, returning new socket and client address\n\
1869 bind() -- bind the socket to a local address\n\
1870 close() -- close the socket\n\
1871 connect() -- connect the socket to a remote address\n\
1872 connect_ex() -- connect, return an error code instead of an exception \n\
1873 dup() -- return a new socket object identical to the current one (*)\n\
1874 fileno() -- return underlying file descriptor\n\
1875 getpeername() -- return remote address (*)\n\
1876 getsockname() -- return local address\n\
1877 getsockopt() -- get socket options\n\
1878 listen() -- start listening for incoming connections\n\
1879 makefile() -- return a file object corresponding tot the socket (*)\n\
1880 recv() -- receive data\n\
1881 recvfrom() -- receive data and sender's address\n\
1882 send() -- send data\n\
1883 sendto() -- send data to a given address\n\
1884 setblocking() -- set or clear the blocking I/O flag\n\
1885 setsockopt() -- set socket options\n\
1886 shutdown() -- shut down traffic in one or both directions\n\
1888 (*) not available on all platforms!)";
1890 DL_EXPORT(void)
1891 #if defined(MS_WINDOWS) || defined(PYOS_OS2) || defined(__BEOS__)
1892 init_socket()
1893 #else
1894 initsocket()
1895 #endif
1897 PyObject *m, *d;
1898 #ifdef MS_WINDOWS
1899 if (!NTinit())
1900 return;
1901 m = Py_InitModule3("_socket", PySocket_methods, module_doc);
1902 #else
1903 #if defined(__TOS_OS2__)
1904 if (!OS2init())
1905 return;
1906 m = Py_InitModule3("_socket", PySocket_methods, module_doc);
1907 #else
1908 #if defined(__BEOS__)
1909 m = Py_InitModule3("_socket", PySocket_methods, module_doc);
1910 #else
1911 m = Py_InitModule3("socket", PySocket_methods, module_doc);
1912 #endif /* __BEOS__ */
1913 #endif
1914 #endif
1915 d = PyModule_GetDict(m);
1916 PySocket_Error = PyErr_NewException("socket.error", NULL, NULL);
1917 if (PySocket_Error == NULL)
1918 return;
1919 PyDict_SetItemString(d, "error", PySocket_Error);
1920 PySocketSock_Type.ob_type = &PyType_Type;
1921 PySocketSock_Type.tp_doc = sockettype_doc;
1922 Py_INCREF(&PySocketSock_Type);
1923 if (PyDict_SetItemString(d, "SocketType",
1924 (PyObject *)&PySocketSock_Type) != 0)
1925 return;
1926 insint(d, "AF_INET", AF_INET);
1927 #ifdef AF_UNIX
1928 insint(d, "AF_UNIX", AF_UNIX);
1929 #endif /* AF_UNIX */
1930 insint(d, "SOCK_STREAM", SOCK_STREAM);
1931 insint(d, "SOCK_DGRAM", SOCK_DGRAM);
1932 #ifndef __BEOS__
1933 /* We have incomplete socket support. */
1934 insint(d, "SOCK_RAW", SOCK_RAW);
1935 insint(d, "SOCK_SEQPACKET", SOCK_SEQPACKET);
1936 insint(d, "SOCK_RDM", SOCK_RDM);
1937 #endif
1939 #ifdef SO_DEBUG
1940 insint(d, "SO_DEBUG", SO_DEBUG);
1941 #endif
1942 #ifdef SO_ACCEPTCONN
1943 insint(d, "SO_ACCEPTCONN", SO_ACCEPTCONN);
1944 #endif
1945 #ifdef SO_REUSEADDR
1946 insint(d, "SO_REUSEADDR", SO_REUSEADDR);
1947 #endif
1948 #ifdef SO_KEEPALIVE
1949 insint(d, "SO_KEEPALIVE", SO_KEEPALIVE);
1950 #endif
1951 #ifdef SO_DONTROUTE
1952 insint(d, "SO_DONTROUTE", SO_DONTROUTE);
1953 #endif
1954 #ifdef SO_BROADCAST
1955 insint(d, "SO_BROADCAST", SO_BROADCAST);
1956 #endif
1957 #ifdef SO_USELOOPBACK
1958 insint(d, "SO_USELOOPBACK", SO_USELOOPBACK);
1959 #endif
1960 #ifdef SO_LINGER
1961 insint(d, "SO_LINGER", SO_LINGER);
1962 #endif
1963 #ifdef SO_OOBINLINE
1964 insint(d, "SO_OOBINLINE", SO_OOBINLINE);
1965 #endif
1966 #ifdef SO_REUSEPORT
1967 insint(d, "SO_REUSEPORT", SO_REUSEPORT);
1968 #endif
1970 #ifdef SO_SNDBUF
1971 insint(d, "SO_SNDBUF", SO_SNDBUF);
1972 #endif
1973 #ifdef SO_RCVBUF
1974 insint(d, "SO_RCVBUF", SO_RCVBUF);
1975 #endif
1976 #ifdef SO_SNDLOWAT
1977 insint(d, "SO_SNDLOWAT", SO_SNDLOWAT);
1978 #endif
1979 #ifdef SO_RCVLOWAT
1980 insint(d, "SO_RCVLOWAT", SO_RCVLOWAT);
1981 #endif
1982 #ifdef SO_SNDTIMEO
1983 insint(d, "SO_SNDTIMEO", SO_SNDTIMEO);
1984 #endif
1985 #ifdef SO_RCVTIMEO
1986 insint(d, "SO_RCVTIMEO", SO_RCVTIMEO);
1987 #endif
1988 #ifdef SO_ERROR
1989 insint(d, "SO_ERROR", SO_ERROR);
1990 #endif
1991 #ifdef SO_TYPE
1992 insint(d, "SO_TYPE", SO_TYPE);
1993 #endif
1995 /* Maximum number of connections for "listen" */
1996 #ifdef SOMAXCONN
1997 insint(d, "SOMAXCONN", SOMAXCONN);
1998 #else
1999 insint(d, "SOMAXCONN", 5); /* Common value */
2000 #endif
2002 /* Flags for send, recv */
2003 #ifdef MSG_OOB
2004 insint(d, "MSG_OOB", MSG_OOB);
2005 #endif
2006 #ifdef MSG_PEEK
2007 insint(d, "MSG_PEEK", MSG_PEEK);
2008 #endif
2009 #ifdef MSG_DONTROUTE
2010 insint(d, "MSG_DONTROUTE", MSG_DONTROUTE);
2011 #endif
2012 #ifdef MSG_EOR
2013 insint(d, "MSG_EOR", MSG_EOR);
2014 #endif
2015 #ifdef MSG_TRUNC
2016 insint(d, "MSG_TRUNC", MSG_TRUNC);
2017 #endif
2018 #ifdef MSG_CTRUNC
2019 insint(d, "MSG_CTRUNC", MSG_CTRUNC);
2020 #endif
2021 #ifdef MSG_WAITALL
2022 insint(d, "MSG_WAITALL", MSG_WAITALL);
2023 #endif
2024 #ifdef MSG_BTAG
2025 insint(d, "MSG_BTAG", MSG_BTAG);
2026 #endif
2027 #ifdef MSG_ETAG
2028 insint(d, "MSG_ETAG", MSG_ETAG);
2029 #endif
2031 /* Protocol level and numbers, usable for [gs]etsockopt */
2032 /* Sigh -- some systems (e.g. Linux) use enums for these. */
2033 #ifdef SOL_SOCKET
2034 insint(d, "SOL_SOCKET", SOL_SOCKET);
2035 #endif
2036 #ifdef IPPROTO_IP
2037 insint(d, "IPPROTO_IP", IPPROTO_IP);
2038 #else
2039 insint(d, "IPPROTO_IP", 0);
2040 #endif
2041 #ifdef IPPROTO_ICMP
2042 insint(d, "IPPROTO_ICMP", IPPROTO_ICMP);
2043 #else
2044 insint(d, "IPPROTO_ICMP", 1);
2045 #endif
2046 #ifdef IPPROTO_IGMP
2047 insint(d, "IPPROTO_IGMP", IPPROTO_IGMP);
2048 #endif
2049 #ifdef IPPROTO_GGP
2050 insint(d, "IPPROTO_GGP", IPPROTO_GGP);
2051 #endif
2052 #ifdef IPPROTO_TCP
2053 insint(d, "IPPROTO_TCP", IPPROTO_TCP);
2054 #else
2055 insint(d, "IPPROTO_TCP", 6);
2056 #endif
2057 #ifdef IPPROTO_EGP
2058 insint(d, "IPPROTO_EGP", IPPROTO_EGP);
2059 #endif
2060 #ifdef IPPROTO_PUP
2061 insint(d, "IPPROTO_PUP", IPPROTO_PUP);
2062 #endif
2063 #ifdef IPPROTO_UDP
2064 insint(d, "IPPROTO_UDP", IPPROTO_UDP);
2065 #else
2066 insint(d, "IPPROTO_UDP", 17);
2067 #endif
2068 #ifdef IPPROTO_IDP
2069 insint(d, "IPPROTO_IDP", IPPROTO_IDP);
2070 #endif
2071 #ifdef IPPROTO_HELLO
2072 insint(d, "IPPROTO_HELLO", IPPROTO_HELLO);
2073 #endif
2074 #ifdef IPPROTO_ND
2075 insint(d, "IPPROTO_ND", IPPROTO_ND);
2076 #endif
2077 #ifdef IPPROTO_TP
2078 insint(d, "IPPROTO_TP", IPPROTO_TP);
2079 #endif
2080 #ifdef IPPROTO_XTP
2081 insint(d, "IPPROTO_XTP", IPPROTO_XTP);
2082 #endif
2083 #ifdef IPPROTO_EON
2084 insint(d, "IPPROTO_EON", IPPROTO_EON);
2085 #endif
2086 #ifdef IPPROTO_BIP
2087 insint(d, "IPPROTO_BIP", IPPROTO_BIP);
2088 #endif
2089 /**/
2090 #ifdef IPPROTO_RAW
2091 insint(d, "IPPROTO_RAW", IPPROTO_RAW);
2092 #else
2093 insint(d, "IPPROTO_RAW", 255);
2094 #endif
2095 #ifdef IPPROTO_MAX
2096 insint(d, "IPPROTO_MAX", IPPROTO_MAX);
2097 #endif
2099 /* Some port configuration */
2100 #ifdef IPPORT_RESERVED
2101 insint(d, "IPPORT_RESERVED", IPPORT_RESERVED);
2102 #else
2103 insint(d, "IPPORT_RESERVED", 1024);
2104 #endif
2105 #ifdef IPPORT_USERRESERVED
2106 insint(d, "IPPORT_USERRESERVED", IPPORT_USERRESERVED);
2107 #else
2108 insint(d, "IPPORT_USERRESERVED", 5000);
2109 #endif
2111 /* Some reserved IP v.4 addresses */
2112 #ifdef INADDR_ANY
2113 insint(d, "INADDR_ANY", INADDR_ANY);
2114 #else
2115 insint(d, "INADDR_ANY", 0x00000000);
2116 #endif
2117 #ifdef INADDR_BROADCAST
2118 insint(d, "INADDR_BROADCAST", INADDR_BROADCAST);
2119 #else
2120 insint(d, "INADDR_BROADCAST", 0xffffffff);
2121 #endif
2122 #ifdef INADDR_LOOPBACK
2123 insint(d, "INADDR_LOOPBACK", INADDR_LOOPBACK);
2124 #else
2125 insint(d, "INADDR_LOOPBACK", 0x7F000001);
2126 #endif
2127 #ifdef INADDR_UNSPEC_GROUP
2128 insint(d, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
2129 #else
2130 insint(d, "INADDR_UNSPEC_GROUP", 0xe0000000);
2131 #endif
2132 #ifdef INADDR_ALLHOSTS_GROUP
2133 insint(d, "INADDR_ALLHOSTS_GROUP", INADDR_ALLHOSTS_GROUP);
2134 #else
2135 insint(d, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
2136 #endif
2137 #ifdef INADDR_MAX_LOCAL_GROUP
2138 insint(d, "INADDR_MAX_LOCAL_GROUP", INADDR_MAX_LOCAL_GROUP);
2139 #else
2140 insint(d, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
2141 #endif
2142 #ifdef INADDR_NONE
2143 insint(d, "INADDR_NONE", INADDR_NONE);
2144 #else
2145 insint(d, "INADDR_NONE", 0xffffffff);
2146 #endif
2148 /* IP [gs]etsockopt options */
2149 #ifdef IP_OPTIONS
2150 insint(d, "IP_OPTIONS", IP_OPTIONS);
2151 #endif
2152 #ifdef IP_HDRINCL
2153 insint(d, "IP_HDRINCL", IP_HDRINCL);
2154 #endif
2155 #ifdef IP_TOS
2156 insint(d, "IP_TOS", IP_TOS);
2157 #endif
2158 #ifdef IP_TTL
2159 insint(d, "IP_TTL", IP_TTL);
2160 #endif
2161 #ifdef IP_RECVOPTS
2162 insint(d, "IP_RECVOPTS", IP_RECVOPTS);
2163 #endif
2164 #ifdef IP_RECVRETOPTS
2165 insint(d, "IP_RECVRETOPTS", IP_RECVRETOPTS);
2166 #endif
2167 #ifdef IP_RECVDSTADDR
2168 insint(d, "IP_RECVDSTADDR", IP_RECVDSTADDR);
2169 #endif
2170 #ifdef IP_RETOPTS
2171 insint(d, "IP_RETOPTS", IP_RETOPTS);
2172 #endif
2173 #ifdef IP_MULTICAST_IF
2174 insint(d, "IP_MULTICAST_IF", IP_MULTICAST_IF);
2175 #endif
2176 #ifdef IP_MULTICAST_TTL
2177 insint(d, "IP_MULTICAST_TTL", IP_MULTICAST_TTL);
2178 #endif
2179 #ifdef IP_MULTICAST_LOOP
2180 insint(d, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
2181 #endif
2182 #ifdef IP_ADD_MEMBERSHIP
2183 insint(d, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
2184 #endif
2185 #ifdef IP_DROP_MEMBERSHIP
2186 insint(d, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
2187 #endif
2189 /* Initialize gethostbyname lock */
2190 #if defined(WITH_THREAD) && !defined(HAVE_GETHOSTBYNAME_R) && !defined(MS_WINDOWS)
2191 gethostbyname_lock = PyThread_allocate_lock();
2192 #endif