home *** CD-ROM | disk | FTP | other *** search
/ The Datafile PD-CD 5 / DATAFILE_PDCD5.iso / utilities / p / python / pytexdoc / ext / source / !Python / Modules / c / socketmodu < prev    next >
Encoding:
Text File  |  1996-11-06  |  39.1 KB  |  1,609 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.getservbyname(servicename, protocolname) --> port number
  50. - socket.socket(family, type [, proto]) --> new socket object
  51. - socket.ntohs(16 bit value) --> new int object
  52. - socket.ntohl(32 bit value) --> new int object
  53. - socket.htons(16 bit value) --> new int object
  54. - socket.htonl(32 bit value) --> new int object
  55. - socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
  56. - an Internet socket address is a pair (hostname, port)
  57.   where hostname can be anything recognized by gethostbyname()
  58.   (including the dd.dd.dd.dd notation) and port is in host byte order
  59. - where a hostname is returned, the dd.dd.dd.dd notation is used
  60. - a UNIX domain socket address is a string specifying the pathname
  61.  
  62. Socket methods:
  63.  
  64. - s.accept() --> new socket object, sockaddr
  65. - s.bind(sockaddr) --> None
  66. - s.close() --> None
  67. - s.connect(sockaddr) --> None
  68. - s.fileno() --> file descriptor
  69. - s.dup() --> same as socket.fromfd(os.dup(s.fileno(), ...)
  70. - s.getpeername() --> sockaddr
  71. - s.getsockname() --> sockaddr
  72. - s.getsockopt(level, optname[, buflen]) --> int or string
  73. - s.listen(backlog) --> None
  74. - s.makefile([mode[, bufsize]]) --> file object
  75. - s.recv(buflen [,flags]) --> string
  76. - s.recvfrom(buflen [,flags]) --> string, sockaddr
  77. - s.send(string [,flags]) --> nbytes
  78. - s.sendto(string, [flags,] sockaddr) --> nbytes
  79. - s.setblocking(0 | 1) --> None
  80. - s.setsockopt(level, optname, value) --> None
  81. - s.shutdown(how) --> None
  82. - repr(s) --> "<socket object, fd=%d, family=%d, type=%d, protocol=%d>"
  83.  
  84. */
  85.  
  86. #include "Python.h"
  87.  
  88. #ifdef RISCOS
  89. #define NO_DUP
  90. #undef off_t
  91. #undef uid_t
  92. #undef gid_t
  93. #undef errno
  94. #include <signal.h>
  95. #include "socklib.h"
  96. #include "inetlib.h"
  97. #include "netdb.h"
  98. #include "unixlib.h"
  99. #include "netinet/in.h"
  100. #include "sys/ioctl.h"
  101. #else
  102.  
  103. #include <sys/types.h>
  104. #include "mytime.h"
  105.  
  106. #include <signal.h>
  107. #ifndef MS_WINDOWS
  108. #include <netdb.h>
  109. #include <sys/socket.h>
  110. #include <netinet/in.h>
  111. #include <fcntl.h>
  112. #else
  113. #include <winsock.h>
  114. #include <fcntl.h>
  115. #endif
  116.  
  117. #endif           /*not RISCOS*/
  118.  
  119. #ifdef HAVE_SYS_UN_H
  120. #include <sys/un.h>
  121. #else
  122. #undef AF_UNIX
  123. #endif
  124.  
  125. #ifndef O_NDELAY
  126. #define O_NDELAY O_NONBLOCK    /* For QNX only? */
  127. #endif
  128.  
  129. #ifdef USE_GUSI
  130. /* fdopen() isn't declared in stdio.h (sigh) */
  131. #include <GUSI.h>
  132. #endif
  133.  
  134.  
  135. /* Here we have some hacks to choose between K&R or ANSI style function
  136.    definitions.  For NT to build this as an extension module (ie, DLL)
  137.    it must be compiled by the C++ compiler, as it takes the address of
  138.    a static data item exported from the main Python DLL.
  139. */
  140. #ifdef MS_WINDOWS
  141. /* seem to be a few differences in the API */
  142. #define close closesocket
  143. #define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */
  144. #define FORCE_ANSI_FUNC_DEFS
  145. #endif
  146.  
  147. #ifdef FORCE_ANSI_FUNC_DEFS
  148. #define BUILD_FUNC_DEF_1( fnname, arg1type, arg1name )    \
  149. fnname( arg1type arg1name )
  150.  
  151. #define BUILD_FUNC_DEF_2( fnname, arg1type, arg1name, arg2type, arg2name ) \
  152. fnname( arg1type arg1name, arg2type arg2name )
  153.  
  154. #define BUILD_FUNC_DEF_3( fnname, arg1type, arg1name, arg2type, arg2name , arg3type, arg3name )    \
  155. fnname( arg1type arg1name, arg2type arg2name, arg3type arg3name )
  156.  
  157. #define BUILD_FUNC_DEF_4( fnname, arg1type, arg1name, arg2type, arg2name , arg3type, arg3name, arg4type, arg4name )    \
  158. fnname( arg1type arg1name, arg2type arg2name, arg3type arg3name, arg4type arg4name )
  159.  
  160. #else /* !FORCE_ANSI_FN_DEFS */
  161. #define BUILD_FUNC_DEF_1( fnname, arg1type, arg1name )    \
  162. fnname( arg1name )    \
  163.     arg1type arg1name;
  164.  
  165. #define BUILD_FUNC_DEF_2( fnname, arg1type, arg1name, arg2type, arg2name ) \
  166. fnname( arg1name, arg2name )    \
  167.     arg1type arg1name;    \
  168.     arg2type arg2name;
  169.  
  170. #define BUILD_FUNC_DEF_3( fnname, arg1type, arg1name, arg2type, arg2name, arg3type, arg3name ) \
  171. fnname( arg1name, arg2name, arg3name )    \
  172.     arg1type arg1name;    \
  173.     arg2type arg2name;    \
  174.     arg3type arg3name;
  175.  
  176. #define BUILD_FUNC_DEF_4( fnname, arg1type, arg1name, arg2type, arg2name, arg3type, arg3name, arg4type, arg4name ) \
  177. fnname( arg1name, arg2name, arg3name, arg4name )    \
  178.     arg1type arg1name;    \
  179.     arg2type arg2name;    \
  180.     arg3type arg3name;    \
  181.     arg4type arg4name;
  182.  
  183. #endif /* !FORCE_ANSI_FN_DEFS */
  184.  
  185. /* Global variable holding the exception type for errors detected
  186.    by this module (but not argument type or memory errors, etc.). */
  187.  
  188. static PyObject *PySocket_Error;
  189.  
  190.  
  191. /* Convenience function to raise an error according to errno
  192.    and return a NULL pointer from a function. */
  193.  
  194. static PyObject *
  195. PySocket_Err()
  196. {
  197. #ifdef MS_WINDOWS
  198.     if (WSAGetLastError()) {
  199.         PyObject *v;
  200.         v = Py_BuildValue("(is)", WSAGetLastError(), "winsock error");
  201.         if (v != NULL) {
  202.             PyErr_SetObject(PySocket_Error, v);
  203.             Py_DECREF(v);
  204.         }
  205.         return NULL;
  206.     }
  207.     else
  208. #endif
  209.     return PyErr_SetFromErrno(PySocket_Error);
  210. }
  211.  
  212.  
  213. /* The object holding a socket.  It holds some extra information,
  214.    like the address family, which is used to decode socket address
  215.    arguments properly. */
  216.  
  217. typedef struct {
  218.     PyObject_HEAD
  219.     int sock_fd;        /* Socket file descriptor */
  220.     int sock_family;    /* Address family, e.g., AF_INET */
  221.     int sock_type;        /* Socket type, e.g., SOCK_STREAM */
  222.     int sock_proto;        /* Protocol type, usually 0 */
  223.     union sock_addr {
  224.         struct sockaddr_in in;
  225. #ifdef AF_UNIX
  226.         struct sockaddr_un un;
  227. #endif
  228.     } sock_addr;
  229. } PySocketSockObject;
  230.  
  231.  
  232. /* A forward reference to the Socktype type object.
  233.    The Socktype variable contains pointers to various functions,
  234.    some of which call newsockobject(), which uses Socktype, so
  235.    there has to be a circular reference. */
  236.  
  237. staticforward PyTypeObject PySocketSock_Type;
  238.  
  239.  
  240. /* Create a new socket object.
  241.    This just creates the object and initializes it.
  242.    If the creation fails, return NULL and set an exception (implicit
  243.    in NEWOBJ()). */
  244.  
  245. static PySocketSockObject *
  246. BUILD_FUNC_DEF_4(PySocketSock_New,int,fd, int,family, int,type, int,proto)
  247. {
  248.     PySocketSockObject *s;
  249.     PySocketSock_Type.ob_type = &PyType_Type;
  250.     s = PyObject_NEW(PySocketSockObject, &PySocketSock_Type);
  251.     if (s != NULL) {
  252.         s->sock_fd = fd;
  253.         s->sock_family = family;
  254.         s->sock_type = type;
  255.         s->sock_proto = proto;
  256.     }
  257.     return s;
  258. }
  259.  
  260.  
  261. /* Convert a string specifying a host name or one of a few symbolic
  262.    names to a numeric IP address.  This usually calls gethostbyname()
  263.    to do the work; the names "" and "<broadcast>" are special.
  264.    Return the length (should always be 4 bytes), or negative if
  265.    an error occurred; then an exception is raised. */
  266.  
  267. static int
  268. BUILD_FUNC_DEF_2(setipaddr, char*,name, struct sockaddr_in *,addr_ret)
  269. {
  270.     struct hostent *hp;
  271.     int d1, d2, d3, d4;
  272.     char ch;
  273. #ifdef HAVE_GETHOSTBYNAME_R
  274.     struct hostent hp_allocated;
  275.     char buf[1001];
  276.     int buf_len = (sizeof buf) - 1;
  277.     int errnop;
  278. #endif /* HAVE_GETHOSTBYNAME_R */
  279.  
  280.     if (name[0] == '\0') {
  281.         addr_ret->sin_addr.s_addr = INADDR_ANY;
  282.         return 4;
  283.     }
  284.     if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
  285.         addr_ret->sin_addr.s_addr = INADDR_BROADCAST;
  286.         return 4;
  287.     }
  288.     if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 &&
  289.         0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 &&
  290.         0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) {
  291.         addr_ret->sin_addr.s_addr = htonl(
  292.             ((long) d1 << 24) | ((long) d2 << 16) |
  293.             ((long) d3 << 8) | ((long) d4 << 0));
  294.         return 4;
  295.     }
  296. #ifdef HAVE_GETHOSTBYNAME_R
  297.     Py_BEGIN_ALLOW_THREADS
  298.     hp = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
  299.     Py_END_ALLOW_THREADS
  300. #else /* not HAVE_GETHOSTBYNAME_R */
  301.     hp = gethostbyname(name);
  302. #endif /* HAVE_GETHOSTBYNAME_R */
  303.  
  304.     if (hp == NULL) {
  305. #ifdef HAVE_HSTRERROR
  306.             /* Let's get real error message to return */
  307.             extern int h_errno;
  308.         PyErr_SetString(PySocket_Error, (char *)hstrerror(h_errno));
  309. #else
  310.         PyErr_SetString(PySocket_Error, "host not found");
  311. #endif
  312.         return -1;
  313.     }
  314.     memcpy((char *) &addr_ret->sin_addr, hp->h_addr, hp->h_length);
  315.     return hp->h_length;
  316. }
  317.  
  318.  
  319. /* Create a string object representing an IP address.
  320.    This is always a string of the form 'dd.dd.dd.dd' (with variable
  321.    size numbers). */
  322.  
  323. static PyObject *
  324. BUILD_FUNC_DEF_1(makeipaddr, struct sockaddr_in *,addr)
  325. {
  326.     long x = ntohl(addr->sin_addr.s_addr);
  327.     char buf[100];
  328.     sprintf(buf, "%d.%d.%d.%d",
  329.         (int) (x>>24) & 0xff, (int) (x>>16) & 0xff,
  330.         (int) (x>> 8) & 0xff, (int) (x>> 0) & 0xff);
  331.     return PyString_FromString(buf);
  332. }
  333.  
  334.  
  335. /* Create an object representing the given socket address,
  336.    suitable for passing it back to bind(), connect() etc.
  337.    The family field of the sockaddr structure is inspected
  338.    to determine what kind of address it really is. */
  339.  
  340. /*ARGSUSED*/
  341. static PyObject *
  342. BUILD_FUNC_DEF_2(makesockaddr,struct sockaddr *,addr, int,addrlen)
  343. {
  344.     if (addrlen == 0) {
  345.         /* No address -- may be recvfrom() from known socket */
  346.         Py_INCREF(Py_None);
  347.         return Py_None;
  348.     }
  349.  
  350.     switch (addr->sa_family) {
  351.  
  352.     case AF_INET:
  353.     {
  354.         struct sockaddr_in *a = (struct sockaddr_in *) addr;
  355.         PyObject *addr = makeipaddr(a);
  356.         PyObject *ret = Py_BuildValue("Oi", addr, ntohs(a->sin_port));
  357.         Py_XDECREF(addr);
  358.         return ret;
  359.     }
  360.  
  361. #ifdef AF_UNIX
  362.     case AF_UNIX:
  363.     {
  364.         struct sockaddr_un *a = (struct sockaddr_un *) addr;
  365.         return PyString_FromString(a->sun_path);
  366.     }
  367. #endif /* AF_UNIX */
  368.  
  369.     /* More cases here... */
  370.  
  371.     default:
  372.         PyErr_SetString(PySocket_Error, "return unknown socket address type");
  373.         return NULL;
  374.  
  375.     }
  376. }
  377.  
  378.  
  379. /* Parse a socket address argument according to the socket object's
  380.    address family.  Return 1 if the address was in the proper format,
  381.    0 of not.  The address is returned through addr_ret, its length
  382.    through len_ret. */
  383.  
  384. static int
  385. BUILD_FUNC_DEF_4(
  386. getsockaddrarg,PySocketSockObject *,s, PyObject *,args, struct sockaddr **,addr_ret, int *,len_ret)
  387. {
  388.     switch (s->sock_family) {
  389.  
  390. #ifdef AF_UNIX
  391.     case AF_UNIX:
  392.     {
  393.         struct sockaddr_un* addr;
  394.         char *path;
  395.         int len;
  396.         addr = (struct sockaddr_un* )&(s->sock_addr).un;
  397.         if (!PyArg_Parse(args, "s#", &path, &len))
  398.             return 0;
  399.         if (len > sizeof addr->sun_path) {
  400.             PyErr_SetString(PySocket_Error, "AF_UNIX path too long");
  401.             return 0;
  402.         }
  403.         addr->sun_family = AF_UNIX;
  404.         memcpy(addr->sun_path, path, len);
  405.         addr->sun_path[len] = 0;
  406.         *addr_ret = (struct sockaddr *) addr;
  407.         *len_ret = len + sizeof(*addr) - sizeof(addr->sun_path);
  408.         return 1;
  409.     }
  410. #endif /* AF_UNIX */
  411.  
  412.     case AF_INET:
  413.     {
  414.         struct sockaddr_in* addr;
  415.         char *host;
  416.         int port;
  417.          addr=(struct sockaddr_in*)&(s->sock_addr).in;
  418.         if (!PyArg_Parse(args, "(si)", &host, &port))
  419.             return 0;
  420.         if (setipaddr(host, addr) < 0)
  421.             return 0;
  422.         addr->sin_family = AF_INET;
  423.         addr->sin_port = htons(port);
  424.         *addr_ret = (struct sockaddr *) addr;
  425.         *len_ret = sizeof *addr;
  426.         return 1;
  427.     }
  428.  
  429.     /* More cases here... */
  430.  
  431.     default:
  432.         PyErr_SetString(PySocket_Error, "getsockaddrarg: bad family");
  433.         return 0;
  434.  
  435.     }
  436. }
  437.  
  438.  
  439. /* Get the address length according to the socket object's address family.
  440.    Return 1 if the family is known, 0 otherwise.  The length is returned
  441.    through len_ret. */
  442.  
  443. static int
  444. BUILD_FUNC_DEF_2(getsockaddrlen,PySocketSockObject *,s, int *,len_ret)
  445. {
  446.     switch (s->sock_family) {
  447.  
  448. #ifdef AF_UNIX
  449.     case AF_UNIX:
  450.     {
  451.         *len_ret = sizeof (struct sockaddr_un);
  452.         return 1;
  453.     }
  454. #endif /* AF_UNIX */
  455.  
  456.     case AF_INET:
  457.     {
  458.         *len_ret = sizeof (struct sockaddr_in);
  459.         return 1;
  460.     }
  461.  
  462.     /* More cases here... */
  463.  
  464.     default:
  465.         PyErr_SetString(PySocket_Error, "getsockaddrarg: bad family");
  466.         return 0;
  467.  
  468.     }
  469. }
  470.  
  471.  
  472. /* s.accept() method */
  473.  
  474. static PyObject *
  475. BUILD_FUNC_DEF_2(PySocketSock_accept,PySocketSockObject *,s, PyObject *,args)
  476. {
  477.     char addrbuf[256];
  478.     int addrlen, newfd;
  479.     PyObject *sock, *addr, *res;
  480.     if (!PyArg_NoArgs(args))
  481.         return NULL;
  482.     if (!getsockaddrlen(s, &addrlen))
  483.         return NULL;
  484.     Py_BEGIN_ALLOW_THREADS
  485.     newfd = accept(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
  486.     Py_END_ALLOW_THREADS
  487.     if (newfd < 0)
  488.         return PySocket_Err();
  489.     /* Create the new object with unspecified family,
  490.        to avoid calls to bind() etc. on it. */
  491.     sock = (PyObject *) PySocketSock_New(newfd,
  492.                     s->sock_family,
  493.                     s->sock_type,
  494.                     s->sock_proto);
  495.     if (sock == NULL)
  496.         close(newfd);
  497.     addr = makesockaddr((struct sockaddr *) addrbuf, addrlen);
  498.     res = Py_BuildValue("OO", sock, addr);
  499.     Py_XDECREF(sock);
  500.     Py_XDECREF(addr);
  501.     return res;
  502. }
  503.  
  504.  
  505. /* s.setblocking(1 | 0) method */
  506.  
  507. static PyObject *
  508. BUILD_FUNC_DEF_2(PySocketSock_setblocking,PySocketSockObject*,s,PyObject*,args)
  509. {
  510.     int block;
  511.     int delay_flag;
  512.     if (!PyArg_GetInt(args, &block))
  513.         return NULL;
  514.     Py_BEGIN_ALLOW_THREADS
  515. #ifndef RISCOS
  516. #ifndef MS_WINDOWS
  517.     delay_flag = fcntl (s->sock_fd, F_GETFL, 0);
  518.     if (block)
  519.         delay_flag &= (~O_NDELAY);
  520.     else
  521.         delay_flag |= O_NDELAY;
  522.     fcntl (s->sock_fd, F_SETFL, delay_flag);
  523. #else
  524.     block = !block;
  525.     ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
  526. #endif
  527. #else
  528.         socketioctl(s->sock_fd, FIONBIO, (u_long*)&block);
  529. #endif /* RISCOS */
  530.     Py_END_ALLOW_THREADS
  531.  
  532.     Py_INCREF(Py_None);
  533.     return Py_None;
  534. }
  535.  
  536.  
  537. /* s.setsockopt() method.
  538.    With an integer third argument, sets an integer option.
  539.    With a string third argument, sets an option from a buffer;
  540.    use optional built-in module 'struct' to encode the string. */
  541.  
  542. static PyObject *
  543. BUILD_FUNC_DEF_2(PySocketSock_setsockopt,PySocketSockObject *,s, PyObject *,args)
  544. {
  545.     int level;
  546.     int optname;
  547.     int res;
  548.     char *buf;
  549.     int buflen;
  550.     int flag;
  551.  
  552.     if (PyArg_Parse(args, "(iii)", &level, &optname, &flag)) {
  553.         buf = (char *) &flag;
  554.         buflen = sizeof flag;
  555.     }
  556.     else {
  557.         PyErr_Clear();
  558.         if (!PyArg_Parse(args, "(iis#)", &level, &optname, &buf, &buflen))
  559.             return NULL;
  560.     }
  561.     res = setsockopt(s->sock_fd, level, optname, (ANY *)buf, buflen);
  562.     if (res < 0)
  563.         return PySocket_Err();
  564.     Py_INCREF(Py_None);
  565.     return Py_None;
  566. }
  567.  
  568.  
  569. /* s.getsockopt() method.
  570.    With two arguments, retrieves an integer option.
  571.    With a third integer argument, retrieves a string buffer of that size;
  572.    use optional built-in module 'struct' to decode the string. */
  573.  
  574. static PyObject *
  575. BUILD_FUNC_DEF_2(PySocketSock_getsockopt,PySocketSockObject *,s, PyObject *,args)
  576. {
  577.     int level;
  578.     int optname;
  579.     int res;
  580.     PyObject *buf;
  581.     int buflen = 0;
  582.  
  583.     if (!PyArg_ParseTuple(args, "ii|i", &level, &optname, &buflen))
  584.         return NULL;
  585.  
  586.     if (buflen == 0) {
  587.         int flag = 0;
  588.         int flagsize = sizeof flag;
  589.         res = getsockopt(s->sock_fd, level, optname,
  590.                  (ANY *)&flag, &flagsize);
  591.         if (res < 0)
  592.             return PySocket_Err();
  593.         return PyInt_FromLong(flag);
  594.     }
  595.     if (buflen <= 0 || buflen > 1024) {
  596.         PyErr_SetString(PySocket_Error, "getsockopt buflen out of range");
  597.         return NULL;
  598.     }
  599.     buf = PyString_FromStringAndSize((char *)NULL, buflen);
  600.     if (buf == NULL)
  601.         return NULL;
  602.     res = getsockopt(s->sock_fd, level, optname,
  603.              (ANY *)PyString_AsString(buf), &buflen);
  604.     if (res < 0) {
  605.         Py_DECREF(buf);
  606.         return PySocket_Err();
  607.     }
  608.     _PyString_Resize(&buf, buflen);
  609.     return buf;
  610. }
  611.  
  612.  
  613. /* s.bind(sockaddr) method */
  614.  
  615. static PyObject *
  616. BUILD_FUNC_DEF_2(PySocketSock_bind,PySocketSockObject *,s, PyObject *,args)
  617. {
  618.     struct sockaddr *addr;
  619.     int addrlen;
  620.     int res;
  621.     if (!getsockaddrarg(s, args, &addr, &addrlen))
  622.         return NULL;
  623.     Py_BEGIN_ALLOW_THREADS
  624.     res = bind(s->sock_fd, addr, addrlen);
  625.     Py_END_ALLOW_THREADS
  626.     if (res < 0)
  627.         return PySocket_Err();
  628.     Py_INCREF(Py_None);
  629.     return Py_None;
  630. }
  631.  
  632.  
  633. /* s.close() method.
  634.    Set the file descriptor to -1 so operations tried subsequently
  635.    will surely fail. */
  636.  
  637. static PyObject *
  638. BUILD_FUNC_DEF_2(PySocketSock_close,PySocketSockObject *,s, PyObject *,args)
  639. {
  640.     if (!PyArg_NoArgs(args))
  641.         return NULL;
  642.     if (s->sock_fd != -1) {
  643.         Py_BEGIN_ALLOW_THREADS
  644.         (void) close(s->sock_fd);
  645.         Py_END_ALLOW_THREADS
  646.     }
  647.     s->sock_fd = -1;
  648.     Py_INCREF(Py_None);
  649.     return Py_None;
  650. }
  651.  
  652.  
  653. /* s.connect(sockaddr) method */
  654.  
  655. static PyObject *
  656. BUILD_FUNC_DEF_2(PySocketSock_connect,PySocketSockObject *,s, PyObject *,args)
  657. {
  658.     struct sockaddr *addr;
  659.     int addrlen;
  660.     int res;
  661.     if (!getsockaddrarg(s, args, &addr, &addrlen))
  662.         return NULL;
  663.     Py_BEGIN_ALLOW_THREADS
  664.     res = connect(s->sock_fd, addr, addrlen);
  665.     Py_END_ALLOW_THREADS
  666.     if (res < 0)
  667.         return PySocket_Err();
  668.     Py_INCREF(Py_None);
  669.     return Py_None;
  670. }
  671.  
  672.  
  673. /* s.fileno() method */
  674.  
  675. static PyObject *
  676. BUILD_FUNC_DEF_2(PySocketSock_fileno,PySocketSockObject *,s, PyObject *,args)
  677. {
  678.     if (!PyArg_NoArgs(args))
  679.         return NULL;
  680.     return PyInt_FromLong((long) s->sock_fd);
  681. }
  682.  
  683.  
  684. #ifndef NO_DUP
  685. /* s.dup() method */
  686.  
  687. static PyObject *
  688. BUILD_FUNC_DEF_2(PySocketSock_dup,PySocketSockObject *,s, PyObject *,args)
  689. {
  690.     int newfd;
  691.     PyObject *sock;
  692.     if (!PyArg_NoArgs(args))
  693.         return NULL;
  694.     newfd = dup(s->sock_fd);
  695.     if (newfd < 0)
  696.         return PySocket_Err();
  697.     sock = (PyObject *) PySocketSock_New(newfd,
  698.                     s->sock_family,
  699.                     s->sock_type,
  700.                     s->sock_proto);
  701.     if (sock == NULL)
  702.         close(newfd);
  703.     return sock;
  704. }
  705. #endif
  706.  
  707.  
  708. /* s.getsockname() method */
  709.  
  710. static PyObject *
  711. BUILD_FUNC_DEF_2(PySocketSock_getsockname,PySocketSockObject *,s, PyObject *,args)
  712. {
  713.     char addrbuf[256];
  714.     int addrlen, res;
  715.     if (!PyArg_NoArgs(args))
  716.         return NULL;
  717.     if (!getsockaddrlen(s, &addrlen))
  718.         return NULL;
  719.     memset(addrbuf, 0, addrlen);
  720.     Py_BEGIN_ALLOW_THREADS
  721.     res = getsockname(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
  722.     Py_END_ALLOW_THREADS
  723.     if (res < 0)
  724.         return PySocket_Err();
  725.     return makesockaddr((struct sockaddr *) addrbuf, addrlen);
  726. }
  727.  
  728.  
  729. #ifdef HAVE_GETPEERNAME        /* Cray APP doesn't have this :-( */
  730. /* s.getpeername() method */
  731.  
  732. static PyObject *
  733. BUILD_FUNC_DEF_2(PySocketSock_getpeername,PySocketSockObject *,s, PyObject *,args)
  734. {
  735.     char addrbuf[256];
  736.     int addrlen, res;
  737.     if (!PyArg_NoArgs(args))
  738.         return NULL;
  739.     if (!getsockaddrlen(s, &addrlen))
  740.         return NULL;
  741.     Py_BEGIN_ALLOW_THREADS
  742.     res = getpeername(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
  743.     Py_END_ALLOW_THREADS
  744.     if (res < 0)
  745.         return PySocket_Err();
  746.     return makesockaddr((struct sockaddr *) addrbuf, addrlen);
  747. }
  748. #endif /* HAVE_GETPEERNAME */
  749.  
  750.  
  751. /* s.listen(n) method */
  752.  
  753. static PyObject *
  754. BUILD_FUNC_DEF_2(PySocketSock_listen,PySocketSockObject *,s, PyObject *,args)
  755. {
  756.     int backlog;
  757.     int res;
  758.     if (!PyArg_GetInt(args, &backlog))
  759.         return NULL;
  760.     Py_BEGIN_ALLOW_THREADS
  761.     if (backlog < 1)
  762.         backlog = 1;
  763.     res = listen(s->sock_fd, backlog);
  764.     Py_END_ALLOW_THREADS
  765.     if (res < 0)
  766.         return PySocket_Err();
  767.     Py_INCREF(Py_None);
  768.     return Py_None;
  769. }
  770.  
  771. #ifndef NO_DUP
  772. /* s.makefile(mode) method.
  773.    Create a new open file object referring to a dupped version of
  774.    the socket's file descriptor.  (The dup() call is necessary so
  775.    that the open file and socket objects may be closed independent
  776.    of each other.)
  777.    The mode argument specifies 'r' or 'w' passed to fdopen(). */
  778.  
  779. static PyObject *
  780. BUILD_FUNC_DEF_2(PySocketSock_makefile,PySocketSockObject *,s, PyObject *,args)
  781. {
  782.     extern int fclose Py_PROTO((FILE *));
  783.     char *mode = "r";
  784.     int bufsize = -1;
  785.     int fd;
  786.     FILE *fp;
  787.     PyObject *f;
  788.  
  789.     if (!PyArg_ParseTuple(args, "|si", &mode, &bufsize))
  790.         return NULL;
  791. #ifdef MS_WIN32
  792.    if ( ((fd =  _open_osfhandle( s->sock_fd, _O_BINARY )) < 0) ||
  793.         ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL)) {
  794. #else
  795.     if ((fd = dup(s->sock_fd)) < 0 ||
  796.         (fp = fdopen(fd, mode)) == NULL) {
  797. #endif
  798.         if (fd >= 0)
  799.             close(fd);
  800.         return PySocket_Err();
  801.     }
  802.     f = PyFile_FromFile(fp, "<socket>", mode, fclose);
  803.     if (f != NULL)
  804.         PyFile_SetBufSize(f, bufsize);
  805.     return f;
  806. }
  807. #endif /* NO_DUP */
  808.  
  809. /* s.recv(nbytes [,flags]) method */
  810.  
  811. static PyObject *
  812. BUILD_FUNC_DEF_2(PySocketSock_recv,PySocketSockObject *,s, PyObject *,args)
  813. {
  814.     int len, n, flags = 0;
  815.     PyObject *buf;
  816.     if (!PyArg_ParseTuple(args, "i|i", &len, &flags))
  817.         return NULL;
  818.     buf = PyString_FromStringAndSize((char *) 0, len);
  819.     if (buf == NULL)
  820.         return NULL;
  821.     Py_BEGIN_ALLOW_THREADS
  822.     n = recv(s->sock_fd, PyString_AsString(buf), len, flags);
  823.     Py_END_ALLOW_THREADS
  824.     if (n < 0) {
  825.         Py_DECREF(buf);
  826.         return PySocket_Err();
  827.     }
  828.     if (n != len && _PyString_Resize(&buf, n) < 0)
  829.         return NULL;
  830.     return buf;
  831. }
  832.  
  833.  
  834. /* s.recvfrom(nbytes [,flags]) method */
  835.  
  836. static PyObject *
  837. BUILD_FUNC_DEF_2(PySocketSock_recvfrom,PySocketSockObject *,s, PyObject *,args)
  838. {
  839.     char addrbuf[256];
  840.     PyObject *buf, *addr, *ret;
  841.     int addrlen, len, n, flags = 0;
  842.     if (!PyArg_ParseTuple(args, "i|i", &len, &flags))
  843.         return NULL;
  844.     if (!getsockaddrlen(s, &addrlen))
  845.         return NULL;
  846.     buf = PyString_FromStringAndSize((char *) 0, len);
  847.     if (buf == NULL)
  848.         return NULL;
  849.     Py_BEGIN_ALLOW_THREADS
  850.     n = recvfrom(s->sock_fd, PyString_AsString(buf), len, flags,
  851. #ifndef MS_WINDOWS
  852.              (ANY *)addrbuf, &addrlen);
  853. #else
  854.              (struct sockaddr *)addrbuf, &addrlen);
  855. #endif
  856.     Py_END_ALLOW_THREADS
  857.     if (n < 0) {
  858.         Py_DECREF(buf);
  859.         return PySocket_Err();
  860.     }
  861.     if (n != len && _PyString_Resize(&buf, n) < 0)
  862.         return NULL;
  863.     addr = makesockaddr((struct sockaddr *)addrbuf, addrlen);
  864.     ret = Py_BuildValue("OO", buf, addr);
  865.     Py_XDECREF(addr);
  866.     Py_XDECREF(buf);
  867.     return ret;
  868. }
  869.  
  870.  
  871. /* s.send(data [,flags]) method */
  872.  
  873. static PyObject *
  874. BUILD_FUNC_DEF_2(PySocketSock_send,PySocketSockObject *,s, PyObject *,args)
  875. {
  876.     char *buf;
  877.     int len, n, flags = 0;
  878.     if (!PyArg_ParseTuple(args, "s#|i", &buf, &len, &flags))
  879.         return NULL;
  880.     Py_BEGIN_ALLOW_THREADS
  881.     n = send(s->sock_fd, buf, len, flags);
  882.     Py_END_ALLOW_THREADS
  883.     if (n < 0)
  884.         return PySocket_Err();
  885.     return PyInt_FromLong((long)n);
  886. }
  887.  
  888.  
  889. /* s.sendto(data, [flags,] sockaddr) method */
  890.  
  891. static PyObject *
  892. BUILD_FUNC_DEF_2(PySocketSock_sendto,PySocketSockObject *,s, PyObject *,args)
  893. {
  894.     PyObject *addro;
  895.     char *buf;
  896.     struct sockaddr *addr;
  897.     int addrlen, len, n, flags;
  898.     flags = 0;
  899.     if (!PyArg_Parse(args, "(s#O)", &buf, &len, &addro)) {
  900.         PyErr_Clear();
  901.         if (!PyArg_Parse(args, "(s#iO)", &buf, &len, &flags, &addro))
  902.             return NULL;
  903.     }
  904.     if (!getsockaddrarg(s, addro, &addr, &addrlen))
  905.         return NULL;
  906.     Py_BEGIN_ALLOW_THREADS
  907.     n = sendto(s->sock_fd, buf, len, flags, addr, addrlen);
  908.     Py_END_ALLOW_THREADS
  909.     if (n < 0)
  910.         return PySocket_Err();
  911.     return PyInt_FromLong((long)n);
  912. }
  913.  
  914.  
  915. /* s.shutdown(how) method */
  916.  
  917. static PyObject *
  918. BUILD_FUNC_DEF_2(PySocketSock_shutdown,PySocketSockObject *,s, PyObject *,args)
  919. {
  920.     int how;
  921.     int res;
  922.     if (!PyArg_GetInt(args, &how))
  923.         return NULL;
  924.     Py_BEGIN_ALLOW_THREADS
  925.     res = shutdown(s->sock_fd, how);
  926.     Py_END_ALLOW_THREADS
  927.     if (res < 0)
  928.         return PySocket_Err();
  929.     Py_INCREF(Py_None);
  930.     return Py_None;
  931. }
  932.  
  933.  
  934. /* List of methods for socket objects */
  935.  
  936. static PyMethodDef PySocketSock_methods[] = {
  937.     {"accept",        (PyCFunction)PySocketSock_accept},
  938.     {"setblocking",        (PyCFunction)PySocketSock_setblocking},
  939.     {"setsockopt",        (PyCFunction)PySocketSock_setsockopt},
  940.     {"getsockopt",        (PyCFunction)PySocketSock_getsockopt, 1},
  941.     {"bind",        (PyCFunction)PySocketSock_bind},
  942.     {"close",        (PyCFunction)PySocketSock_close},
  943.     {"connect",        (PyCFunction)PySocketSock_connect},
  944.     {"fileno",        (PyCFunction)PySocketSock_fileno},
  945. #ifndef NO_DUP
  946.     {"dup",            (PyCFunction)PySocketSock_dup},
  947. #endif
  948.     {"getsockname",        (PyCFunction)PySocketSock_getsockname},
  949. #ifdef HAVE_GETPEERNAME
  950.     {"getpeername",        (PyCFunction)PySocketSock_getpeername},
  951. #endif
  952.     {"listen",        (PyCFunction)PySocketSock_listen},
  953. #ifndef NO_DUP
  954.     {"makefile",        (PyCFunction)PySocketSock_makefile, 1},
  955. #endif
  956.     {"recv",        (PyCFunction)PySocketSock_recv, 1},
  957.     {"recvfrom",        (PyCFunction)PySocketSock_recvfrom, 1},
  958.     {"send",        (PyCFunction)PySocketSock_send, 1},
  959.     {"sendto",        (PyCFunction)PySocketSock_sendto},
  960.     {"shutdown",        (PyCFunction)PySocketSock_shutdown},
  961.     {NULL,            NULL}        /* sentinel */
  962. };
  963.  
  964.  
  965. /* Deallocate a socket object in response to the last Py_DECREF().
  966.    First close the file description. */
  967.  
  968. static void
  969. BUILD_FUNC_DEF_1(PySocketSock_dealloc,PySocketSockObject *,s)
  970. {
  971.     (void) close(s->sock_fd);
  972.     PyMem_DEL(s);
  973. }
  974.  
  975.  
  976. /* Return a socket object's named attribute. */
  977.  
  978. static PyObject *
  979. BUILD_FUNC_DEF_2(PySocketSock_getattr,PySocketSockObject *,s, char *,name)
  980. {
  981.     return Py_FindMethod(PySocketSock_methods, (PyObject *) s, name);
  982. }
  983.  
  984.  
  985. static PyObject *
  986. BUILD_FUNC_DEF_1(PySocketSock_repr,PySocketSockObject *,s)
  987. {
  988.     char buf[512];
  989.     sprintf(buf,
  990.         "<socket object, fd=%d, family=%d, type=%d, protocol=%d>",
  991.         s->sock_fd, s->sock_family, s->sock_type, s->sock_proto);
  992.     return PyString_FromString(buf);
  993. }
  994.  
  995.  
  996. /* Type object for socket objects. */
  997.  
  998. static PyTypeObject PySocketSock_Type = {
  999.     PyObject_HEAD_INIT(0)    /* Must fill in type value later */
  1000.     0,
  1001.     "socket",
  1002.     sizeof(PySocketSockObject),
  1003.     0,
  1004.     (destructor)PySocketSock_dealloc, /*tp_dealloc*/
  1005.     0,        /*tp_print*/
  1006.     (getattrfunc)PySocketSock_getattr, /*tp_getattr*/
  1007.     0,        /*tp_setattr*/
  1008.     0,        /*tp_compare*/
  1009.     (reprfunc)PySocketSock_repr, /*tp_repr*/
  1010.     0,        /*tp_as_number*/
  1011.     0,        /*tp_as_sequence*/
  1012.     0,        /*tp_as_mapping*/
  1013. };
  1014.  
  1015.  
  1016. /* Python interface to gethostname(). */
  1017.  
  1018. /*ARGSUSED*/
  1019. static PyObject *
  1020. BUILD_FUNC_DEF_2(PySocket_gethostname,PyObject *,self, PyObject *,args)
  1021. {
  1022.     char buf[1024];
  1023.     int res;
  1024.     if (!PyArg_NoArgs(args))
  1025.         return NULL;
  1026.     Py_BEGIN_ALLOW_THREADS
  1027.     res = gethostname(buf, (int) sizeof buf - 1);
  1028.     Py_END_ALLOW_THREADS
  1029.     if (res < 0)
  1030.         return PySocket_Err();
  1031.     buf[sizeof buf - 1] = '\0';
  1032.     return PyString_FromString(buf);
  1033. }
  1034.  
  1035.  
  1036. /* Python interface to gethostbyname(name). */
  1037.  
  1038. /*ARGSUSED*/
  1039. static PyObject *
  1040. BUILD_FUNC_DEF_2(PySocket_gethostbyname,PyObject *,self, PyObject *,args)
  1041. {
  1042.     char *name;
  1043.     struct sockaddr_in addrbuf;
  1044.     if (!PyArg_Parse(args, "s", &name))
  1045.         return NULL;
  1046.     if (setipaddr(name, &addrbuf) < 0)
  1047.         return NULL;
  1048.     return makeipaddr(&addrbuf);
  1049. }
  1050.  
  1051. /* Python interface to gethostbyaddr(IP). */
  1052.  
  1053. /*ARGSUSED*/
  1054. static PyObject *
  1055. BUILD_FUNC_DEF_2(PySocket_gethostbyaddr,PyObject *,self, PyObject *, args)
  1056. {
  1057.         struct sockaddr_in addr;
  1058.     char *ip_num;
  1059.     struct hostent *h;
  1060.     char **pch;
  1061.     PyObject *rtn_tuple = (PyObject *)NULL;
  1062.     PyObject *name_list = (PyObject *)NULL;
  1063.     PyObject *addr_list = (PyObject *)NULL;
  1064.     PyObject *tmp;
  1065.  
  1066.     if (!PyArg_Parse(args, "s", &ip_num))
  1067.         return NULL;
  1068.     if (setipaddr(ip_num, &addr) < 0)
  1069.         return NULL;
  1070.     h = gethostbyaddr((char *)&addr.sin_addr,
  1071.               sizeof(addr.sin_addr),
  1072.               AF_INET);
  1073.     if (h == NULL) {
  1074. #ifdef HAVE_HSTRERROR
  1075.             /* Let's get real error message to return */
  1076.             extern int h_errno;
  1077.         PyErr_SetString(PySocket_Error, (char *)hstrerror(h_errno));
  1078. #else
  1079.         PyErr_SetString(PySocket_Error, "host not found");
  1080. #endif
  1081.         return NULL;
  1082.     }
  1083.     if ((name_list = PyList_New(0)) == NULL)
  1084.         goto err;
  1085.     if ((addr_list = PyList_New(0)) == NULL)
  1086.         goto err;
  1087.     for (pch = h->h_aliases; *pch != NULL; pch++) {
  1088.         tmp = PyString_FromString(*pch);
  1089.         if (tmp == NULL)
  1090.             goto err;
  1091.         PyList_Append(name_list, tmp);
  1092.         Py_DECREF(tmp);
  1093.     }
  1094.     for (pch = h->h_addr_list; *pch != NULL; pch++) {
  1095.         memcpy((char *) &addr.sin_addr, *pch, h->h_length);
  1096.         tmp = makeipaddr(&addr);
  1097.         if (tmp == NULL)
  1098.             goto err;
  1099.         PyList_Append(addr_list, tmp);
  1100.         Py_DECREF(tmp);
  1101.     }
  1102.     rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list);
  1103.  err:
  1104.     Py_XDECREF(name_list);
  1105.     Py_XDECREF(addr_list);
  1106.     return rtn_tuple;
  1107. }
  1108.  
  1109.  
  1110. /* Python interface to getservbyname(name).
  1111.    This only returns the port number, since the other info is already
  1112.    known or not useful (like the list of aliases). */
  1113.  
  1114. /*ARGSUSED*/
  1115. static PyObject *
  1116. BUILD_FUNC_DEF_2(PySocket_getservbyname,PyObject *,self, PyObject *,args)
  1117. {
  1118.     char *name, *proto;
  1119.     struct servent *sp;
  1120.     if (!PyArg_Parse(args, "(ss)", &name, &proto))
  1121.         return NULL;
  1122.     Py_BEGIN_ALLOW_THREADS
  1123.     sp = getservbyname(name, proto);
  1124.     Py_END_ALLOW_THREADS
  1125.     if (sp == NULL) {
  1126.         PyErr_SetString(PySocket_Error, "service/proto not found");
  1127.         return NULL;
  1128.     }
  1129.     return PyInt_FromLong((long) ntohs(sp->s_port));
  1130. }
  1131.  
  1132.  
  1133. /* Python interface to socket(family, type, proto).
  1134.    The third (protocol) argument is optional.
  1135.    Return a new socket object. */
  1136.  
  1137. /*ARGSUSED*/
  1138. static PyObject *
  1139. BUILD_FUNC_DEF_2(PySocket_socket,PyObject *,self, PyObject *,args)
  1140. {
  1141.     PySocketSockObject *s;
  1142. #ifdef MS_WINDOWS
  1143.     SOCKET fd;
  1144. #else
  1145.     int fd;
  1146. #endif
  1147.     int family, type, proto = 0;
  1148.     if (!PyArg_ParseTuple(args, "ii|i", &family, &type, &proto))
  1149.         return NULL;
  1150.     Py_BEGIN_ALLOW_THREADS
  1151.     fd = socket(family, type, proto);
  1152.     Py_END_ALLOW_THREADS
  1153. #ifdef MS_WINDOWS
  1154.     if (fd == INVALID_SOCKET)
  1155. #else
  1156.     if (fd < 0)
  1157. #endif
  1158.         return PySocket_Err();
  1159.     s = PySocketSock_New(fd, family, type, proto);
  1160.     /* If the object can't be created, don't forget to close the
  1161.        file descriptor again! */
  1162.     if (s == NULL)
  1163.         (void) close(fd);
  1164.     /* From now on, ignore SIGPIPE and let the error checking
  1165.        do the work. */
  1166. #ifdef SIGPIPE
  1167.     (void) signal(SIGPIPE, SIG_IGN);
  1168. #endif
  1169.     return (PyObject *) s;
  1170. }
  1171.  
  1172. #ifndef NO_DUP
  1173. /* Create a socket object from a numeric file description.
  1174.    Useful e.g. if stdin is a socket.
  1175.    Additional arguments as for socket(). */
  1176.  
  1177. /*ARGSUSED*/
  1178. static PyObject *
  1179. BUILD_FUNC_DEF_2(PySocket_fromfd,PyObject *,self, PyObject *,args)
  1180. {
  1181.     PySocketSockObject *s;
  1182.     int fd, family, type, proto = 0;
  1183.     if (!PyArg_ParseTuple(args, "iii|i", &fd, &family, &type, &proto))
  1184.         return NULL;
  1185.     /* Dup the fd so it and the socket can be closed independently */
  1186.     fd = dup(fd);
  1187.     if (fd < 0)
  1188.         return PySocket_Err();
  1189.     s = PySocketSock_New(fd, family, type, proto);
  1190.     /* From now on, ignore SIGPIPE and let the error checking
  1191.        do the work. */
  1192. #ifdef SIGPIPE
  1193.     (void) signal(SIGPIPE, SIG_IGN);
  1194. #endif
  1195.     return (PyObject *) s;
  1196. }
  1197. #endif /* NO_DUP */
  1198.  
  1199. static PyObject *
  1200. BUILD_FUNC_DEF_2(PySocket_ntohs, PyObject *, self, PyObject *, args)
  1201. {
  1202.     int x1, x2;
  1203.  
  1204.     if (!PyArg_Parse(args, "i", &x1)) {
  1205.         return NULL;
  1206.     }
  1207.     x2 = (int)ntohs((short)x1);
  1208.     return PyInt_FromLong(x2);
  1209. }
  1210.  
  1211. static PyObject *
  1212. BUILD_FUNC_DEF_2(PySocket_ntohl, PyObject *, self, PyObject *, args)
  1213. {
  1214.     int x1, x2;
  1215.  
  1216.     if (!PyArg_Parse(args, "i", &x1)) {
  1217.         return NULL;
  1218.     }
  1219.     x2 = ntohl(x1);
  1220.     return PyInt_FromLong(x2);
  1221. }
  1222.  
  1223. static PyObject *
  1224. BUILD_FUNC_DEF_2(PySocket_htons, PyObject *, self, PyObject *, args)
  1225. {
  1226.     int x1, x2;
  1227.  
  1228.     if (!PyArg_Parse(args, "i", &x1)) {
  1229.         return NULL;
  1230.     }
  1231.     x2 = (int)htons((short)x1);
  1232.     return PyInt_FromLong(x2);
  1233. }
  1234.  
  1235. static PyObject *
  1236. BUILD_FUNC_DEF_2(PySocket_htonl, PyObject *, self, PyObject *, args)
  1237. {
  1238.     int x1, x2;
  1239.  
  1240.     if (!PyArg_Parse(args, "i", &x1)) {
  1241.         return NULL;
  1242.     }
  1243.     x2 = htonl(x1);
  1244.     return PyInt_FromLong(x2);
  1245. }
  1246.  
  1247. /* List of functions exported by this module. */
  1248.  
  1249. static PyMethodDef PySocket_methods[] = {
  1250.     {"gethostbyname",    PySocket_gethostbyname},
  1251.     {"gethostbyaddr",    PySocket_gethostbyaddr},
  1252.     {"gethostname",        PySocket_gethostname},
  1253.     {"getservbyname",    PySocket_getservbyname},
  1254.     {"socket",        PySocket_socket, 1},
  1255. #ifndef NO_DUP
  1256.     {"fromfd",        PySocket_fromfd, 1},
  1257. #endif
  1258.     {"ntohs",        PySocket_ntohs},
  1259.     {"ntohl",        PySocket_ntohl},
  1260.     {"htons",        PySocket_htons},
  1261.     {"htonl",        PySocket_htonl},
  1262.     {NULL,            NULL}         /* Sentinel */
  1263. };
  1264.  
  1265.  
  1266. /* Convenience routine to export an integer value.
  1267.    For simplicity, errors (which are unlikely anyway) are ignored. */
  1268.  
  1269. static void
  1270. BUILD_FUNC_DEF_3(insint,PyObject *,d, char *,name, int,value)
  1271. {
  1272.     PyObject *v = PyInt_FromLong((long) value);
  1273.     if (v == NULL) {
  1274.         /* Don't bother reporting this error */
  1275.         PyErr_Clear();
  1276.     }
  1277.     else {
  1278.         PyDict_SetItemString(d, name, v);
  1279.         Py_DECREF(v);
  1280.     }
  1281. }
  1282.  
  1283.  
  1284. #ifdef MS_WINDOWS
  1285.  
  1286. /* Additional initialization and cleanup for NT/Windows */
  1287.  
  1288. static void
  1289. NTcleanup()
  1290. {
  1291.     WSACleanup();
  1292. }
  1293.  
  1294. static int
  1295. NTinit()
  1296. {
  1297.     WSADATA WSAData;
  1298.     int ret;
  1299.     char buf[100];
  1300.     ret = WSAStartup(0x0101, &WSAData);
  1301.     switch (ret) {
  1302.     case 0:    /* no error */
  1303.         atexit(NTcleanup);
  1304.         return 1;
  1305.     case WSASYSNOTREADY:
  1306.         PyErr_SetString(PyExc_ImportError,
  1307.                 "WSAStartup failed: network not ready");
  1308.         break;
  1309.     case WSAVERNOTSUPPORTED:
  1310.     case WSAEINVAL:
  1311.         PyErr_SetString(PyExc_ImportError,
  1312.             "WSAStartup failed: requested version not supported");
  1313.         break;
  1314.     default:
  1315.         sprintf(buf, "WSAStartup failed: error code %d", ret);
  1316.         PyErr_SetString(PyExc_ImportError, buf);
  1317.         break;
  1318.     }
  1319.     return 0;
  1320. }
  1321.  
  1322. #endif /* MS_WINDOWS */
  1323.  
  1324.  
  1325. /* Initialize this module.
  1326.    This is called when the first 'import socket' is done,
  1327.    via a table in config.c, if config.c is compiled with USE_SOCKET
  1328.    defined.
  1329.  
  1330.    For MS_WINDOWS (which means any Windows variant), this module
  1331.    is actually called "_socket", and there's a wrapper "socket.py"
  1332.    which implements some missing functionality (such as makefile(),
  1333.    dup() and fromfd()).  The import of "_socket" may fail with an
  1334.    ImportError exception if initialization of WINSOCK fails.  When
  1335.    WINSOCK is initialized succesfully, a call to WSACleanup() is
  1336.    scheduled to be made at exit time.  */
  1337.  
  1338. void
  1339. #if defined(MS_WINDOWS) || defined(RISCOS)
  1340. init_socket()
  1341. #else
  1342. initsocket()
  1343. #endif
  1344. {
  1345.     PyObject *m, *d;
  1346. #ifdef MS_WINDOWS
  1347.     if (!NTinit())
  1348.         return;
  1349. #endif
  1350. #if   defined(MS_WINDOWS) || defined(RISCOS)
  1351.     m = Py_InitModule("_socket", PySocket_methods);
  1352. #else
  1353.     m = Py_InitModule("socket", PySocket_methods);
  1354. #endif
  1355.     d = PyModule_GetDict(m);
  1356.     PySocket_Error = PyString_FromString("socket.error");
  1357.     if (PySocket_Error == NULL ||
  1358.         PyDict_SetItemString(d, "error", PySocket_Error) != 0)
  1359.         Py_FatalError("can't define socket.error");
  1360.     insint(d, "AF_INET", AF_INET);
  1361. #ifdef AF_UNIX
  1362.     insint(d, "AF_UNIX", AF_UNIX);
  1363. #endif /* AF_UNIX */
  1364.     insint(d, "SOCK_STREAM", SOCK_STREAM);
  1365.     insint(d, "SOCK_DGRAM", SOCK_DGRAM);
  1366.     insint(d, "SOCK_RAW", SOCK_RAW);
  1367.     insint(d, "SOCK_SEQPACKET", SOCK_SEQPACKET);
  1368.     insint(d, "SOCK_RDM", SOCK_RDM);
  1369.  
  1370. #ifdef    SO_DEBUG
  1371.     insint(d, "SO_DEBUG", SO_DEBUG);
  1372. #endif
  1373. #ifdef    SO_ACCEPTCONN
  1374.     insint(d, "SO_ACCEPTCONN", SO_ACCEPTCONN);
  1375. #endif
  1376. #ifdef    SO_REUSEADDR
  1377.     insint(d, "SO_REUSEADDR", SO_REUSEADDR);
  1378. #endif
  1379. #ifdef    SO_KEEPALIVE
  1380.     insint(d, "SO_KEEPALIVE", SO_KEEPALIVE);
  1381. #endif
  1382. #ifdef    SO_DONTROUTE
  1383.     insint(d, "SO_DONTROUTE", SO_DONTROUTE);
  1384. #endif
  1385. #ifdef    SO_BROADCAST
  1386.     insint(d, "SO_BROADCAST", SO_BROADCAST);
  1387. #endif
  1388. #ifdef    SO_USELOOPBACK
  1389.     insint(d, "SO_USELOOPBACK", SO_USELOOPBACK);
  1390. #endif
  1391. #ifdef    SO_LINGER
  1392.     insint(d, "SO_LINGER", SO_LINGER);
  1393. #endif
  1394. #ifdef    SO_OOBINLINE
  1395.     insint(d, "SO_OOBINLINE", SO_OOBINLINE);
  1396. #endif
  1397. #ifdef    SO_REUSEPORT
  1398.     insint(d, "SO_REUSEPORT", SO_REUSEPORT);
  1399. #endif
  1400.  
  1401. #ifdef    SO_SNDBUF
  1402.     insint(d, "SO_SNDBUF", SO_SNDBUF);
  1403. #endif
  1404. #ifdef    SO_RCVBUF
  1405.     insint(d, "SO_RCVBUF", SO_RCVBUF);
  1406. #endif
  1407. #ifdef    SO_SNDLOWAT
  1408.     insint(d, "SO_SNDLOWAT", SO_SNDLOWAT);
  1409. #endif
  1410. #ifdef    SO_RCVLOWAT
  1411.     insint(d, "SO_RCVLOWAT", SO_RCVLOWAT);
  1412. #endif
  1413. #ifdef    SO_SNDTIMEO
  1414.     insint(d, "SO_SNDTIMEO", SO_SNDTIMEO);
  1415. #endif
  1416. #ifdef    SO_RCVTIMEO
  1417.     insint(d, "SO_RCVTIMEO", SO_RCVTIMEO);
  1418. #endif
  1419. #ifdef    SO_ERROR
  1420.     insint(d, "SO_ERROR", SO_ERROR);
  1421. #endif
  1422. #ifdef    SO_TYPE
  1423.     insint(d, "SO_TYPE", SO_TYPE);
  1424. #endif
  1425.  
  1426.     /* Maximum number of connections for "listen" */
  1427. #ifdef    SOMAXCONN
  1428.     insint(d, "SOMAXCONN", SOMAXCONN);
  1429. #else
  1430.     insint(d, "SOMAXCONN", 5);    /* Common value */
  1431. #endif
  1432.  
  1433.     /* Flags for send, recv */
  1434. #ifdef    MSG_OOB
  1435.     insint(d, "MSG_OOB", MSG_OOB);
  1436. #endif
  1437. #ifdef    MSG_PEEK
  1438.     insint(d, "MSG_PEEK", MSG_PEEK);
  1439. #endif
  1440. #ifdef    MSG_DONTROUTE
  1441.     insint(d, "MSG_DONTROUTE", MSG_DONTROUTE);
  1442. #endif
  1443. #ifdef    MSG_EOR
  1444.     insint(d, "MSG_EOR", MSG_EOR);
  1445. #endif
  1446. #ifdef    MSG_TRUNC
  1447.     insint(d, "MSG_TRUNC", MSG_TRUNC);
  1448. #endif
  1449. #ifdef    MSG_CTRUNC
  1450.     insint(d, "MSG_CTRUNC", MSG_CTRUNC);
  1451. #endif
  1452. #ifdef    MSG_WAITALL
  1453.     insint(d, "MSG_WAITALL", MSG_WAITALL);
  1454. #endif
  1455. #ifdef    MSG_BTAG
  1456.     insint(d, "MSG_BTAG", MSG_BTAG);
  1457. #endif
  1458. #ifdef    MSG_ETAG
  1459.     insint(d, "MSG_ETAG", MSG_ETAG);
  1460. #endif
  1461.  
  1462.     /* Protocol level and numbers, usable for [gs]etsockopt */
  1463. #ifdef    SOL_SOCKET
  1464.     insint(d, "SOL_SOCKET", SOL_SOCKET);
  1465. #endif
  1466. #ifdef    IPPROTO_IP
  1467.     insint(d, "IPPROTO_IP", IPPROTO_IP);
  1468. #endif
  1469. #ifdef    IPPROTO_ICMP
  1470.     insint(d, "IPPROTO_ICMP", IPPROTO_ICMP);
  1471. #endif
  1472. #ifdef    IPPROTO_IGMP
  1473.     insint(d, "IPPROTO_IGMP", IPPROTO_IGMP);
  1474. #endif
  1475. #ifdef    IPPROTO_GGP
  1476.     insint(d, "IPPROTO_GGP", IPPROTO_GGP);
  1477. #endif
  1478. #ifdef    IPPROTO_TCP
  1479.     insint(d, "IPPROTO_TCP", IPPROTO_TCP);
  1480. #endif
  1481. #ifdef    IPPROTO_EGP
  1482.     insint(d, "IPPROTO_EGP", IPPROTO_EGP);
  1483. #endif
  1484. #ifdef    IPPROTO_PUP
  1485.     insint(d, "IPPROTO_PUP", IPPROTO_PUP);
  1486. #endif
  1487. #ifdef    IPPROTO_UDP
  1488.     insint(d, "IPPROTO_UDP", IPPROTO_UDP);
  1489. #endif
  1490. #ifdef    IPPROTO_IDP
  1491.     insint(d, "IPPROTO_IDP", IPPROTO_IDP);
  1492. #endif
  1493. #ifdef    IPPROTO_HELLO
  1494.     insint(d, "IPPROTO_HELLO", IPPROTO_HELLO);
  1495. #endif
  1496. #ifdef    IPPROTO_ND
  1497.     insint(d, "IPPROTO_ND", IPPROTO_ND);
  1498. #endif
  1499. #ifdef    IPPROTO_TP
  1500.     insint(d, "IPPROTO_TP", IPPROTO_TP);
  1501. #endif
  1502. #ifdef    IPPROTO_XTP
  1503.     insint(d, "IPPROTO_XTP", IPPROTO_XTP);
  1504. #endif
  1505. #ifdef    IPPROTO_EON
  1506.     insint(d, "IPPROTO_EON", IPPROTO_EON);
  1507. #endif
  1508. #ifdef    IPPROTO_BIP
  1509.     insint(d, "IPPROTO_BIP", IPPROTO_BIP);
  1510. #endif
  1511. /**/
  1512. #ifdef    IPPROTO_RAW
  1513.     insint(d, "IPPROTO_RAW", IPPROTO_RAW);
  1514. #endif
  1515. #ifdef    IPPROTO_MAX
  1516.     insint(d, "IPPROTO_MAX", IPPROTO_MAX);
  1517. #endif
  1518.  
  1519.     /* Some port configuration */
  1520. #ifdef    IPPORT_RESERVED
  1521.     insint(d, "IPPORT_RESERVED", IPPORT_RESERVED);
  1522. #else
  1523.     insint(d, "IPPORT_RESERVED", 1024);
  1524. #endif
  1525. #ifdef    IPPORT_USERRESERVED
  1526.     insint(d, "IPPORT_USERRESERVED", IPPORT_USERRESERVED);
  1527. #else
  1528.     insint(d, "IPPORT_USERRESERVED", 5000);
  1529. #endif
  1530.  
  1531.     /* Some reserved IP v.4 addresses */
  1532. #ifdef    INADDR_ANY
  1533.     insint(d, "INADDR_ANY", INADDR_ANY);
  1534. #else
  1535.     insint(d, "INADDR_ANY", 0x00000000);
  1536. #endif
  1537. #ifdef    INADDR_BROADCAST
  1538.     insint(d, "INADDR_BROADCAST", INADDR_BROADCAST);
  1539. #else
  1540.     insint(d, "INADDR_BROADCAST", 0xffffffff);
  1541. #endif
  1542. #ifdef    INADDR_LOOPBACK
  1543.     insint(d, "INADDR_LOOPBACK", INADDR_LOOPBACK);
  1544. #else
  1545.     insint(d, "INADDR_LOOPBACK", 0x7F000001);
  1546. #endif
  1547. #ifdef    INADDR_UNSPEC_GROUP
  1548.     insint(d, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
  1549. #else
  1550.     insint(d, "INADDR_UNSPEC_GROUP", 0xe0000000);
  1551. #endif
  1552. #ifdef    INADDR_ALLHOSTS_GROUP
  1553.     insint(d, "INADDR_ALLHOSTS_GROUP", INADDR_ALLHOSTS_GROUP);
  1554. #else
  1555.     insint(d, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
  1556. #endif
  1557. #ifdef    INADDR_MAX_LOCAL_GROUP
  1558.     insint(d, "INADDR_MAX_LOCAL_GROUP", INADDR_MAX_LOCAL_GROUP);
  1559. #else
  1560.     insint(d, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
  1561. #endif
  1562. #ifdef    INADDR_NONE
  1563.     insint(d, "INADDR_NONE", INADDR_NONE);
  1564. #else
  1565.     insint(d, "INADDR_NONE", 0xffffffff);
  1566. #endif
  1567.  
  1568.     /* IP [gs]etsockopt options */
  1569. #ifdef    IP_OPTIONS
  1570.     insint(d, "IP_OPTIONS", IP_OPTIONS);
  1571. #endif
  1572. #ifdef    IP_HDRINCL
  1573.     insint(d, "IP_HDRINCL", IP_HDRINCL);
  1574. #endif
  1575. #ifdef    IP_TOS
  1576.     insint(d, "IP_TOS", IP_TOS);
  1577. #endif
  1578. #ifdef    IP_TTL
  1579.     insint(d, "IP_TTL", IP_TTL);
  1580. #endif
  1581. #ifdef    IP_RECVOPTS
  1582.     insint(d, "IP_RECVOPTS", IP_RECVOPTS);
  1583. #endif
  1584. #ifdef    IP_RECVRETOPTS
  1585.     insint(d, "IP_RECVRETOPTS", IP_RECVRETOPTS);
  1586. #endif
  1587. #ifdef    IP_RECVDSTADDR
  1588.     insint(d, "IP_RECVDSTADDR", IP_RECVDSTADDR);
  1589. #endif
  1590. #ifdef    IP_RETOPTS
  1591.     insint(d, "IP_RETOPTS", IP_RETOPTS);
  1592. #endif
  1593. #ifdef    IP_MULTICAST_IF
  1594.     insint(d, "IP_MULTICAST_IF", IP_MULTICAST_IF);
  1595. #endif
  1596. #ifdef    IP_MULTICAST_TTL
  1597.     insint(d, "IP_MULTICAST_TTL", IP_MULTICAST_TTL);
  1598. #endif
  1599. #ifdef    IP_MULTICAST_LOOP
  1600.     insint(d, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
  1601. #endif
  1602. #ifdef    IP_ADD_MEMBERSHIP
  1603.     insint(d, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
  1604. #endif
  1605. #ifdef    IP_DROP_MEMBERSHIP
  1606.     insint(d, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
  1607. #endif
  1608. }
  1609.