home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / py2s152.zip / Modules / socketmodule.c < prev    next >
C/C++ Source or Header  |  1999-06-27  |  61KB  |  2,278 lines

  1. /***********************************************************
  2. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
  3. The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  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.
  16.  
  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.
  20.  
  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.
  29.  
  30. ******************************************************************/
  31.  
  32. /* Socket module */
  33.  
  34. /*
  35. This module provides an interface to Berkeley socket IPC.
  36.  
  37. Limitations:
  38.  
  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
  42.  
  43. Module interface:
  44.  
  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
  62.  
  63. Socket methods:
  64.  
  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>"
  85.  
  86. */
  87.  
  88. #include "Python.h"
  89.  
  90. #undef HAVE_GETHOSTBYNAME_R_3_ARG
  91. #undef HAVE_GETHOSTBYNAME_R_5_ARG
  92. #undef HAVE_GETHOSTBYNAME_R_6_ARG
  93.  
  94. #ifndef WITH_THREAD
  95. #undef HAVE_GETHOSTBYNAME_R
  96. #endif
  97.  
  98. #ifdef HAVE_GETHOSTBYNAME_R
  99. #if defined(_AIX) || defined(__osf__)
  100. #define HAVE_GETHOSTBYNAME_R_3_ARG
  101. #elif defined(__sun__) || defined(__sgi)
  102. #define HAVE_GETHOSTBYNAME_R_5_ARG
  103. #elif defined(linux)
  104. #define HAVE_GETHOSTBYNAME_R_6_ARG
  105. #else
  106. #undef HAVE_GETHOSTBYNAME_R
  107. #endif
  108. #endif
  109.  
  110. #if !defined(HAVE_GETHOSTBYNAME_R) && defined(WITH_THREAD) && !defined(MS_WINDOWS)
  111. #define USE_GETHOSTBYNAME_LOCK
  112. #endif
  113.  
  114. #ifdef USE_GETHOSTBYNAME_LOCK
  115. #include "pythread.h"
  116. #endif
  117.  
  118. #ifdef HAVE_UNISTD_H
  119. #include <unistd.h>
  120. #endif
  121.  
  122. #if !defined(MS_WINDOWS) && !defined(PYOS_OS2) && !defined(__BEOS__)
  123. extern int gethostname(); /* For Solaris, at least */
  124. #endif
  125.  
  126. #if defined(PYCC_VACPP)
  127. #include <types.h>
  128. #include <io.h>
  129. #include <sys/ioctl.h>
  130. #include <utils.h>
  131. #include <ctype.h>
  132. #endif
  133.  
  134. #if defined(PYOS_OS2)
  135. #define  INCL_DOS
  136. #define  INCL_DOSERRORS
  137. #define  INCL_NOPMAPI
  138. #include <os2.h>
  139. #endif
  140.  
  141. #if defined(__BEOS__)
  142. /* It's in the libs, but not the headers... - [cjh] */
  143. int shutdown( int, int );
  144. #endif
  145.  
  146. #include <sys/types.h>
  147. #include "mytime.h"
  148.  
  149. #include <signal.h>
  150. #ifndef MS_WINDOWS
  151. #include <netdb.h>
  152. #include <sys/socket.h>
  153. #include <netinet/in.h>
  154. #include <fcntl.h>
  155. #else
  156. #include <winsock.h>
  157. #include <fcntl.h>
  158. #endif
  159. #ifdef HAVE_SYS_UN_H
  160. #include <sys/un.h>
  161. #else
  162. #undef AF_UNIX
  163. #endif
  164.  
  165. #ifndef O_NDELAY
  166. #define O_NDELAY O_NONBLOCK    /* For QNX only? */
  167. #endif
  168.  
  169. #ifdef USE_GUSI
  170. /* fdopen() isn't declared in stdio.h (sigh) */
  171. #include <GUSI.h>
  172. #endif
  173.  
  174.  
  175. /* Here we have some hacks to choose between K&R or ANSI style function
  176.    definitions.  For NT to build this as an extension module (ie, DLL)
  177.    it must be compiled by the C++ compiler, as it takes the address of
  178.    a static data item exported from the main Python DLL.
  179. */
  180. #if defined(MS_WINDOWS) || defined(__BEOS__)
  181. /* BeOS suffers from the same socket dichotomy as Win32... - [cjh] */
  182. /* seem to be a few differences in the API */
  183. #define close closesocket
  184. #define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */
  185. #define FORCE_ANSI_FUNC_DEFS
  186. #endif
  187.  
  188. #if defined(PYOS_OS2)
  189. #define close soclose
  190. #define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
  191. #define FORCE_ANSI_FUNC_DEFS
  192. #endif
  193.  
  194. #ifdef FORCE_ANSI_FUNC_DEFS
  195. #define BUILD_FUNC_DEF_1( fnname, arg1type, arg1name )    \
  196. fnname( arg1type arg1name )
  197.  
  198. #define BUILD_FUNC_DEF_2( fnname, arg1type, arg1name, arg2type, arg2name ) \
  199. fnname( arg1type arg1name, arg2type arg2name )
  200.  
  201. #define BUILD_FUNC_DEF_3( fnname, arg1type, arg1name, arg2type, arg2name , arg3type, arg3name )    \
  202. fnname( arg1type arg1name, arg2type arg2name, arg3type arg3name )
  203.  
  204. #define BUILD_FUNC_DEF_4( fnname, arg1type, arg1name, arg2type, arg2name , arg3type, arg3name, arg4type, arg4name )    \
  205. fnname( arg1type arg1name, arg2type arg2name, arg3type arg3name, arg4type arg4name )
  206.  
  207. #else /* !FORCE_ANSI_FN_DEFS */
  208. #define BUILD_FUNC_DEF_1( fnname, arg1type, arg1name )    \
  209. fnname( arg1name )    \
  210.     arg1type arg1name;
  211.  
  212. #define BUILD_FUNC_DEF_2( fnname, arg1type, arg1name, arg2type, arg2name ) \
  213. fnname( arg1name, arg2name )    \
  214.     arg1type arg1name;    \
  215.     arg2type arg2name;
  216.  
  217. #define BUILD_FUNC_DEF_3( fnname, arg1type, arg1name, arg2type, arg2name, arg3type, arg3name ) \
  218. fnname( arg1name, arg2name, arg3name )    \
  219.     arg1type arg1name;    \
  220.     arg2type arg2name;    \
  221.     arg3type arg3name;
  222.  
  223. #define BUILD_FUNC_DEF_4( fnname, arg1type, arg1name, arg2type, arg2name, arg3type, arg3name, arg4type, arg4name ) \
  224. fnname( arg1name, arg2name, arg3name, arg4name )    \
  225.     arg1type arg1name;    \
  226.     arg2type arg2name;    \
  227.     arg3type arg3name;    \
  228.     arg4type arg4name;
  229.  
  230. #endif /* !FORCE_ANSI_FN_DEFS */
  231.  
  232. /* Global variable holding the exception type for errors detected
  233.    by this module (but not argument type or memory errors, etc.). */
  234.  
  235. static PyObject *PySocket_Error;
  236.  
  237.  
  238. /* Convenience function to raise an error according to errno
  239.    and return a NULL pointer from a function. */
  240.  
  241. static PyObject *
  242. PySocket_Err()
  243. {
  244. #ifdef MS_WINDOWS
  245.     if (WSAGetLastError()) {
  246.         PyObject *v;
  247.         v = Py_BuildValue("(is)", WSAGetLastError(), "winsock error");
  248.         if (v != NULL) {
  249.             PyErr_SetObject(PySocket_Error, v);
  250.             Py_DECREF(v);
  251.         }
  252.         return NULL;
  253.     }
  254.     else
  255. #endif
  256.  
  257. #if defined(PYOS_OS2)
  258.     if (sock_errno() != NO_ERROR) {
  259.         APIRET rc;
  260.         ULONG  msglen;
  261.         char   outbuf[100];
  262.         int    myerrorcode = sock_errno();
  263.  
  264.         /* Retrieve Socket-Related Error Message from MPTN.MSG File */
  265.         rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf),
  266.                            myerrorcode - SOCBASEERR + 26, "mptn.msg", &msglen);
  267.         if (rc == NO_ERROR) {
  268.             PyObject *v;
  269.  
  270.             outbuf[msglen] = '\0'; /* OS/2 Doesn't Guarantee a Terminator */
  271.             if (strlen(outbuf) > 0) { /* If Non-Empty Msg, Trim CRLF */
  272.                 char *lastc = &outbuf[ strlen(outbuf)-1 ];
  273.                 while (lastc > outbuf && isspace(*lastc))
  274.                     *lastc-- = '\0'; /* Trim Trailing Whitespace (CRLF) */
  275.             }
  276.             v = Py_BuildValue("(is)", myerrorcode, outbuf);
  277.             if (v != NULL) {
  278.                 PyErr_SetObject(PySocket_Error, v);
  279.                 Py_DECREF(v);
  280.             }
  281.             return NULL;
  282.         }
  283.     }
  284. #endif
  285.  
  286.     return PyErr_SetFromErrno(PySocket_Error);
  287. }
  288.  
  289.  
  290. /* The object holding a socket.  It holds some extra information,
  291.    like the address family, which is used to decode socket address
  292.    arguments properly. */
  293.  
  294. typedef struct {
  295.     PyObject_HEAD
  296.     int sock_fd;        /* Socket file descriptor */
  297.     int sock_family;    /* Address family, e.g., AF_INET */
  298.     int sock_type;        /* Socket type, e.g., SOCK_STREAM */
  299.     int sock_proto;        /* Protocol type, usually 0 */
  300.     union sock_addr {
  301.         struct sockaddr_in in;
  302. #ifdef AF_UNIX
  303.         struct sockaddr_un un;
  304. #endif
  305.     } sock_addr;
  306. } PySocketSockObject;
  307.  
  308.  
  309. /* A forward reference to the Socktype type object.
  310.    The Socktype variable contains pointers to various functions,
  311.    some of which call newsockobject(), which uses Socktype, so
  312.    there has to be a circular reference. */
  313.  
  314. staticforward PyTypeObject PySocketSock_Type;
  315.  
  316.  
  317. /* Create a new socket object.
  318.    This just creates the object and initializes it.
  319.    If the creation fails, return NULL and set an exception (implicit
  320.    in NEWOBJ()). */
  321.  
  322. static PySocketSockObject *
  323. BUILD_FUNC_DEF_4(PySocketSock_New,int,fd, int,family, int,type, int,proto)
  324. {
  325.     PySocketSockObject *s;
  326.     PySocketSock_Type.ob_type = &PyType_Type;
  327.     s = PyObject_NEW(PySocketSockObject, &PySocketSock_Type);
  328.     if (s != NULL) {
  329.         s->sock_fd = fd;
  330.         s->sock_family = family;
  331.         s->sock_type = type;
  332.         s->sock_proto = proto;
  333.     }
  334.     return s;
  335. }
  336.  
  337.  
  338. /* Lock to allow python interpreter to continue, but only allow one 
  339.    thread to be in gethostbyname */
  340. #ifdef USE_GETHOSTBYNAME_LOCK
  341. PyThread_type_lock gethostbyname_lock;
  342. #endif
  343.  
  344.  
  345. /* Convert a string specifying a host name or one of a few symbolic
  346.    names to a numeric IP address.  This usually calls gethostbyname()
  347.    to do the work; the names "" and "<broadcast>" are special.
  348.    Return the length (should always be 4 bytes), or negative if
  349.    an error occurred; then an exception is raised. */
  350.  
  351. static int
  352. BUILD_FUNC_DEF_2(setipaddr, char*,name, struct sockaddr_in *,addr_ret)
  353. {
  354.     struct hostent *hp;
  355.     int d1, d2, d3, d4;
  356.     int h_length;
  357.     char ch;
  358. #ifdef HAVE_GETHOSTBYNAME_R
  359.     struct hostent hp_allocated;
  360. #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
  361.     struct hostent_data data;
  362. #else
  363.     char buf[1001];
  364.     int buf_len = (sizeof buf) - 1;
  365.     int errnop;
  366. #endif
  367. #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
  368.     int result;
  369. #endif
  370. #endif /* HAVE_GETHOSTBYNAME_R */
  371.  
  372.     memset((void *) addr_ret, '\0', sizeof(*addr_ret));
  373.     if (name[0] == '\0') {
  374.         addr_ret->sin_addr.s_addr = INADDR_ANY;
  375.         return 4;
  376.     }
  377.     if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
  378.         addr_ret->sin_addr.s_addr = INADDR_BROADCAST;
  379.         return 4;
  380.     }
  381.     if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 &&
  382.         0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 &&
  383.         0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) {
  384.         addr_ret->sin_addr.s_addr = htonl(
  385.             ((long) d1 << 24) | ((long) d2 << 16) |
  386.             ((long) d3 << 8) | ((long) d4 << 0));
  387.         return 4;
  388.     }
  389.     Py_BEGIN_ALLOW_THREADS
  390. #ifdef HAVE_GETHOSTBYNAME_R
  391. #if    defined(HAVE_GETHOSTBYNAME_R_6_ARG)
  392.     result = gethostbyname_r(name, &hp_allocated, buf, buf_len, &hp, &errnop);
  393. #elif  defined(HAVE_GETHOSTBYNAME_R_5_ARG)
  394.     hp = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
  395. #else  /* HAVE_GETHOSTBYNAME_R_3_ARG */
  396.     memset((void *) &data, '\0', sizeof(data));
  397.     result = gethostbyname_r(name, &hp_allocated, &data);
  398.     hp = (result != 0) ? NULL : &hp_allocated;
  399. #endif
  400. #else /* not HAVE_GETHOSTBYNAME_R */
  401. #ifdef USE_GETHOSTBYNAME_LOCK
  402.     PyThread_acquire_lock(gethostbyname_lock, 1);
  403. #endif
  404.     hp = gethostbyname(name);
  405. #endif /* HAVE_GETHOSTBYNAME_R */
  406.     Py_END_ALLOW_THREADS
  407.  
  408.     if (hp == NULL) {
  409. #ifdef HAVE_HSTRERROR
  410.             /* Let's get real error message to return */
  411.             extern int h_errno;
  412.         PyErr_SetString(PySocket_Error, (char *)hstrerror(h_errno));
  413. #else
  414.         PyErr_SetString(PySocket_Error, "host not found");
  415. #endif
  416. #ifdef USE_GETHOSTBYNAME_LOCK
  417.         PyThread_release_lock(gethostbyname_lock);
  418. #endif
  419.         return -1;
  420.     }
  421.     memcpy((char *) &addr_ret->sin_addr, hp->h_addr, hp->h_length);
  422.     h_length = hp->h_length;
  423. #ifdef USE_GETHOSTBYNAME_LOCK
  424.     PyThread_release_lock(gethostbyname_lock);
  425. #endif
  426.     return h_length;
  427. }
  428.  
  429.  
  430. /* Create a string object representing an IP address.
  431.    This is always a string of the form 'dd.dd.dd.dd' (with variable
  432.    size numbers). */
  433.  
  434. static PyObject *
  435. BUILD_FUNC_DEF_1(makeipaddr, struct sockaddr_in *,addr)
  436. {
  437.     long x = ntohl(addr->sin_addr.s_addr);
  438.     char buf[100];
  439.     sprintf(buf, "%d.%d.%d.%d",
  440.         (int) (x>>24) & 0xff, (int) (x>>16) & 0xff,
  441.         (int) (x>> 8) & 0xff, (int) (x>> 0) & 0xff);
  442.     return PyString_FromString(buf);
  443. }
  444.  
  445.  
  446. /* Create an object representing the given socket address,
  447.    suitable for passing it back to bind(), connect() etc.
  448.    The family field of the sockaddr structure is inspected
  449.    to determine what kind of address it really is. */
  450.  
  451. /*ARGSUSED*/
  452. static PyObject *
  453. BUILD_FUNC_DEF_2(makesockaddr,struct sockaddr *,addr, int,addrlen)
  454. {
  455.     if (addrlen == 0) {
  456.         /* No address -- may be recvfrom() from known socket */
  457.         Py_INCREF(Py_None);
  458.         return Py_None;
  459.     }
  460.  
  461. #ifdef __BEOS__
  462.     /* XXX: BeOS version of accept() doesn't set family coreectly */
  463.     addr->sa_family = AF_INET;
  464. #endif
  465.  
  466.     switch (addr->sa_family) {
  467.  
  468.     case AF_INET:
  469.     {
  470.         struct sockaddr_in *a = (struct sockaddr_in *) addr;
  471.         PyObject *addrobj = makeipaddr(a);
  472.         PyObject *ret = NULL;
  473.         if (addrobj) {
  474.             ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
  475.             Py_DECREF(addrobj);
  476.         }
  477.         return ret;
  478.     }
  479.  
  480. #ifdef AF_UNIX
  481.     case AF_UNIX:
  482.     {
  483.         struct sockaddr_un *a = (struct sockaddr_un *) addr;
  484.         return PyString_FromString(a->sun_path);
  485.     }
  486. #endif /* AF_UNIX */
  487.  
  488.     /* More cases here... */
  489.  
  490.     default:
  491.         /* If we don't know the address family, don't raise an
  492.            exception -- return it as a tuple. */
  493.         return Py_BuildValue("is#",
  494.                      addr->sa_family,
  495.                      addr->sa_data,
  496.                      sizeof(addr->sa_data));
  497.  
  498.     }
  499. }
  500.  
  501.  
  502. /* Parse a socket address argument according to the socket object's
  503.    address family.  Return 1 if the address was in the proper format,
  504.    0 of not.  The address is returned through addr_ret, its length
  505.    through len_ret. */
  506.  
  507. static int
  508. BUILD_FUNC_DEF_4(
  509. getsockaddrarg,PySocketSockObject *,s, PyObject *,args, struct sockaddr **,addr_ret, int *,len_ret)
  510. {
  511.     switch (s->sock_family) {
  512.  
  513. #ifdef AF_UNIX
  514.     case AF_UNIX:
  515.     {
  516.         struct sockaddr_un* addr;
  517.         char *path;
  518.         int len;
  519.         addr = (struct sockaddr_un* )&(s->sock_addr).un;
  520.         if (!PyArg_Parse(args, "t#", &path, &len))
  521.             return 0;
  522.         if (len > sizeof addr->sun_path) {
  523.             PyErr_SetString(PySocket_Error,
  524.                     "AF_UNIX path too long");
  525.             return 0;
  526.         }
  527.         addr->sun_family = AF_UNIX;
  528.         memcpy(addr->sun_path, path, len);
  529.         addr->sun_path[len] = 0;
  530.         *addr_ret = (struct sockaddr *) addr;
  531.         *len_ret = len + sizeof(*addr) - sizeof(addr->sun_path);
  532.         return 1;
  533.     }
  534. #endif /* AF_UNIX */
  535.  
  536.     case AF_INET:
  537.     {
  538.         struct sockaddr_in* addr;
  539.         char *host;
  540.         int port;
  541.          addr=(struct sockaddr_in*)&(s->sock_addr).in;
  542.         if (!PyArg_Parse(args, "(si)", &host, &port))
  543.             return 0;
  544.         if (setipaddr(host, addr) < 0)
  545.             return 0;
  546.         addr->sin_family = AF_INET;
  547.         addr->sin_port = htons((short)port);
  548.         *addr_ret = (struct sockaddr *) addr;
  549.         *len_ret = sizeof *addr;
  550.         return 1;
  551.     }
  552.  
  553.     /* More cases here... */
  554.  
  555.     default:
  556.         PyErr_SetString(PySocket_Error, "getsockaddrarg: bad family");
  557.         return 0;
  558.  
  559.     }
  560. }
  561.  
  562.  
  563. /* Get the address length according to the socket object's address family. 
  564.    Return 1 if the family is known, 0 otherwise.  The length is returned
  565.    through len_ret. */
  566.  
  567. static int
  568. BUILD_FUNC_DEF_2(getsockaddrlen,PySocketSockObject *,s, int *,len_ret)
  569. {
  570.     switch (s->sock_family) {
  571.  
  572. #ifdef AF_UNIX
  573.     case AF_UNIX:
  574.     {
  575.         *len_ret = sizeof (struct sockaddr_un);
  576.         return 1;
  577.     }
  578. #endif /* AF_UNIX */
  579.  
  580.     case AF_INET:
  581.     {
  582.         *len_ret = sizeof (struct sockaddr_in);
  583.         return 1;
  584.     }
  585.  
  586.     /* More cases here... */
  587.  
  588.     default:
  589.         PyErr_SetString(PySocket_Error, "getsockaddrarg: bad family");
  590.         return 0;
  591.  
  592.     }
  593. }
  594.  
  595.  
  596. /* s.accept() method */
  597.  
  598. static PyObject *
  599. BUILD_FUNC_DEF_2(PySocketSock_accept,PySocketSockObject *,s, PyObject *,args)
  600. {
  601.     char addrbuf[256];
  602.     int addrlen, newfd;
  603.     PyObject *sock = NULL;
  604.     PyObject *addr = NULL;
  605.     PyObject *res = NULL;
  606.  
  607.     if (!PyArg_NoArgs(args))
  608.         return NULL;
  609.     if (!getsockaddrlen(s, &addrlen))
  610.         return NULL;
  611.     Py_BEGIN_ALLOW_THREADS
  612.     newfd = accept(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
  613.     Py_END_ALLOW_THREADS
  614.     if (newfd < 0)
  615.         return PySocket_Err();
  616.  
  617.     /* Create the new object with unspecified family,
  618.        to avoid calls to bind() etc. on it. */
  619.     sock = (PyObject *) PySocketSock_New(newfd,
  620.                     s->sock_family,
  621.                     s->sock_type,
  622.                     s->sock_proto);
  623.     if (sock == NULL) {
  624.         close(newfd);
  625.         goto finally;
  626.     }
  627.     if (!(addr = makesockaddr((struct sockaddr *) addrbuf, addrlen)))
  628.         goto finally;
  629.  
  630.     if (!(res = Py_BuildValue("OO", sock, addr)))
  631.         goto finally;
  632.  
  633.   finally:
  634.     Py_XDECREF(sock);
  635.     Py_XDECREF(addr);
  636.     return res;
  637. }
  638.  
  639. static char accept_doc[] =
  640. "accept() -> (socket object, address info)\n\
  641. \n\
  642. Wait for an incoming connection.  Return a new socket representing the\n\
  643. connection, and the address of the client.  For IP sockets, the address\n\
  644. info is a pair (hostaddr, port).";
  645.  
  646.  
  647. /* s.setblocking(1 | 0) method */
  648.  
  649. static PyObject *
  650. BUILD_FUNC_DEF_2(PySocketSock_setblocking,PySocketSockObject*,s,PyObject*,args)
  651. {
  652.     int block;
  653. #ifndef MS_WINDOWS
  654.     int delay_flag;
  655. #endif
  656.     if (!PyArg_Parse(args, "i", &block))
  657.         return NULL;
  658.     Py_BEGIN_ALLOW_THREADS
  659. #ifdef __BEOS__
  660.     block = !block;
  661.     setsockopt( s->sock_fd, SOL_SOCKET, SO_NONBLOCK,
  662.                 (void *)(&block), sizeof( int ) );
  663. #else
  664. #ifndef MS_WINDOWS
  665. #ifdef PYOS_OS2
  666.     block = !block;
  667.     ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block));
  668. #else /* !PYOS_OS2 */
  669.     delay_flag = fcntl (s->sock_fd, F_GETFL, 0);
  670.     if (block)
  671.         delay_flag &= (~O_NDELAY);
  672.     else
  673.         delay_flag |= O_NDELAY;
  674.     fcntl (s->sock_fd, F_SETFL, delay_flag);
  675. #endif /* !PYOS_OS2 */
  676. #else /* MS_WINDOWS */
  677.     block = !block;
  678.     ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
  679. #endif /* MS_WINDOWS */
  680. #endif /* __BEOS__ */
  681.     Py_END_ALLOW_THREADS
  682.  
  683.     Py_INCREF(Py_None);
  684.     return Py_None;
  685. }
  686.  
  687. static char setblocking_doc[] =
  688. "setblocking(flag)\n\
  689. \n\
  690. Set the socket to blocking (flag is true) or non-blocking (false).\n\
  691. This uses the FIONBIO ioctl with the O_NDELAY flag.";
  692.  
  693.  
  694. /* s.setsockopt() method.
  695.    With an integer third argument, sets an integer option.
  696.    With a string third argument, sets an option from a buffer;
  697.    use optional built-in module 'struct' to encode the string. */
  698.  
  699. static PyObject *
  700. BUILD_FUNC_DEF_2(PySocketSock_setsockopt,PySocketSockObject *,s, PyObject *,args)
  701. {
  702.     int level;
  703.     int optname;
  704.     int res;
  705.     char *buf;
  706.     int buflen;
  707.     int flag;
  708.  
  709.     if (PyArg_Parse(args, "(iii)", &level, &optname, &flag)) {
  710.         buf = (char *) &flag;
  711.         buflen = sizeof flag;
  712.     }
  713.     else {
  714.         PyErr_Clear();
  715.         if (!PyArg_Parse(args, "(iis#)", &level, &optname,
  716.                  &buf, &buflen))
  717.             return NULL;
  718.     }
  719.     res = setsockopt(s->sock_fd, level, optname, (ANY *)buf, buflen);
  720.     if (res < 0)
  721.         return PySocket_Err();
  722.     Py_INCREF(Py_None);
  723.     return Py_None;
  724. }
  725.  
  726. static char setsockopt_doc[] =
  727. "setsockopt(level, option, value)\n\
  728. \n\
  729. Set a socket option.  See the Unix manual for level and option.\n\
  730. The value argument can either be an integer or a string.";
  731.  
  732.  
  733. /* s.getsockopt() method.
  734.    With two arguments, retrieves an integer option.
  735.    With a third integer argument, retrieves a string buffer of that size;
  736.    use optional built-in module 'struct' to decode the string. */
  737.  
  738. static PyObject *
  739. BUILD_FUNC_DEF_2(PySocketSock_getsockopt,PySocketSockObject *,s, PyObject *,args)
  740. {
  741.     int level;
  742.     int optname;
  743.     int res;
  744.     PyObject *buf;
  745.     int buflen = 0;
  746.  
  747. #ifdef __BEOS__
  748. /* We have incomplete socket support. */
  749.     PyErr_SetString( PySocket_Error, "getsockopt not supported" );
  750.     return NULL;
  751. #else
  752.  
  753.     if (!PyArg_ParseTuple(args, "ii|i", &level, &optname, &buflen))
  754.         return NULL;
  755.     
  756.     if (buflen == 0) {
  757.         int flag = 0;
  758.         int flagsize = sizeof flag;
  759.         res = getsockopt(s->sock_fd, level, optname,
  760.                  (ANY *)&flag, &flagsize);
  761.         if (res < 0)
  762.             return PySocket_Err();
  763.         return PyInt_FromLong(flag);
  764.     }
  765.     if (buflen <= 0 || buflen > 1024) {
  766.         PyErr_SetString(PySocket_Error,
  767.                 "getsockopt buflen out of range");
  768.         return NULL;
  769.     }
  770.     buf = PyString_FromStringAndSize((char *)NULL, buflen);
  771.     if (buf == NULL)
  772.         return NULL;
  773.     res = getsockopt(s->sock_fd, level, optname,
  774.              (ANY *)PyString_AsString(buf), &buflen);
  775.     if (res < 0) {
  776.         Py_DECREF(buf);
  777.         return PySocket_Err();
  778.     }
  779.     _PyString_Resize(&buf, buflen);
  780.     return buf;
  781. #endif /* __BEOS__ */
  782. }
  783.  
  784. static char getsockopt_doc[] =
  785. "getsockopt(level, option[, buffersize]) -> value\n\
  786. \n\
  787. Get a socket option.  See the Unix manual for level and option.\n\
  788. If a nonzero buffersize argument is given, the return value is a\n\
  789. string of that length; otherwise it is an integer.";
  790.  
  791.  
  792. /* s.bind(sockaddr) method */
  793.  
  794. static PyObject *
  795. BUILD_FUNC_DEF_2(PySocketSock_bind,PySocketSockObject *,s, PyObject *,args)
  796. {
  797.     struct sockaddr *addr;
  798.     int addrlen;
  799.     int res;
  800.     if (!getsockaddrarg(s, args, &addr, &addrlen))
  801.         return NULL;
  802.     Py_BEGIN_ALLOW_THREADS
  803.     res = bind(s->sock_fd, addr, addrlen);
  804.     Py_END_ALLOW_THREADS
  805.     if (res < 0)
  806.         return PySocket_Err();
  807.     Py_INCREF(Py_None);
  808.     return Py_None;
  809. }
  810.  
  811. static char bind_doc[] =
  812. "bind(address)\n\
  813. \n\
  814. Bind the socket to a local address.  For IP sockets, the address is a\n\
  815. pair (host, port); the host must refer to the local host.";
  816.  
  817.  
  818. /* s.close() method.
  819.    Set the file descriptor to -1 so operations tried subsequently
  820.    will surely fail. */
  821.  
  822. static PyObject *
  823. BUILD_FUNC_DEF_2(PySocketSock_close,PySocketSockObject *,s, PyObject *,args)
  824. {
  825.     if (!PyArg_NoArgs(args))
  826.         return NULL;
  827.     if (s->sock_fd != -1) {
  828.         Py_BEGIN_ALLOW_THREADS
  829.         (void) close(s->sock_fd);
  830.         Py_END_ALLOW_THREADS
  831.     }
  832.     s->sock_fd = -1;
  833.     Py_INCREF(Py_None);
  834.     return Py_None;
  835. }
  836.  
  837. static char close_doc[] =
  838. "close()\n\
  839. \n\
  840. Close the socket.  It cannot be used after this call.";
  841.  
  842.  
  843. /* s.connect(sockaddr) method */
  844.  
  845. static PyObject *
  846. BUILD_FUNC_DEF_2(PySocketSock_connect,PySocketSockObject *,s, PyObject *,args)
  847. {
  848.     struct sockaddr *addr;
  849.     int addrlen;
  850.     int res;
  851.     if (!getsockaddrarg(s, args, &addr, &addrlen))
  852.         return NULL;
  853.     Py_BEGIN_ALLOW_THREADS
  854.     res = connect(s->sock_fd, addr, addrlen);
  855.     Py_END_ALLOW_THREADS
  856.     if (res < 0)
  857.         return PySocket_Err();
  858.     Py_INCREF(Py_None);
  859.     return Py_None;
  860. }
  861.  
  862. static char connect_doc[] =
  863. "connect(address)\n\
  864. \n\
  865. Connect the socket to a remote address.  For IP sockets, the address\n\
  866. is a pair (host, port).";
  867.  
  868.  
  869. /* s.connect_ex(sockaddr) method */
  870.  
  871. static PyObject *
  872. BUILD_FUNC_DEF_2(PySocketSock_connect_ex,PySocketSockObject *,s, PyObject *,args)
  873. {
  874.     struct sockaddr *addr;
  875.     int addrlen;
  876.     int res;
  877.     if (!getsockaddrarg(s, args, &addr, &addrlen))
  878.         return NULL;
  879.     Py_BEGIN_ALLOW_THREADS
  880.     res = connect(s->sock_fd, addr, addrlen);
  881.     Py_END_ALLOW_THREADS
  882.     if (res != 0)
  883.         res = errno;
  884.     return PyInt_FromLong((long) res);
  885. }
  886.  
  887. static char connect_ex_doc[] =
  888. "connect_ex(address)\n\
  889. \n\
  890. This is like connect(address), but returns an error code (the errno value)\n\
  891. instead of raising an exception when an error occurs.";
  892.  
  893.  
  894. /* s.fileno() method */
  895.  
  896. static PyObject *
  897. BUILD_FUNC_DEF_2(PySocketSock_fileno,PySocketSockObject *,s, PyObject *,args)
  898. {
  899.     if (!PyArg_NoArgs(args))
  900.         return NULL;
  901.     return PyInt_FromLong((long) s->sock_fd);
  902. }
  903.  
  904. static char fileno_doc[] =
  905. "fileno() -> integer\n\
  906. \n\
  907. Return the integer file descriptor of the socket.";
  908.  
  909.  
  910. #ifndef NO_DUP
  911. /* s.dup() method */
  912.  
  913. static PyObject *
  914. BUILD_FUNC_DEF_2(PySocketSock_dup,PySocketSockObject *,s, PyObject *,args)
  915. {
  916.     int newfd;
  917.     PyObject *sock;
  918.     if (!PyArg_NoArgs(args))
  919.         return NULL;
  920.     newfd = dup(s->sock_fd);
  921.     if (newfd < 0)
  922.         return PySocket_Err();
  923.     sock = (PyObject *) PySocketSock_New(newfd,
  924.                          s->sock_family,
  925.                          s->sock_type,
  926.                          s->sock_proto);
  927.     if (sock == NULL)
  928.         close(newfd);
  929.     return sock;
  930. }
  931.  
  932. static char dup_doc[] =
  933. "dup() -> socket object\n\
  934. \n\
  935. Return a new socket object connected to the same system resource.";
  936.  
  937. #endif
  938.  
  939.  
  940. /* s.getsockname() method */
  941.  
  942. static PyObject *
  943. BUILD_FUNC_DEF_2(PySocketSock_getsockname,PySocketSockObject *,s, PyObject *,args)
  944. {
  945.     char addrbuf[256];
  946.     int addrlen, res;
  947.     if (!PyArg_NoArgs(args))
  948.         return NULL;
  949.     if (!getsockaddrlen(s, &addrlen))
  950.         return NULL;
  951.     memset(addrbuf, 0, addrlen);
  952.     Py_BEGIN_ALLOW_THREADS
  953.     res = getsockname(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
  954.     Py_END_ALLOW_THREADS
  955.     if (res < 0)
  956.         return PySocket_Err();
  957.     return makesockaddr((struct sockaddr *) addrbuf, addrlen);
  958. }
  959.  
  960. static char getsockname_doc[] =
  961. "getsockname() -> address info\n\
  962. \n\
  963. Return the address of the local endpoint.  For IP sockets, the address\n\
  964. info is a pair (hostaddr, port).";
  965.  
  966.  
  967. #ifdef HAVE_GETPEERNAME        /* Cray APP doesn't have this :-( */
  968. /* s.getpeername() method */
  969.  
  970. static PyObject *
  971. BUILD_FUNC_DEF_2(PySocketSock_getpeername,PySocketSockObject *,s, PyObject *,args)
  972. {
  973.     char addrbuf[256];
  974.     int addrlen, res;
  975.     if (!PyArg_NoArgs(args))
  976.         return NULL;
  977.     if (!getsockaddrlen(s, &addrlen))
  978.         return NULL;
  979.     Py_BEGIN_ALLOW_THREADS
  980.     res = getpeername(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
  981.     Py_END_ALLOW_THREADS
  982.     if (res < 0)
  983.         return PySocket_Err();
  984.     return makesockaddr((struct sockaddr *) addrbuf, addrlen);
  985. }
  986.  
  987. static char getpeername_doc[] =
  988. "getpeername() -> address info\n\
  989. \n\
  990. Return the address of the remote endpoint.  For IP sockets, the address\n\
  991. info is a pair (hostaddr, port).";
  992.  
  993. #endif /* HAVE_GETPEERNAME */
  994.  
  995.  
  996. /* s.listen(n) method */
  997.  
  998. static PyObject *
  999. BUILD_FUNC_DEF_2(PySocketSock_listen,PySocketSockObject *,s, PyObject *,args)
  1000. {
  1001.     int backlog;
  1002.     int res;
  1003.     if (!PyArg_Parse(args, "i", &backlog))
  1004.         return NULL;
  1005.     Py_BEGIN_ALLOW_THREADS
  1006.     if (backlog < 1)
  1007.         backlog = 1;
  1008.     res = listen(s->sock_fd, backlog);
  1009.     Py_END_ALLOW_THREADS
  1010.     if (res < 0)
  1011.         return PySocket_Err();
  1012.     Py_INCREF(Py_None);
  1013.     return Py_None;
  1014. }
  1015.  
  1016. static char listen_doc[] =
  1017. "listen(backlog)\n\
  1018. \n\
  1019. Enable a server to accept connections.  The backlog argument must be at\n\
  1020. least 1; it specifies the number of unaccepted connection that the system\n\
  1021. will allow before refusing new connections.";
  1022.  
  1023.  
  1024. #ifndef NO_DUP
  1025. /* s.makefile(mode) method.
  1026.    Create a new open file object referring to a dupped version of
  1027.    the socket's file descriptor.  (The dup() call is necessary so
  1028.    that the open file and socket objects may be closed independent
  1029.    of each other.)
  1030.    The mode argument specifies 'r' or 'w' passed to fdopen(). */
  1031.  
  1032. static PyObject *
  1033. BUILD_FUNC_DEF_2(PySocketSock_makefile,PySocketSockObject *,s, PyObject *,args)
  1034. {
  1035.     extern int fclose Py_PROTO((FILE *));
  1036.     char *mode = "r";
  1037.     int bufsize = -1;
  1038.     int fd;
  1039.     FILE *fp;
  1040.     PyObject *f;
  1041.  
  1042.     if (!PyArg_ParseTuple(args, "|si", &mode, &bufsize))
  1043.         return NULL;
  1044. #ifdef MS_WIN32
  1045.     if (((fd = _open_osfhandle(s->sock_fd, _O_BINARY)) < 0) ||
  1046.         ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL))
  1047. #else
  1048.     if ((fd = dup(s->sock_fd)) < 0 || (fp = fdopen(fd, mode)) == NULL)
  1049. #endif
  1050.     {
  1051.         if (fd >= 0)
  1052.             close(fd);
  1053.         return PySocket_Err();
  1054.     }
  1055.     f = PyFile_FromFile(fp, "<socket>", mode, fclose);
  1056.     if (f != NULL)
  1057.         PyFile_SetBufSize(f, bufsize);
  1058.     return f;
  1059. }
  1060.  
  1061. static char makefile_doc[] =
  1062. "makefile([mode[, buffersize]]) -> file object\n\
  1063. \n\
  1064. Return a regular file object corresponding to the socket.\n\
  1065. The mode and buffersize arguments are as for the built-in open() function.";
  1066.  
  1067. #endif /* NO_DUP */
  1068.  
  1069.  
  1070. /* s.recv(nbytes [,flags]) method */
  1071.  
  1072. static PyObject *
  1073. BUILD_FUNC_DEF_2(PySocketSock_recv,PySocketSockObject *,s, PyObject *,args)
  1074. {
  1075.     int len, n, flags = 0;
  1076.     PyObject *buf;
  1077.     if (!PyArg_ParseTuple(args, "i|i", &len, &flags))
  1078.         return NULL;
  1079.     buf = PyString_FromStringAndSize((char *) 0, len);
  1080.     if (buf == NULL)
  1081.         return NULL;
  1082.     Py_BEGIN_ALLOW_THREADS
  1083.     n = recv(s->sock_fd, PyString_AsString(buf), len, flags);
  1084.     Py_END_ALLOW_THREADS
  1085.     if (n < 0) {
  1086.         Py_DECREF(buf);
  1087.         return PySocket_Err();
  1088.     }
  1089.     if (n != len && _PyString_Resize(&buf, n) < 0)
  1090.         return NULL;
  1091.     return buf;
  1092. }
  1093.  
  1094. static char recv_doc[] =
  1095. "recv(buffersize[, flags]) -> data\n\
  1096. \n\
  1097. Receive up to buffersize bytes from the socket.  For the optional flags\n\
  1098. argument, see the Unix manual.  When no data is available, block until\n\
  1099. at least one byte is available or until the remote end is closed.  When\n\
  1100. the remote end is closed and all data is read, return the empty string.";
  1101.  
  1102.  
  1103. /* s.recvfrom(nbytes [,flags]) method */
  1104.  
  1105. static PyObject *
  1106. BUILD_FUNC_DEF_2(PySocketSock_recvfrom,PySocketSockObject *,s, PyObject *,args)
  1107. {
  1108.     char addrbuf[256];
  1109.     PyObject *buf = NULL;
  1110.     PyObject *addr = NULL;
  1111.     PyObject *ret = NULL;
  1112.  
  1113.     int addrlen, len, n, flags = 0;
  1114.     if (!PyArg_ParseTuple(args, "i|i", &len, &flags))
  1115.         return NULL;
  1116.     if (!getsockaddrlen(s, &addrlen))
  1117.         return NULL;
  1118.     buf = PyString_FromStringAndSize((char *) 0, len);
  1119.     if (buf == NULL)
  1120.         return NULL;
  1121.     Py_BEGIN_ALLOW_THREADS
  1122.     n = recvfrom(s->sock_fd, PyString_AsString(buf), len, flags,
  1123. #ifndef MS_WINDOWS
  1124. #if defined(PYOS_OS2)
  1125.              (struct sockaddr *)addrbuf, &addrlen
  1126. #else
  1127.              (ANY *)addrbuf, &addrlen
  1128. #endif
  1129. #else
  1130.              (struct sockaddr *)addrbuf, &addrlen
  1131. #endif
  1132.              );
  1133.     Py_END_ALLOW_THREADS
  1134.     if (n < 0) {
  1135.         Py_DECREF(buf);
  1136.         return PySocket_Err();
  1137.     }
  1138.     if (n != len && _PyString_Resize(&buf, n) < 0)
  1139.         return NULL;
  1140.         
  1141.     if (!(addr = makesockaddr((struct sockaddr *)addrbuf, addrlen)))
  1142.         goto finally;
  1143.  
  1144.     ret = Py_BuildValue("OO", buf, addr);
  1145.   finally:
  1146.     Py_XDECREF(addr);
  1147.     Py_XDECREF(buf);
  1148.     return ret;
  1149. }
  1150.  
  1151. static char recvfrom_doc[] =
  1152. "recvfrom(buffersize[, flags]) -> (data, address info)\n\
  1153. \n\
  1154. Like recv(buffersize, flags) but also return the sender's address info.";
  1155.  
  1156.  
  1157. /* s.send(data [,flags]) method */
  1158.  
  1159. static PyObject *
  1160. BUILD_FUNC_DEF_2(PySocketSock_send,PySocketSockObject *,s, PyObject *,args)
  1161. {
  1162.     char *buf;
  1163.     int len, n, flags = 0;
  1164.     if (!PyArg_ParseTuple(args, "s#|i", &buf, &len, &flags))
  1165.         return NULL;
  1166.     Py_BEGIN_ALLOW_THREADS
  1167.     n = send(s->sock_fd, buf, len, flags);
  1168.     Py_END_ALLOW_THREADS
  1169.     if (n < 0)
  1170.         return PySocket_Err();
  1171.     return PyInt_FromLong((long)n);
  1172. }
  1173.  
  1174. static char send_doc[] =
  1175. "send(data[, flags])\n\
  1176. \n\
  1177. Send a data string to the socket.  For the optional flags\n\
  1178. argument, see the Unix manual.";
  1179.  
  1180.  
  1181. /* s.sendto(data, [flags,] sockaddr) method */
  1182.  
  1183. static PyObject *
  1184. BUILD_FUNC_DEF_2(PySocketSock_sendto,PySocketSockObject *,s, PyObject *,args)
  1185. {
  1186.     PyObject *addro;
  1187.     char *buf;
  1188.     struct sockaddr *addr;
  1189.     int addrlen, len, n, flags;
  1190.     flags = 0;
  1191.     if (!PyArg_Parse(args, "(s#O)", &buf, &len, &addro)) {
  1192.         PyErr_Clear();
  1193.         if (!PyArg_Parse(args, "(s#iO)", &buf, &len, &flags, &addro))
  1194.             return NULL;
  1195.     }
  1196.     if (!getsockaddrarg(s, addro, &addr, &addrlen))
  1197.         return NULL;
  1198.     Py_BEGIN_ALLOW_THREADS
  1199.     n = sendto(s->sock_fd, buf, len, flags, addr, addrlen);
  1200.     Py_END_ALLOW_THREADS
  1201.     if (n < 0)
  1202.         return PySocket_Err();
  1203.     return PyInt_FromLong((long)n);
  1204. }
  1205.  
  1206. static char sendto_doc[] =
  1207. "sendto(data[, flags], address)\n\
  1208. \n\
  1209. Like send(data, flags) but allows specifying the destination address.\n\
  1210. For IP sockets, the address is a pair (hostaddr, port).";
  1211.  
  1212.  
  1213. /* s.shutdown(how) method */
  1214.  
  1215. static PyObject *
  1216. BUILD_FUNC_DEF_2(PySocketSock_shutdown,PySocketSockObject *,s, PyObject *,args)
  1217. {
  1218.     int how;
  1219.     int res;
  1220.     if (!PyArg_Parse(args, "i", &how))
  1221.         return NULL;
  1222.     Py_BEGIN_ALLOW_THREADS
  1223.     res = shutdown(s->sock_fd, how);
  1224.     Py_END_ALLOW_THREADS
  1225.     if (res < 0)
  1226.         return PySocket_Err();
  1227.     Py_INCREF(Py_None);
  1228.     return Py_None;
  1229. }
  1230.  
  1231. static char shutdown_doc[] =
  1232. "shutdown(flag)\n\
  1233. \n\
  1234. Shut down the reading side of the socket (flag == 0), the writing side\n\
  1235. of the socket (flag == 1), or both ends (flag == 2).";
  1236.  
  1237.  
  1238. /* List of methods for socket objects */
  1239.  
  1240. static PyMethodDef PySocketSock_methods[] = {
  1241.     {"accept",        (PyCFunction)PySocketSock_accept, 0,
  1242.                 accept_doc},
  1243.     {"bind",        (PyCFunction)PySocketSock_bind, 0,
  1244.                 bind_doc},
  1245.     {"close",        (PyCFunction)PySocketSock_close, 0,
  1246.                 close_doc},
  1247.     {"connect",        (PyCFunction)PySocketSock_connect, 0,
  1248.                 connect_doc},
  1249.     {"connect_ex",        (PyCFunction)PySocketSock_connect_ex, 0,
  1250.                 connect_ex_doc},
  1251. #ifndef NO_DUP
  1252.     {"dup",            (PyCFunction)PySocketSock_dup, 0,
  1253.                 dup_doc},
  1254. #endif
  1255.     {"fileno",        (PyCFunction)PySocketSock_fileno, 0,
  1256.                 fileno_doc},
  1257. #ifdef HAVE_GETPEERNAME
  1258.     {"getpeername",        (PyCFunction)PySocketSock_getpeername, 0,
  1259.                 getpeername_doc},
  1260. #endif
  1261.     {"getsockname",        (PyCFunction)PySocketSock_getsockname, 0,
  1262.                 getsockname_doc},
  1263.     {"getsockopt",        (PyCFunction)PySocketSock_getsockopt, 1,
  1264.                 getsockopt_doc},
  1265.     {"listen",        (PyCFunction)PySocketSock_listen, 0,
  1266.                 listen_doc},
  1267. #ifndef NO_DUP
  1268.     {"makefile",        (PyCFunction)PySocketSock_makefile, 1,
  1269.                 makefile_doc},
  1270. #endif
  1271.     {"recv",        (PyCFunction)PySocketSock_recv, 1,
  1272.                 recv_doc},
  1273.     {"recvfrom",        (PyCFunction)PySocketSock_recvfrom, 1,
  1274.                 recvfrom_doc},
  1275.     {"send",        (PyCFunction)PySocketSock_send, 1,
  1276.                 send_doc},
  1277.     {"sendto",        (PyCFunction)PySocketSock_sendto, 0,
  1278.                 sendto_doc},
  1279.     {"setblocking",        (PyCFunction)PySocketSock_setblocking, 0,
  1280.                 setblocking_doc},
  1281.     {"setsockopt",        (PyCFunction)PySocketSock_setsockopt, 0,
  1282.                 setsockopt_doc},
  1283.     {"shutdown",        (PyCFunction)PySocketSock_shutdown, 0,
  1284.                 shutdown_doc},
  1285.     {NULL,            NULL}        /* sentinel */
  1286. };
  1287.  
  1288.  
  1289. /* Deallocate a socket object in response to the last Py_DECREF().
  1290.    First close the file description. */
  1291.  
  1292. static void
  1293. BUILD_FUNC_DEF_1(PySocketSock_dealloc,PySocketSockObject *,s)
  1294. {
  1295.     (void) close(s->sock_fd);
  1296.     PyMem_DEL(s);
  1297. }
  1298.  
  1299.  
  1300. /* Return a socket object's named attribute. */
  1301.  
  1302. static PyObject *
  1303. BUILD_FUNC_DEF_2(PySocketSock_getattr,PySocketSockObject *,s, char *,name)
  1304. {
  1305.     return Py_FindMethod(PySocketSock_methods, (PyObject *) s, name);
  1306. }
  1307.  
  1308.  
  1309. static PyObject *
  1310. BUILD_FUNC_DEF_1(PySocketSock_repr,PySocketSockObject *,s)
  1311. {
  1312.     char buf[512];
  1313.     sprintf(buf, 
  1314.         "<socket object, fd=%d, family=%d, type=%d, protocol=%d>", 
  1315.         s->sock_fd, s->sock_family, s->sock_type, s->sock_proto);
  1316.     return PyString_FromString(buf);
  1317. }
  1318.  
  1319.  
  1320. /* Type object for socket objects. */
  1321.  
  1322. static PyTypeObject PySocketSock_Type = {
  1323.     PyObject_HEAD_INIT(0)    /* Must fill in type value later */
  1324.     0,
  1325.     "socket",
  1326.     sizeof(PySocketSockObject),
  1327.     0,
  1328.     (destructor)PySocketSock_dealloc, /*tp_dealloc*/
  1329.     0,        /*tp_print*/
  1330.     (getattrfunc)PySocketSock_getattr, /*tp_getattr*/
  1331.     0,        /*tp_setattr*/
  1332.     0,        /*tp_compare*/
  1333.     (reprfunc)PySocketSock_repr, /*tp_repr*/
  1334.     0,        /*tp_as_number*/
  1335.     0,        /*tp_as_sequence*/
  1336.     0,        /*tp_as_mapping*/
  1337. };
  1338.  
  1339.  
  1340. /* Python interface to gethostname(). */
  1341.  
  1342. /*ARGSUSED*/
  1343. static PyObject *
  1344. BUILD_FUNC_DEF_2(PySocket_gethostname,PyObject *,self, PyObject *,args)
  1345. {
  1346.     char buf[1024];
  1347.     int res;
  1348.     if (!PyArg_NoArgs(args))
  1349.         return NULL;
  1350.     Py_BEGIN_ALLOW_THREADS
  1351.     res = gethostname(buf, (int) sizeof buf - 1);
  1352.     Py_END_ALLOW_THREADS
  1353.     if (res < 0)
  1354.         return PySocket_Err();
  1355.     buf[sizeof buf - 1] = '\0';
  1356.     return PyString_FromString(buf);
  1357. }
  1358.  
  1359. static char gethostname_doc[] =
  1360. "gethostname() -> string\n\
  1361. \n\
  1362. Return the current host name.";
  1363.  
  1364.  
  1365. /* Python interface to gethostbyname(name). */
  1366.  
  1367. /*ARGSUSED*/
  1368. static PyObject *
  1369. BUILD_FUNC_DEF_2(PySocket_gethostbyname,PyObject *,self, PyObject *,args)
  1370. {
  1371.     char *name;
  1372.     struct sockaddr_in addrbuf;
  1373.     if (!PyArg_Parse(args, "s", &name))
  1374.         return NULL;
  1375.     if (setipaddr(name, &addrbuf) < 0)
  1376.         return NULL;
  1377.     return makeipaddr(&addrbuf);
  1378. }
  1379.  
  1380. static char gethostbyname_doc[] =
  1381. "gethostbyname(host) -> address\n\
  1382. \n\
  1383. Return the IP address (a string of the form '255.255.255.255') for a host.";
  1384.  
  1385.  
  1386. /* Convenience function common to gethostbyname_ex and gethostbyaddr */
  1387.  
  1388. static PyObject *
  1389. gethost_common(h, addr)
  1390.     struct hostent *h;
  1391.     struct sockaddr_in *addr;
  1392. {
  1393.     char **pch;
  1394.     PyObject *rtn_tuple = (PyObject *)NULL;
  1395.     PyObject *name_list = (PyObject *)NULL;
  1396.     PyObject *addr_list = (PyObject *)NULL;
  1397.     PyObject *tmp;
  1398.     if (h == NULL) {
  1399. #ifdef HAVE_HSTRERROR
  1400.             /* Let's get real error message to return */
  1401.             extern int h_errno;
  1402.         PyErr_SetString(PySocket_Error, (char *)hstrerror(h_errno));
  1403. #else
  1404.         PyErr_SetString(PySocket_Error, "host not found");
  1405. #endif
  1406.         return NULL;
  1407.     }
  1408.     if ((name_list = PyList_New(0)) == NULL)
  1409.         goto err;
  1410.     if ((addr_list = PyList_New(0)) == NULL)
  1411.         goto err;
  1412.     for (pch = h->h_aliases; *pch != NULL; pch++) {
  1413.         int status;
  1414.         tmp = PyString_FromString(*pch);
  1415.         if (tmp == NULL)
  1416.             goto err;
  1417.         status = PyList_Append(name_list, tmp);
  1418.         Py_DECREF(tmp);
  1419.         if (status)
  1420.             goto err;
  1421.     }
  1422.     for (pch = h->h_addr_list; *pch != NULL; pch++) {
  1423.         int status;
  1424.         memcpy((char *) &addr->sin_addr, *pch, h->h_length);
  1425.         tmp = makeipaddr(addr);
  1426.         if (tmp == NULL)
  1427.             goto err;
  1428.         status = PyList_Append(addr_list, tmp);
  1429.         Py_DECREF(tmp);
  1430.         if (status)
  1431.             goto err;
  1432.     }
  1433.     rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list);
  1434.  err:
  1435.     Py_XDECREF(name_list);
  1436.     Py_XDECREF(addr_list);
  1437.     return rtn_tuple;
  1438. }
  1439.  
  1440.  
  1441. /* Python interface to gethostbyname_ex(name). */
  1442.  
  1443. /*ARGSUSED*/
  1444. static PyObject *
  1445. BUILD_FUNC_DEF_2(PySocket_gethostbyname_ex,PyObject *,self, PyObject *,args)
  1446. {
  1447.     char *name;
  1448.     struct hostent *h;
  1449.     struct sockaddr_in addr;
  1450.     PyObject *ret;
  1451. #ifdef HAVE_GETHOSTBYNAME_R
  1452.     struct hostent hp_allocated;
  1453. #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
  1454.     struct hostent_data data;
  1455. #else
  1456.     char buf[16384];
  1457.     int buf_len = (sizeof buf) - 1;
  1458.     int errnop;
  1459. #endif
  1460. #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
  1461.     int result;
  1462. #endif
  1463. #endif /* HAVE_GETHOSTBYNAME_R */
  1464.     if (!PyArg_Parse(args, "s", &name))
  1465.         return NULL;
  1466.     if (setipaddr(name, &addr) < 0)
  1467.         return NULL;
  1468.     Py_BEGIN_ALLOW_THREADS
  1469. #ifdef HAVE_GETHOSTBYNAME_R
  1470. #if   defined(HAVE_GETHOSTBYNAME_R_6_ARG)
  1471.     result = gethostbyname_r(name, &hp_allocated, buf, buf_len, &h, &errnop);
  1472. #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
  1473.     h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
  1474. #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
  1475.     memset((void *) &data, '\0', sizeof(data));
  1476.     result = gethostbyname_r(name, &hp_allocated, &data);
  1477.     h = (result != 0) ? NULL : &hp_allocated;
  1478. #endif
  1479. #else /* not HAVE_GETHOSTBYNAME_R */
  1480. #ifdef USE_GETHOSTBYNAME_LOCK
  1481.     PyThread_acquire_lock(gethostbyname_lock, 1);
  1482. #endif
  1483.     h = gethostbyname(name);
  1484. #endif /* HAVE_GETHOSTBYNAME_R */
  1485.     Py_END_ALLOW_THREADS
  1486.     ret = gethost_common(h, &addr);
  1487. #ifdef USE_GETHOSTBYNAME_LOCK
  1488.     PyThread_release_lock(gethostbyname_lock);
  1489. #endif
  1490.     return ret;
  1491. }
  1492.  
  1493. static char ghbn_ex_doc[] =
  1494. "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
  1495. \n\
  1496. Return the true host name, a list of aliases, and a list of IP addresses,\n\
  1497. for a host.  The host argument is a string giving a host name or IP number.";
  1498.  
  1499.  
  1500. /* Python interface to gethostbyaddr(IP). */
  1501.  
  1502. /*ARGSUSED*/
  1503. static PyObject *
  1504. BUILD_FUNC_DEF_2(PySocket_gethostbyaddr,PyObject *,self, PyObject *, args)
  1505. {
  1506.         struct sockaddr_in addr;
  1507.     char *ip_num;
  1508.     struct hostent *h;
  1509.     PyObject *ret;
  1510. #ifdef HAVE_GETHOSTBYNAME_R
  1511.     struct hostent hp_allocated;
  1512. #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
  1513.     struct hostent_data data;
  1514. #else
  1515.     char buf[16384];
  1516.     int buf_len = (sizeof buf) - 1;
  1517.     int errnop;
  1518. #endif
  1519. #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
  1520.     int result;
  1521. #endif
  1522. #endif /* HAVE_GETHOSTBYNAME_R */
  1523.  
  1524.     if (!PyArg_Parse(args, "s", &ip_num))
  1525.         return NULL;
  1526.     if (setipaddr(ip_num, &addr) < 0)
  1527.         return NULL;
  1528.     Py_BEGIN_ALLOW_THREADS
  1529. #ifdef HAVE_GETHOSTBYNAME_R
  1530. #if   defined(HAVE_GETHOSTBYNAME_R_6_ARG)
  1531.     result = gethostbyaddr_r((char *)&addr.sin_addr,
  1532.         sizeof(addr.sin_addr),
  1533.         AF_INET, &hp_allocated, buf, buf_len,
  1534.         &h, &errnop);
  1535. #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
  1536.     h = gethostbyaddr_r((char *)&addr.sin_addr,
  1537.                 sizeof(addr.sin_addr),
  1538.                 AF_INET, 
  1539.                 &hp_allocated, buf, buf_len, &errnop);
  1540. #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
  1541.     memset((void *) &data, '\0', sizeof(data));
  1542.     result = gethostbyaddr_r((char *)&addr.sin_addr,
  1543.         sizeof(addr.sin_addr),
  1544.         AF_INET, &hp_allocated, &data);
  1545.     h = (result != 0) ? NULL : &hp_allocated;
  1546. #endif
  1547. #else /* not HAVE_GETHOSTBYNAME_R */
  1548. #ifdef USE_GETHOSTBYNAME_LOCK
  1549.     PyThread_acquire_lock(gethostbyname_lock, 1);
  1550. #endif
  1551.     h = gethostbyaddr((char *)&addr.sin_addr,
  1552.               sizeof(addr.sin_addr),
  1553.               AF_INET);
  1554. #endif /* HAVE_GETHOSTBYNAME_R */
  1555.     Py_END_ALLOW_THREADS
  1556.     ret = gethost_common(h, &addr);
  1557. #ifdef USE_GETHOSTBYNAME_LOCK
  1558.     PyThread_release_lock(gethostbyname_lock);
  1559. #endif
  1560.     return ret;
  1561. }
  1562.  
  1563. static char gethostbyaddr_doc[] =
  1564. "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
  1565. \n\
  1566. Return the true host name, a list of aliases, and a list of IP addresses,\n\
  1567. for a host.  The host argument is a string giving a host name or IP number.";
  1568.  
  1569.  
  1570. /* Python interface to getservbyname(name).
  1571.    This only returns the port number, since the other info is already
  1572.    known or not useful (like the list of aliases). */
  1573.  
  1574. /*ARGSUSED*/
  1575. static PyObject *
  1576. BUILD_FUNC_DEF_2(PySocket_getservbyname,PyObject *,self, PyObject *,args)
  1577. {
  1578.     char *name, *proto;
  1579.     struct servent *sp;
  1580.     if (!PyArg_Parse(args, "(ss)", &name, &proto))
  1581.         return NULL;
  1582.     Py_BEGIN_ALLOW_THREADS
  1583.     sp = getservbyname(name, proto);
  1584.     Py_END_ALLOW_THREADS
  1585.     if (sp == NULL) {
  1586.         PyErr_SetString(PySocket_Error, "service/proto not found");
  1587.         return NULL;
  1588.     }
  1589.     return PyInt_FromLong((long) ntohs(sp->s_port));
  1590. }
  1591.  
  1592. static char getservbyname_doc[] =
  1593. "getservbyname(servicename, protocolname) -> integer\n\
  1594. \n\
  1595. Return a port number from a service name and protocol name.\n\
  1596. The protocol name should be 'tcp' or 'udp'.";
  1597.  
  1598.  
  1599. /* Python interface to getprotobyname(name).
  1600.    This only returns the protocol number, since the other info is
  1601.    already known or not useful (like the list of aliases). */
  1602.  
  1603. /*ARGSUSED*/
  1604. static PyObject *
  1605. BUILD_FUNC_DEF_2(PySocket_getprotobyname,PyObject *,self, PyObject *,args)
  1606. {
  1607.     char *name;
  1608.     struct protoent *sp;
  1609. #ifdef __BEOS__
  1610. /* Not available in BeOS yet. - [cjh] */
  1611.     PyErr_SetString( PySocket_Error, "getprotobyname not supported" );
  1612.     return NULL;
  1613. #else
  1614.     if (!PyArg_Parse(args, "s", &name))
  1615.         return NULL;
  1616.     Py_BEGIN_ALLOW_THREADS
  1617.     sp = getprotobyname(name);
  1618.     Py_END_ALLOW_THREADS
  1619.     if (sp == NULL) {
  1620.         PyErr_SetString(PySocket_Error, "protocol not found");
  1621.         return NULL;
  1622.     }
  1623.     return PyInt_FromLong((long) sp->p_proto);
  1624. #endif
  1625. }
  1626.  
  1627. static char getprotobyname_doc[] =
  1628. "getprotobyname(name) -> integer\n\
  1629. \n\
  1630. Return the protocol number for the named protocol.  (Rarely used.)";
  1631.  
  1632.  
  1633. /* Python interface to socket(family, type, proto).
  1634.    The third (protocol) argument is optional.
  1635.    Return a new socket object. */
  1636.  
  1637. /*ARGSUSED*/
  1638. static PyObject *
  1639. BUILD_FUNC_DEF_2(PySocket_socket,PyObject *,self, PyObject *,args)
  1640. {
  1641.     PySocketSockObject *s;
  1642. #ifdef MS_WINDOWS
  1643.     SOCKET fd;
  1644. #else
  1645.     int fd;
  1646. #endif
  1647.     int family, type, proto = 0;
  1648.     if (!PyArg_ParseTuple(args, "ii|i", &family, &type, &proto))
  1649.         return NULL;
  1650.     Py_BEGIN_ALLOW_THREADS
  1651.     fd = socket(family, type, proto);
  1652.     Py_END_ALLOW_THREADS
  1653. #ifdef MS_WINDOWS
  1654.     if (fd == INVALID_SOCKET)
  1655. #else
  1656.     if (fd < 0)
  1657. #endif
  1658.         return PySocket_Err();
  1659.     s = PySocketSock_New(fd, family, type, proto);
  1660.     /* If the object can't be created, don't forget to close the
  1661.        file descriptor again! */
  1662.     if (s == NULL)
  1663.         (void) close(fd);
  1664.     /* From now on, ignore SIGPIPE and let the error checking
  1665.        do the work. */
  1666. #ifdef SIGPIPE      
  1667.     (void) signal(SIGPIPE, SIG_IGN);
  1668. #endif   
  1669.     return (PyObject *) s;
  1670. }
  1671.  
  1672. static char socket_doc[] =
  1673. "socket(family, type[, proto]) -> socket object\n\
  1674. \n\
  1675. Open a socket of the given type.  The family argument specifies the\n\
  1676. address family; it is normally AF_INET, sometimes AF_UNIX.\n\
  1677. The type argument specifies whether this is a stream (SOCK_STREAM)\n\
  1678. or datagram (SOCK_DGRAM) socket.  The protocol argument defaults to 0,\n\
  1679. specifying the default protocol.";
  1680.  
  1681.  
  1682. #ifndef NO_DUP
  1683. /* Create a socket object from a numeric file description.
  1684.    Useful e.g. if stdin is a socket.
  1685.    Additional arguments as for socket(). */
  1686.  
  1687. /*ARGSUSED*/
  1688. static PyObject *
  1689. BUILD_FUNC_DEF_2(PySocket_fromfd,PyObject *,self, PyObject *,args)
  1690. {
  1691.     PySocketSockObject *s;
  1692.     int fd, family, type, proto = 0;
  1693.     if (!PyArg_ParseTuple(args, "iii|i", &fd, &family, &type, &proto))
  1694.         return NULL;
  1695.     /* Dup the fd so it and the socket can be closed independently */
  1696.     fd = dup(fd);
  1697.     if (fd < 0)
  1698.         return PySocket_Err();
  1699.     s = PySocketSock_New(fd, family, type, proto);
  1700.     /* From now on, ignore SIGPIPE and let the error checking
  1701.        do the work. */
  1702. #ifdef SIGPIPE      
  1703.     (void) signal(SIGPIPE, SIG_IGN);
  1704. #endif   
  1705.     return (PyObject *) s;
  1706. }
  1707.  
  1708. static char fromfd_doc[] =
  1709. "fromfd(fd, family, type[, proto]) -> socket object\n\
  1710. \n\
  1711. Create a socket object from the given file descriptor.\n\
  1712. The remaining arguments are the same as for socket().";
  1713.  
  1714. #endif /* NO_DUP */
  1715.  
  1716.  
  1717. static PyObject *
  1718. BUILD_FUNC_DEF_2(PySocket_ntohs, PyObject *, self, PyObject *, args)
  1719. {
  1720.     int x1, x2;
  1721.  
  1722.     if (!PyArg_Parse(args, "i", &x1)) {
  1723.         return NULL;
  1724.     }
  1725.     x2 = (int)ntohs((short)x1);
  1726.     return PyInt_FromLong(x2);
  1727. }
  1728.  
  1729. static char ntohs_doc[] =
  1730. "ntohs(integer) -> integer\n\
  1731. \n\
  1732. Convert a 16-bit integer from network to host byte order.";
  1733.  
  1734.  
  1735. static PyObject *
  1736. BUILD_FUNC_DEF_2(PySocket_ntohl, PyObject *, self, PyObject *, args)
  1737. {
  1738.     int x1, x2;
  1739.  
  1740.     if (!PyArg_Parse(args, "i", &x1)) {
  1741.         return NULL;
  1742.     }
  1743.     x2 = ntohl(x1);
  1744.     return PyInt_FromLong(x2);
  1745. }
  1746.  
  1747. static char ntohl_doc[] =
  1748. "ntohl(integer) -> integer\n\
  1749. \n\
  1750. Convert a 32-bit integer from network to host byte order.";
  1751.  
  1752.  
  1753. static PyObject *
  1754. BUILD_FUNC_DEF_2(PySocket_htons, PyObject *, self, PyObject *, args)
  1755. {
  1756.     int x1, x2;
  1757.  
  1758.     if (!PyArg_Parse(args, "i", &x1)) {
  1759.         return NULL;
  1760.     }
  1761.     x2 = (int)htons((short)x1);
  1762.     return PyInt_FromLong(x2);
  1763. }
  1764.  
  1765. static char htons_doc[] =
  1766. "htons(integer) -> integer\n\
  1767. \n\
  1768. Convert a 16-bit integer from host to network byte order.";
  1769.  
  1770.  
  1771. static PyObject *
  1772. BUILD_FUNC_DEF_2(PySocket_htonl, PyObject *, self, PyObject *, args)
  1773. {
  1774.     int x1, x2;
  1775.  
  1776.     if (!PyArg_Parse(args, "i", &x1)) {
  1777.         return NULL;
  1778.     }
  1779.     x2 = htonl(x1);
  1780.     return PyInt_FromLong(x2);
  1781. }
  1782.  
  1783. static char htonl_doc[] =
  1784. "htonl(integer) -> integer\n\
  1785. \n\
  1786. Convert a 32-bit integer from host to network byte order.";
  1787.  
  1788.  
  1789. /* List of functions exported by this module. */
  1790.  
  1791. static PyMethodDef PySocket_methods[] = {
  1792.     {"gethostbyname",    PySocket_gethostbyname, 0, gethostbyname_doc},
  1793.     {"gethostbyname_ex",    PySocket_gethostbyname_ex, 0, ghbn_ex_doc},
  1794.     {"gethostbyaddr",    PySocket_gethostbyaddr, 0, gethostbyaddr_doc},
  1795.     {"gethostname",        PySocket_gethostname, 0, gethostname_doc},
  1796.     {"getservbyname",    PySocket_getservbyname, 0, getservbyname_doc},
  1797.     {"getprotobyname",    PySocket_getprotobyname, 0,getprotobyname_doc},
  1798.     {"socket",        PySocket_socket, 1, socket_doc},
  1799. #ifndef NO_DUP
  1800.     {"fromfd",        PySocket_fromfd, 1, fromfd_doc},
  1801. #endif
  1802.     {"ntohs",        PySocket_ntohs, 0, ntohs_doc},
  1803.     {"ntohl",        PySocket_ntohl, 0, ntohl_doc},
  1804.     {"htons",        PySocket_htons, 0, htons_doc},
  1805.     {"htonl",        PySocket_htonl, 0, htonl_doc},
  1806.     {NULL,            NULL}         /* Sentinel */
  1807. };
  1808.  
  1809.  
  1810. /* Convenience routine to export an integer value.
  1811.  *
  1812.  * Errors are silently ignored, for better or for worse...
  1813.  */
  1814. static void
  1815. BUILD_FUNC_DEF_3(insint,PyObject *,d, char *,name, int,value)
  1816. {
  1817.     PyObject *v = PyInt_FromLong((long) value);
  1818.     if (!v || PyDict_SetItemString(d, name, v))
  1819.         PyErr_Clear();
  1820.  
  1821.     Py_XDECREF(v);
  1822. }
  1823.  
  1824.  
  1825. #ifdef MS_WINDOWS
  1826.  
  1827. /* Additional initialization and cleanup for NT/Windows */
  1828.  
  1829. static void
  1830. NTcleanup()
  1831. {
  1832.     WSACleanup();
  1833. }
  1834.  
  1835. static int
  1836. NTinit()
  1837. {
  1838.     WSADATA WSAData;
  1839.     int ret;
  1840.     char buf[100];
  1841.     ret = WSAStartup(0x0101, &WSAData);
  1842.     switch (ret) {
  1843.     case 0:    /* no error */
  1844.         atexit(NTcleanup);
  1845.         return 1;
  1846.     case WSASYSNOTREADY:
  1847.         PyErr_SetString(PyExc_ImportError,
  1848.                 "WSAStartup failed: network not ready");
  1849.         break;
  1850.     case WSAVERNOTSUPPORTED:
  1851.     case WSAEINVAL:
  1852.         PyErr_SetString(PyExc_ImportError,
  1853.             "WSAStartup failed: requested version not supported");
  1854.         break;
  1855.     default:
  1856.         sprintf(buf, "WSAStartup failed: error code %d", ret);
  1857.         PyErr_SetString(PyExc_ImportError, buf);
  1858.         break;
  1859.     }
  1860.     return 0;
  1861. }
  1862.  
  1863. #endif /* MS_WINDOWS */
  1864.  
  1865. #if defined(PYOS_OS2)
  1866.  
  1867. /* Additional initialization and cleanup for OS/2 */
  1868.  
  1869. static void
  1870. OS2cleanup()
  1871. {
  1872.     /* No cleanup is necessary for OS/2 Sockets */
  1873. }
  1874.  
  1875. static int
  1876. OS2init()
  1877. {
  1878.     char reason[64];
  1879.     int rc = sock_init();
  1880.  
  1881.     if (rc == 0) {
  1882.         atexit(OS2cleanup);
  1883.         return 1; /* Indicate Success */
  1884.     }
  1885.  
  1886.     sprintf(reason, "OS/2 TCP/IP Error# %d", sock_errno());
  1887.     PyErr_SetString(PyExc_ImportError, reason);
  1888.  
  1889.     return 0;  /* Indicate Failure */
  1890. }
  1891.  
  1892. #endif /* PYOS_OS2 */
  1893.  
  1894.  
  1895. /* Initialize this module.
  1896.  *   This is called when the first 'import socket' is done,
  1897.  *   via a table in config.c, if config.c is compiled with USE_SOCKET
  1898.  *   defined.
  1899.  *
  1900.  *   For MS_WINDOWS (which means any Windows variant), this module
  1901.  *   is actually called "_socket", and there's a wrapper "socket.py"
  1902.  *   which implements some missing functionality (such as makefile(),
  1903.  *   dup() and fromfd()).  The import of "_socket" may fail with an
  1904.  *   ImportError exception if initialization of WINSOCK fails.  When
  1905.  *   WINSOCK is initialized succesfully, a call to WSACleanup() is
  1906.  *   scheduled to be made at exit time.
  1907.  *
  1908.  *   For OS/2, this module is also called "_socket" and uses a wrapper
  1909.  *   "socket.py" which implements that functionality that is missing
  1910.  *   when PC operating systems don't put socket descriptors in the
  1911.  *   operating system's filesystem layer.
  1912.  */
  1913.  
  1914. static char module_doc[] =
  1915. "This module provides socket operations and some related functions.\n\
  1916. On Unix, it supports IP (Internet Protocol) and Unix domain sockets.\n\
  1917. On other systems, it only supports IP.\n\
  1918. \n\
  1919. Functions:\n\
  1920. \n\
  1921. socket() -- create a new socket object\n\
  1922. fromfd() -- create a socket object from an open file descriptor (*)\n\
  1923. gethostname() -- return the current hostname\n\
  1924. gethostbyname() -- map a hostname to its IP number\n\
  1925. gethostbyaddr() -- map an IP number or hostname to DNS info\n\
  1926. getservbyname() -- map a service name and a protocol name to a port number\n\
  1927. getprotobyname() -- mape a protocol name (e.g. 'tcp') to a number\n\
  1928. ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order\n\
  1929. htons(), htonl() -- convert 16, 32 bit int from host to network byte order\n\
  1930. \n\
  1931. (*) not available on all platforms!)\n\
  1932. \n\
  1933. Special objects:\n\
  1934. \n\
  1935. SocketType -- type object for socket objects\n\
  1936. error -- exception raised for I/O errors\n\
  1937. \n\
  1938. Integer constants:\n\
  1939. \n\
  1940. AF_INET, AF_UNIX -- socket domains (first argument to socket() call)\n\
  1941. SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument)\n\
  1942. \n\
  1943. Many other constants may be defined; these may be used in calls to\n\
  1944. the setsockopt() and getsockopt() methods.\n\
  1945. ";
  1946.  
  1947. static char sockettype_doc[] =
  1948. "A socket represents one endpoint of a network connection.\n\
  1949. \n\
  1950. Methods:\n\
  1951. \n\
  1952. accept() -- accept a connection, returning new socket and client address\n\
  1953. bind() -- bind the socket to a local address\n\
  1954. close() -- close the socket\n\
  1955. connect() -- connect the socket to a remote address\n\
  1956. connect_ex() -- connect, return an error code instead of an exception \n\
  1957. dup() -- return a new socket object identical to the current one (*)\n\
  1958. fileno() -- return underlying file descriptor\n\
  1959. getpeername() -- return remote address (*)\n\
  1960. getsockname() -- return local address\n\
  1961. getsockopt() -- get socket options\n\
  1962. listen() -- start listening for incoming connections\n\
  1963. makefile() -- return a file object corresponding tot the socket (*)\n\
  1964. recv() -- receive data\n\
  1965. recvfrom() -- receive data and sender's address\n\
  1966. send() -- send data\n\
  1967. sendto() -- send data to a given address\n\
  1968. setblocking() -- set or clear the blocking I/O flag\n\
  1969. setsockopt() -- set socket options\n\
  1970. shutdown() -- shut down traffic in one or both directions\n\
  1971. \n\
  1972. (*) not available on all platforms!)";
  1973.  
  1974. DL_EXPORT(void)
  1975. #if defined(MS_WINDOWS) || defined(PYOS_OS2) || defined(__BEOS__)
  1976. init_socket()
  1977. #else
  1978. initsocket()
  1979. #endif
  1980. {
  1981.     PyObject *m, *d;
  1982. #ifdef MS_WINDOWS
  1983.     if (!NTinit())
  1984.         return;
  1985.     m = Py_InitModule3("_socket", PySocket_methods, module_doc);
  1986. #else
  1987. #if defined(__TOS_OS2__)
  1988.     if (!OS2init())
  1989.         return;
  1990.     m = Py_InitModule3("_socket", PySocket_methods, module_doc);
  1991. #else
  1992. #if defined(__BEOS__)
  1993.     m = Py_InitModule3("_socket", PySocket_methods, module_doc);
  1994. #else
  1995.     m = Py_InitModule3("socket", PySocket_methods, module_doc);
  1996. #endif /* __BEOS__ */
  1997. #endif
  1998. #endif
  1999.     d = PyModule_GetDict(m);
  2000.     PySocket_Error = PyErr_NewException("socket.error", NULL, NULL);
  2001.     if (PySocket_Error == NULL)
  2002.         return;
  2003.     PyDict_SetItemString(d, "error", PySocket_Error);
  2004.     PySocketSock_Type.ob_type = &PyType_Type;
  2005.     PySocketSock_Type.tp_doc = sockettype_doc;
  2006.     Py_INCREF(&PySocketSock_Type);
  2007.     if (PyDict_SetItemString(d, "SocketType",
  2008.                  (PyObject *)&PySocketSock_Type) != 0)
  2009.         return;
  2010.     insint(d, "AF_INET", AF_INET);
  2011. #ifdef AF_UNIX
  2012.     insint(d, "AF_UNIX", AF_UNIX);
  2013. #endif /* AF_UNIX */
  2014.     insint(d, "SOCK_STREAM", SOCK_STREAM);
  2015.     insint(d, "SOCK_DGRAM", SOCK_DGRAM);
  2016. #ifndef __BEOS__
  2017. /* We have incomplete socket support. */
  2018.     insint(d, "SOCK_RAW", SOCK_RAW);
  2019.     insint(d, "SOCK_SEQPACKET", SOCK_SEQPACKET);
  2020.     insint(d, "SOCK_RDM", SOCK_RDM);
  2021. #endif
  2022.  
  2023. #ifdef    SO_DEBUG
  2024.     insint(d, "SO_DEBUG", SO_DEBUG);
  2025. #endif
  2026. #ifdef    SO_ACCEPTCONN
  2027.     insint(d, "SO_ACCEPTCONN", SO_ACCEPTCONN);
  2028. #endif
  2029. #ifdef    SO_REUSEADDR
  2030.     insint(d, "SO_REUSEADDR", SO_REUSEADDR);
  2031. #endif
  2032. #ifdef    SO_KEEPALIVE
  2033.     insint(d, "SO_KEEPALIVE", SO_KEEPALIVE);
  2034. #endif
  2035. #ifdef    SO_DONTROUTE
  2036.     insint(d, "SO_DONTROUTE", SO_DONTROUTE);
  2037. #endif
  2038. #ifdef    SO_BROADCAST
  2039.     insint(d, "SO_BROADCAST", SO_BROADCAST);
  2040. #endif
  2041. #ifdef    SO_USELOOPBACK
  2042.     insint(d, "SO_USELOOPBACK", SO_USELOOPBACK);
  2043. #endif
  2044. #ifdef    SO_LINGER
  2045.     insint(d, "SO_LINGER", SO_LINGER);
  2046. #endif
  2047. #ifdef    SO_OOBINLINE
  2048.     insint(d, "SO_OOBINLINE", SO_OOBINLINE);
  2049. #endif
  2050. #ifdef    SO_REUSEPORT
  2051.     insint(d, "SO_REUSEPORT", SO_REUSEPORT);
  2052. #endif
  2053.  
  2054. #ifdef    SO_SNDBUF
  2055.     insint(d, "SO_SNDBUF", SO_SNDBUF);
  2056. #endif
  2057. #ifdef    SO_RCVBUF
  2058.     insint(d, "SO_RCVBUF", SO_RCVBUF);
  2059. #endif
  2060. #ifdef    SO_SNDLOWAT
  2061.     insint(d, "SO_SNDLOWAT", SO_SNDLOWAT);
  2062. #endif
  2063. #ifdef    SO_RCVLOWAT
  2064.     insint(d, "SO_RCVLOWAT", SO_RCVLOWAT);
  2065. #endif
  2066. #ifdef    SO_SNDTIMEO
  2067.     insint(d, "SO_SNDTIMEO", SO_SNDTIMEO);
  2068. #endif
  2069. #ifdef    SO_RCVTIMEO
  2070.     insint(d, "SO_RCVTIMEO", SO_RCVTIMEO);
  2071. #endif
  2072. #ifdef    SO_ERROR
  2073.     insint(d, "SO_ERROR", SO_ERROR);
  2074. #endif
  2075. #ifdef    SO_TYPE
  2076.     insint(d, "SO_TYPE", SO_TYPE);
  2077. #endif
  2078.  
  2079.     /* Maximum number of connections for "listen" */
  2080. #ifdef    SOMAXCONN
  2081.     insint(d, "SOMAXCONN", SOMAXCONN);
  2082. #else
  2083.     insint(d, "SOMAXCONN", 5);    /* Common value */
  2084. #endif
  2085.  
  2086.     /* Flags for send, recv */
  2087. #ifdef    MSG_OOB
  2088.     insint(d, "MSG_OOB", MSG_OOB);
  2089. #endif
  2090. #ifdef    MSG_PEEK
  2091.     insint(d, "MSG_PEEK", MSG_PEEK);
  2092. #endif
  2093. #ifdef    MSG_DONTROUTE
  2094.     insint(d, "MSG_DONTROUTE", MSG_DONTROUTE);
  2095. #endif
  2096. #ifdef    MSG_EOR
  2097.     insint(d, "MSG_EOR", MSG_EOR);
  2098. #endif
  2099. #ifdef    MSG_TRUNC
  2100.     insint(d, "MSG_TRUNC", MSG_TRUNC);
  2101. #endif
  2102. #ifdef    MSG_CTRUNC
  2103.     insint(d, "MSG_CTRUNC", MSG_CTRUNC);
  2104. #endif
  2105. #ifdef    MSG_WAITALL
  2106.     insint(d, "MSG_WAITALL", MSG_WAITALL);
  2107. #endif
  2108. #ifdef    MSG_BTAG
  2109.     insint(d, "MSG_BTAG", MSG_BTAG);
  2110. #endif
  2111. #ifdef    MSG_ETAG
  2112.     insint(d, "MSG_ETAG", MSG_ETAG);
  2113. #endif
  2114.  
  2115.     /* Protocol level and numbers, usable for [gs]etsockopt */
  2116. /* Sigh -- some systems (e.g. Linux) use enums for these. */
  2117. #ifdef    SOL_SOCKET
  2118.     insint(d, "SOL_SOCKET", SOL_SOCKET);
  2119. #endif
  2120. #ifdef    IPPROTO_IP
  2121.     insint(d, "IPPROTO_IP", IPPROTO_IP);
  2122. #else
  2123.     insint(d, "IPPROTO_IP", 0);
  2124. #endif
  2125. #ifdef    IPPROTO_ICMP
  2126.     insint(d, "IPPROTO_ICMP", IPPROTO_ICMP);
  2127. #else
  2128.     insint(d, "IPPROTO_ICMP", 1);
  2129. #endif
  2130. #ifdef    IPPROTO_IGMP
  2131.     insint(d, "IPPROTO_IGMP", IPPROTO_IGMP);
  2132. #endif
  2133. #ifdef    IPPROTO_GGP
  2134.     insint(d, "IPPROTO_GGP", IPPROTO_GGP);
  2135. #endif
  2136. #ifdef    IPPROTO_TCP
  2137.     insint(d, "IPPROTO_TCP", IPPROTO_TCP);
  2138. #else
  2139.     insint(d, "IPPROTO_TCP", 6);
  2140. #endif
  2141. #ifdef    IPPROTO_EGP
  2142.     insint(d, "IPPROTO_EGP", IPPROTO_EGP);
  2143. #endif
  2144. #ifdef    IPPROTO_PUP
  2145.     insint(d, "IPPROTO_PUP", IPPROTO_PUP);
  2146. #endif
  2147. #ifdef    IPPROTO_UDP
  2148.     insint(d, "IPPROTO_UDP", IPPROTO_UDP);
  2149. #else
  2150.     insint(d, "IPPROTO_UDP", 17);
  2151. #endif
  2152. #ifdef    IPPROTO_IDP
  2153.     insint(d, "IPPROTO_IDP", IPPROTO_IDP);
  2154. #endif
  2155. #ifdef    IPPROTO_HELLO
  2156.     insint(d, "IPPROTO_HELLO", IPPROTO_HELLO);
  2157. #endif
  2158. #ifdef    IPPROTO_ND
  2159.     insint(d, "IPPROTO_ND", IPPROTO_ND);
  2160. #endif
  2161. #ifdef    IPPROTO_TP
  2162.     insint(d, "IPPROTO_TP", IPPROTO_TP);
  2163. #endif
  2164. #ifdef    IPPROTO_XTP
  2165.     insint(d, "IPPROTO_XTP", IPPROTO_XTP);
  2166. #endif
  2167. #ifdef    IPPROTO_EON
  2168.     insint(d, "IPPROTO_EON", IPPROTO_EON);
  2169. #endif
  2170. #ifdef    IPPROTO_BIP
  2171.     insint(d, "IPPROTO_BIP", IPPROTO_BIP);
  2172. #endif
  2173. /**/
  2174. #ifdef    IPPROTO_RAW
  2175.     insint(d, "IPPROTO_RAW", IPPROTO_RAW);
  2176. #else
  2177.     insint(d, "IPPROTO_RAW", 255);
  2178. #endif
  2179. #ifdef    IPPROTO_MAX
  2180.     insint(d, "IPPROTO_MAX", IPPROTO_MAX);
  2181. #endif
  2182.  
  2183.     /* Some port configuration */
  2184. #ifdef    IPPORT_RESERVED
  2185.     insint(d, "IPPORT_RESERVED", IPPORT_RESERVED);
  2186. #else
  2187.     insint(d, "IPPORT_RESERVED", 1024);
  2188. #endif
  2189. #ifdef    IPPORT_USERRESERVED
  2190.     insint(d, "IPPORT_USERRESERVED", IPPORT_USERRESERVED);
  2191. #else
  2192.     insint(d, "IPPORT_USERRESERVED", 5000);
  2193. #endif
  2194.  
  2195.     /* Some reserved IP v.4 addresses */
  2196. #ifdef    INADDR_ANY
  2197.     insint(d, "INADDR_ANY", INADDR_ANY);
  2198. #else
  2199.     insint(d, "INADDR_ANY", 0x00000000);
  2200. #endif
  2201. #ifdef    INADDR_BROADCAST
  2202.     insint(d, "INADDR_BROADCAST", INADDR_BROADCAST);
  2203. #else
  2204.     insint(d, "INADDR_BROADCAST", 0xffffffff);
  2205. #endif
  2206. #ifdef    INADDR_LOOPBACK
  2207.     insint(d, "INADDR_LOOPBACK", INADDR_LOOPBACK);
  2208. #else
  2209.     insint(d, "INADDR_LOOPBACK", 0x7F000001);
  2210. #endif
  2211. #ifdef    INADDR_UNSPEC_GROUP
  2212.     insint(d, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
  2213. #else
  2214.     insint(d, "INADDR_UNSPEC_GROUP", 0xe0000000);
  2215. #endif
  2216. #ifdef    INADDR_ALLHOSTS_GROUP
  2217.     insint(d, "INADDR_ALLHOSTS_GROUP", INADDR_ALLHOSTS_GROUP);
  2218. #else
  2219.     insint(d, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
  2220. #endif
  2221. #ifdef    INADDR_MAX_LOCAL_GROUP
  2222.     insint(d, "INADDR_MAX_LOCAL_GROUP", INADDR_MAX_LOCAL_GROUP);
  2223. #else
  2224.     insint(d, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
  2225. #endif
  2226. #ifdef    INADDR_NONE
  2227.     insint(d, "INADDR_NONE", INADDR_NONE);
  2228. #else
  2229.     insint(d, "INADDR_NONE", 0xffffffff);
  2230. #endif
  2231.  
  2232.     /* IP [gs]etsockopt options */
  2233. #ifdef    IP_OPTIONS
  2234.     insint(d, "IP_OPTIONS", IP_OPTIONS);
  2235. #endif
  2236. #ifdef    IP_HDRINCL
  2237.     insint(d, "IP_HDRINCL", IP_HDRINCL);
  2238. #endif
  2239. #ifdef    IP_TOS
  2240.     insint(d, "IP_TOS", IP_TOS);
  2241. #endif
  2242. #ifdef    IP_TTL
  2243.     insint(d, "IP_TTL", IP_TTL);
  2244. #endif
  2245. #ifdef    IP_RECVOPTS
  2246.     insint(d, "IP_RECVOPTS", IP_RECVOPTS);
  2247. #endif
  2248. #ifdef    IP_RECVRETOPTS
  2249.     insint(d, "IP_RECVRETOPTS", IP_RECVRETOPTS);
  2250. #endif
  2251. #ifdef    IP_RECVDSTADDR
  2252.     insint(d, "IP_RECVDSTADDR", IP_RECVDSTADDR);
  2253. #endif
  2254. #ifdef    IP_RETOPTS
  2255.     insint(d, "IP_RETOPTS", IP_RETOPTS);
  2256. #endif
  2257. #ifdef    IP_MULTICAST_IF
  2258.     insint(d, "IP_MULTICAST_IF", IP_MULTICAST_IF);
  2259. #endif
  2260. #ifdef    IP_MULTICAST_TTL
  2261.     insint(d, "IP_MULTICAST_TTL", IP_MULTICAST_TTL);
  2262. #endif
  2263. #ifdef    IP_MULTICAST_LOOP
  2264.     insint(d, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
  2265. #endif
  2266. #ifdef    IP_ADD_MEMBERSHIP
  2267.     insint(d, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
  2268. #endif
  2269. #ifdef    IP_DROP_MEMBERSHIP
  2270.     insint(d, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
  2271. #endif
  2272.  
  2273.     /* Initialize gethostbyname lock */
  2274. #ifdef USE_GETHOSTBYNAME_LOCK
  2275.     gethostbyname_lock = PyThread_allocate_lock();
  2276. #endif
  2277. }
  2278.