You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

5467 lines
154 KiB

35 years ago
35 years ago
35 years ago
35 years ago
35 years ago
35 years ago
35 years ago
35 years ago
35 years ago
32 years ago
35 years ago
35 years ago
32 years ago
35 years ago
35 years ago
35 years ago
35 years ago
35 years ago
32 years ago
35 years ago
32 years ago
35 years ago
35 years ago
35 years ago
35 years ago
35 years ago
35 years ago
35 years ago
32 years ago
35 years ago
35 years ago
32 years ago
32 years ago
32 years ago
32 years ago
35 years ago
35 years ago
32 years ago
35 years ago
35 years ago
32 years ago
35 years ago
35 years ago
32 years ago
32 years ago
32 years ago
32 years ago
35 years ago
35 years ago
32 years ago
35 years ago
19 years ago
35 years ago
35 years ago
35 years ago
32 years ago
32 years ago
35 years ago
35 years ago
32 years ago
35 years ago
35 years ago
35 years ago
35 years ago
32 years ago
35 years ago
35 years ago
35 years ago
35 years ago
32 years ago
32 years ago
32 years ago
32 years ago
35 years ago
35 years ago
35 years ago
  1. /* Socket module */
  2. /*
  3. This module provides an interface to Berkeley socket IPC.
  4. Limitations:
  5. - Only AF_INET, AF_INET6 and AF_UNIX address families are supported in a
  6. portable manner, though AF_PACKET, AF_NETLINK and AF_TIPC are supported
  7. under Linux.
  8. - No read/write operations (use sendall/recv or makefile instead).
  9. - Additional restrictions apply on some non-Unix platforms (compensated
  10. for by socket.py).
  11. Module interface:
  12. - socket.error: exception raised for socket specific errors
  13. - socket.gaierror: exception raised for getaddrinfo/getnameinfo errors,
  14. a subclass of socket.error
  15. - socket.herror: exception raised for gethostby* errors,
  16. a subclass of socket.error
  17. - socket.fromfd(fd, family, type[, proto]) --> new socket object (created
  18. from an existing file descriptor)
  19. - socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')
  20. - socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])
  21. - socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com')
  22. - socket.getprotobyname(protocolname) --> protocol number
  23. - socket.getservbyname(servicename[, protocolname]) --> port number
  24. - socket.getservbyport(portnumber[, protocolname]) --> service name
  25. - socket.socket([family[, type [, proto]]]) --> new socket object
  26. - socket.socketpair([family[, type [, proto]]]) --> (socket, socket)
  27. - socket.ntohs(16 bit value) --> new int object
  28. - socket.ntohl(32 bit value) --> new int object
  29. - socket.htons(16 bit value) --> new int object
  30. - socket.htonl(32 bit value) --> new int object
  31. - socket.getaddrinfo(host, port [, family, socktype, proto, flags])
  32. --> List of (family, socktype, proto, canonname, sockaddr)
  33. - socket.getnameinfo(sockaddr, flags) --> (host, port)
  34. - socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
  35. - socket.has_ipv6: boolean value indicating if IPv6 is supported
  36. - socket.inet_aton(IP address) -> 32-bit packed IP representation
  37. - socket.inet_ntoa(packed IP) -> IP address string
  38. - socket.getdefaulttimeout() -> None | float
  39. - socket.setdefaulttimeout(None | float)
  40. - an Internet socket address is a pair (hostname, port)
  41. where hostname can be anything recognized by gethostbyname()
  42. (including the dd.dd.dd.dd notation) and port is in host byte order
  43. - where a hostname is returned, the dd.dd.dd.dd notation is used
  44. - a UNIX domain socket address is a string specifying the pathname
  45. - an AF_PACKET socket address is a tuple containing a string
  46. specifying the ethernet interface and an integer specifying
  47. the Ethernet protocol number to be received. For example:
  48. ("eth0",0x1234). Optional 3rd,4th,5th elements in the tuple
  49. specify packet-type and ha-type/addr.
  50. - an AF_TIPC socket address is expressed as
  51. (addr_type, v1, v2, v3 [, scope]); where addr_type can be one of:
  52. TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, and TIPC_ADDR_ID;
  53. and scope can be one of:
  54. TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and TIPC_NODE_SCOPE.
  55. The meaning of v1, v2 and v3 depends on the value of addr_type:
  56. if addr_type is TIPC_ADDR_NAME:
  57. v1 is the server type
  58. v2 is the port identifier
  59. v3 is ignored
  60. if addr_type is TIPC_ADDR_NAMESEQ:
  61. v1 is the server type
  62. v2 is the lower port number
  63. v3 is the upper port number
  64. if addr_type is TIPC_ADDR_ID:
  65. v1 is the node
  66. v2 is the ref
  67. v3 is ignored
  68. Local naming conventions:
  69. - names starting with sock_ are socket object methods
  70. - names starting with socket_ are module-level functions
  71. - names starting with PySocket are exported through socketmodule.h
  72. */
  73. #ifdef __APPLE__
  74. /*
  75. * inet_aton is not available on OSX 10.3, yet we want to use a binary
  76. * that was build on 10.4 or later to work on that release, weak linking
  77. * comes to the rescue.
  78. */
  79. # pragma weak inet_aton
  80. #endif
  81. #include "Python.h"
  82. #include "structmember.h"
  83. #undef MAX
  84. #define MAX(x, y) ((x) < (y) ? (y) : (x))
  85. /* Socket object documentation */
  86. PyDoc_STRVAR(sock_doc,
  87. "socket([family[, type[, proto]]]) -> socket object\n\
  88. \n\
  89. Open a socket of the given type. The family argument specifies the\n\
  90. address family; it defaults to AF_INET. The type argument specifies\n\
  91. whether this is a stream (SOCK_STREAM, this is the default)\n\
  92. or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0,\n\
  93. specifying the default protocol. Keyword arguments are accepted.\n\
  94. \n\
  95. A socket object represents one endpoint of a network connection.\n\
  96. \n\
  97. Methods of socket objects (keyword arguments not allowed):\n\
  98. \n\
  99. accept() -- accept a connection, returning new socket and client address\n\
  100. bind(addr) -- bind the socket to a local address\n\
  101. close() -- close the socket\n\
  102. connect(addr) -- connect the socket to a remote address\n\
  103. connect_ex(addr) -- connect, return an error code instead of an exception\n\
  104. dup() -- return a new socket object identical to the current one [*]\n\
  105. fileno() -- return underlying file descriptor\n\
  106. getpeername() -- return remote address [*]\n\
  107. getsockname() -- return local address\n\
  108. getsockopt(level, optname[, buflen]) -- get socket options\n\
  109. gettimeout() -- return timeout or None\n\
  110. listen(n) -- start listening for incoming connections\n\
  111. makefile([mode, [bufsize]]) -- return a file object for the socket [*]\n\
  112. recv(buflen[, flags]) -- receive data\n\
  113. recv_into(buffer[, nbytes[, flags]]) -- receive data (into a buffer)\n\
  114. recvfrom(buflen[, flags]) -- receive data and sender\'s address\n\
  115. recvfrom_into(buffer[, nbytes, [, flags])\n\
  116. -- receive data and sender\'s address (into a buffer)\n\
  117. sendall(data[, flags]) -- send all data\n\
  118. send(data[, flags]) -- send data, may not send all of it\n\
  119. sendto(data[, flags], addr) -- send data to a given address\n\
  120. setblocking(0 | 1) -- set or clear the blocking I/O flag\n\
  121. setsockopt(level, optname, value) -- set socket options\n\
  122. settimeout(None | float) -- set or clear the timeout\n\
  123. shutdown(how) -- shut down traffic in one or both directions\n\
  124. \n\
  125. [*] not available on all platforms!");
  126. /* XXX This is a terrible mess of platform-dependent preprocessor hacks.
  127. I hope some day someone can clean this up please... */
  128. /* Hacks for gethostbyname_r(). On some non-Linux platforms, the configure
  129. script doesn't get this right, so we hardcode some platform checks below.
  130. On the other hand, not all Linux versions agree, so there the settings
  131. computed by the configure script are needed! */
  132. #ifndef linux
  133. # undef HAVE_GETHOSTBYNAME_R_3_ARG
  134. # undef HAVE_GETHOSTBYNAME_R_5_ARG
  135. # undef HAVE_GETHOSTBYNAME_R_6_ARG
  136. #endif
  137. #ifndef WITH_THREAD
  138. # undef HAVE_GETHOSTBYNAME_R
  139. #endif
  140. #ifdef HAVE_GETHOSTBYNAME_R
  141. # if defined(_AIX) || defined(__osf__)
  142. # define HAVE_GETHOSTBYNAME_R_3_ARG
  143. # elif defined(__sun) || defined(__sgi)
  144. # define HAVE_GETHOSTBYNAME_R_5_ARG
  145. # elif defined(linux)
  146. /* Rely on the configure script */
  147. # else
  148. # undef HAVE_GETHOSTBYNAME_R
  149. # endif
  150. #endif
  151. #if !defined(HAVE_GETHOSTBYNAME_R) && defined(WITH_THREAD) && \
  152. !defined(MS_WINDOWS)
  153. # define USE_GETHOSTBYNAME_LOCK
  154. #endif
  155. /* To use __FreeBSD_version */
  156. #ifdef HAVE_SYS_PARAM_H
  157. #include <sys/param.h>
  158. #endif
  159. /* On systems on which getaddrinfo() is believed to not be thread-safe,
  160. (this includes the getaddrinfo emulation) protect access with a lock. */
  161. #if defined(WITH_THREAD) && (defined(__APPLE__) || \
  162. (defined(__FreeBSD__) && __FreeBSD_version+0 < 503000) || \
  163. defined(__OpenBSD__) || defined(__NetBSD__) || \
  164. defined(__VMS) || !defined(HAVE_GETADDRINFO))
  165. #define USE_GETADDRINFO_LOCK
  166. #endif
  167. #ifdef USE_GETADDRINFO_LOCK
  168. #define ACQUIRE_GETADDRINFO_LOCK PyThread_acquire_lock(netdb_lock, 1);
  169. #define RELEASE_GETADDRINFO_LOCK PyThread_release_lock(netdb_lock);
  170. #else
  171. #define ACQUIRE_GETADDRINFO_LOCK
  172. #define RELEASE_GETADDRINFO_LOCK
  173. #endif
  174. #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
  175. # include "pythread.h"
  176. #endif
  177. #if defined(PYCC_VACPP)
  178. # include <types.h>
  179. # include <io.h>
  180. # include <sys/ioctl.h>
  181. # include <utils.h>
  182. # include <ctype.h>
  183. #endif
  184. #if defined(__VMS)
  185. # include <ioctl.h>
  186. #endif
  187. #if defined(PYOS_OS2)
  188. # define INCL_DOS
  189. # define INCL_DOSERRORS
  190. # define INCL_NOPMAPI
  191. # include <os2.h>
  192. #endif
  193. #if defined(__sgi) && _COMPILER_VERSION>700 && !_SGIAPI
  194. /* make sure that the reentrant (gethostbyaddr_r etc)
  195. functions are declared correctly if compiling with
  196. MIPSPro 7.x in ANSI C mode (default) */
  197. /* XXX Using _SGIAPI is the wrong thing,
  198. but I don't know what the right thing is. */
  199. #undef _SGIAPI /* to avoid warning */
  200. #define _SGIAPI 1
  201. #undef _XOPEN_SOURCE
  202. #include <sys/socket.h>
  203. #include <sys/types.h>
  204. #include <netinet/in.h>
  205. #ifdef _SS_ALIGNSIZE
  206. #define HAVE_GETADDRINFO 1
  207. #define HAVE_GETNAMEINFO 1
  208. #endif
  209. #define HAVE_INET_PTON
  210. #include <netdb.h>
  211. #endif
  212. /* Irix 6.5 fails to define this variable at all. This is needed
  213. for both GCC and SGI's compiler. I'd say that the SGI headers
  214. are just busted. Same thing for Solaris. */
  215. #if (defined(__sgi) || defined(sun)) && !defined(INET_ADDRSTRLEN)
  216. #define INET_ADDRSTRLEN 16
  217. #endif
  218. /* Generic includes */
  219. #ifdef HAVE_SYS_TYPES_H
  220. #include <sys/types.h>
  221. #endif
  222. /* Generic socket object definitions and includes */
  223. #define PySocket_BUILDING_SOCKET
  224. #include "socketmodule.h"
  225. /* Addressing includes */
  226. #ifndef MS_WINDOWS
  227. /* Non-MS WINDOWS includes */
  228. # include <netdb.h>
  229. /* Headers needed for inet_ntoa() and inet_addr() */
  230. # ifdef __BEOS__
  231. # include <net/netdb.h>
  232. # elif defined(PYOS_OS2) && defined(PYCC_VACPP)
  233. # include <netdb.h>
  234. typedef size_t socklen_t;
  235. # else
  236. # include <arpa/inet.h>
  237. # endif
  238. # ifndef RISCOS
  239. # include <fcntl.h>
  240. # else
  241. # include <sys/ioctl.h>
  242. # include <socklib.h>
  243. # define NO_DUP
  244. int h_errno; /* not used */
  245. # define INET_ADDRSTRLEN 16
  246. # endif
  247. #else
  248. /* MS_WINDOWS includes */
  249. # ifdef HAVE_FCNTL_H
  250. # include <fcntl.h>
  251. # endif
  252. #endif
  253. #include <stddef.h>
  254. #ifndef offsetof
  255. # define offsetof(type, member) ((size_t)(&((type *)0)->member))
  256. #endif
  257. #ifndef O_NONBLOCK
  258. # define O_NONBLOCK O_NDELAY
  259. #endif
  260. /* include Python's addrinfo.h unless it causes trouble */
  261. #if defined(__sgi) && _COMPILER_VERSION>700 && defined(_SS_ALIGNSIZE)
  262. /* Do not include addinfo.h on some newer IRIX versions.
  263. * _SS_ALIGNSIZE is defined in sys/socket.h by 6.5.21,
  264. * for example, but not by 6.5.10.
  265. */
  266. #elif defined(_MSC_VER) && _MSC_VER>1201
  267. /* Do not include addrinfo.h for MSVC7 or greater. 'addrinfo' and
  268. * EAI_* constants are defined in (the already included) ws2tcpip.h.
  269. */
  270. #else
  271. # include "addrinfo.h"
  272. #endif
  273. #ifndef HAVE_INET_PTON
  274. #if !defined(NTDDI_VERSION) || (NTDDI_VERSION < NTDDI_LONGHORN)
  275. int inet_pton(int af, const char *src, void *dst);
  276. const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
  277. #endif
  278. #endif
  279. #ifdef __APPLE__
  280. /* On OS X, getaddrinfo returns no error indication of lookup
  281. failure, so we must use the emulation instead of the libinfo
  282. implementation. Unfortunately, performing an autoconf test
  283. for this bug would require DNS access for the machine performing
  284. the configuration, which is not acceptable. Therefore, we
  285. determine the bug just by checking for __APPLE__. If this bug
  286. gets ever fixed, perhaps checking for sys/version.h would be
  287. appropriate, which is 10/0 on the system with the bug. */
  288. #ifndef HAVE_GETNAMEINFO
  289. /* This bug seems to be fixed in Jaguar. Ths easiest way I could
  290. Find to check for Jaguar is that it has getnameinfo(), which
  291. older releases don't have */
  292. #undef HAVE_GETADDRINFO
  293. #endif
  294. #ifdef HAVE_INET_ATON
  295. #define USE_INET_ATON_WEAKLINK
  296. #endif
  297. #endif
  298. /* I know this is a bad practice, but it is the easiest... */
  299. #if !defined(HAVE_GETADDRINFO)
  300. /* avoid clashes with the C library definition of the symbol. */
  301. #define getaddrinfo fake_getaddrinfo
  302. #define gai_strerror fake_gai_strerror
  303. #define freeaddrinfo fake_freeaddrinfo
  304. #include "getaddrinfo.c"
  305. #endif
  306. #if !defined(HAVE_GETNAMEINFO)
  307. #define getnameinfo fake_getnameinfo
  308. #include "getnameinfo.c"
  309. #endif
  310. #if defined(MS_WINDOWS) || defined(__BEOS__)
  311. /* BeOS suffers from the same socket dichotomy as Win32... - [cjh] */
  312. /* seem to be a few differences in the API */
  313. #define SOCKETCLOSE closesocket
  314. #define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */
  315. #endif
  316. #ifdef MS_WIN32
  317. #define EAFNOSUPPORT WSAEAFNOSUPPORT
  318. #define snprintf _snprintf
  319. #endif
  320. #if defined(PYOS_OS2) && !defined(PYCC_GCC)
  321. #define SOCKETCLOSE soclose
  322. #define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
  323. #endif
  324. #ifndef SOCKETCLOSE
  325. #define SOCKETCLOSE close
  326. #endif
  327. #if (defined(HAVE_BLUETOOTH_H) || defined(HAVE_BLUETOOTH_BLUETOOTH_H)) && !defined(__NetBSD__) && !defined(__DragonFly__)
  328. #define USE_BLUETOOTH 1
  329. #if defined(__FreeBSD__)
  330. #define BTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP
  331. #define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM
  332. #define BTPROTO_HCI BLUETOOTH_PROTO_HCI
  333. #define SOL_HCI SOL_HCI_RAW
  334. #define HCI_FILTER SO_HCI_RAW_FILTER
  335. #define sockaddr_l2 sockaddr_l2cap
  336. #define sockaddr_rc sockaddr_rfcomm
  337. #define hci_dev hci_node
  338. #define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb)
  339. #define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)
  340. #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
  341. #elif defined(__NetBSD__) || defined(__DragonFly__)
  342. #define sockaddr_l2 sockaddr_bt
  343. #define sockaddr_rc sockaddr_bt
  344. #define sockaddr_hci sockaddr_bt
  345. #define sockaddr_sco sockaddr_bt
  346. #define SOL_HCI BTPROTO_HCI
  347. #define HCI_DATA_DIR SO_HCI_DIRECTION
  348. #define _BT_L2_MEMB(sa, memb) ((sa)->bt_##memb)
  349. #define _BT_RC_MEMB(sa, memb) ((sa)->bt_##memb)
  350. #define _BT_HCI_MEMB(sa, memb) ((sa)->bt_##memb)
  351. #define _BT_SCO_MEMB(sa, memb) ((sa)->bt_##memb)
  352. #else
  353. #define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb)
  354. #define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb)
  355. #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
  356. #define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)
  357. #endif
  358. #endif
  359. #ifdef __VMS
  360. /* TCP/IP Services for VMS uses a maximum send/recv buffer length */
  361. #define SEGMENT_SIZE (32 * 1024 -1)
  362. #endif
  363. #define SAS2SA(x) ((struct sockaddr *)(x))
  364. /*
  365. * Constants for getnameinfo()
  366. */
  367. #if !defined(NI_MAXHOST)
  368. #define NI_MAXHOST 1025
  369. #endif
  370. #if !defined(NI_MAXSERV)
  371. #define NI_MAXSERV 32
  372. #endif
  373. /* XXX There's a problem here: *static* functions are not supposed to have
  374. a Py prefix (or use CapitalizedWords). Later... */
  375. /* Global variable holding the exception type for errors detected
  376. by this module (but not argument type or memory errors, etc.). */
  377. static PyObject *socket_error;
  378. static PyObject *socket_herror;
  379. static PyObject *socket_gaierror;
  380. static PyObject *socket_timeout;
  381. #ifdef RISCOS
  382. /* Global variable which is !=0 if Python is running in a RISC OS taskwindow */
  383. static int taskwindow;
  384. #endif
  385. /* A forward reference to the socket type object.
  386. The sock_type variable contains pointers to various functions,
  387. some of which call new_sockobject(), which uses sock_type, so
  388. there has to be a circular reference. */
  389. static PyTypeObject sock_type;
  390. #if defined(HAVE_POLL_H)
  391. #include <poll.h>
  392. #elif defined(HAVE_SYS_POLL_H)
  393. #include <sys/poll.h>
  394. #endif
  395. #ifdef HAVE_POLL
  396. /* Instead of select(), we'll use poll() since poll() works on any fd. */
  397. #define IS_SELECTABLE(s) 1
  398. /* Can we call select() with this socket without a buffer overrun? */
  399. #else
  400. /* If there's no timeout left, we don't have to call select, so it's a safe,
  401. * little white lie. */
  402. #define IS_SELECTABLE(s) (_PyIsSelectable_fd((s)->sock_fd) || (s)->sock_timeout <= 0.0)
  403. #endif
  404. static PyObject*
  405. select_error(void)
  406. {
  407. PyErr_SetString(socket_error, "unable to select on socket");
  408. return NULL;
  409. }
  410. /* Convenience function to raise an error according to errno
  411. and return a NULL pointer from a function. */
  412. static PyObject *
  413. set_error(void)
  414. {
  415. #ifdef MS_WINDOWS
  416. int err_no = WSAGetLastError();
  417. /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which
  418. recognizes the error codes used by both GetLastError() and
  419. WSAGetLastError */
  420. if (err_no)
  421. return PyErr_SetExcFromWindowsErr(socket_error, err_no);
  422. #endif
  423. #if defined(PYOS_OS2) && !defined(PYCC_GCC)
  424. if (sock_errno() != NO_ERROR) {
  425. APIRET rc;
  426. ULONG msglen;
  427. char outbuf[100];
  428. int myerrorcode = sock_errno();
  429. /* Retrieve socket-related error message from MPTN.MSG file */
  430. rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf),
  431. myerrorcode - SOCBASEERR + 26,
  432. "mptn.msg",
  433. &msglen);
  434. if (rc == NO_ERROR) {
  435. PyObject *v;
  436. /* OS/2 doesn't guarantee a terminator */
  437. outbuf[msglen] = '\0';
  438. if (strlen(outbuf) > 0) {
  439. /* If non-empty msg, trim CRLF */
  440. char *lastc = &outbuf[ strlen(outbuf)-1 ];
  441. while (lastc > outbuf &&
  442. isspace(Py_CHARMASK(*lastc))) {
  443. /* Trim trailing whitespace (CRLF) */
  444. *lastc-- = '\0';
  445. }
  446. }
  447. v = Py_BuildValue("(is)", myerrorcode, outbuf);
  448. if (v != NULL) {
  449. PyErr_SetObject(socket_error, v);
  450. Py_DECREF(v);
  451. }
  452. return NULL;
  453. }
  454. }
  455. #endif
  456. #if defined(RISCOS)
  457. if (_inet_error.errnum != NULL) {
  458. PyObject *v;
  459. v = Py_BuildValue("(is)", errno, _inet_err());
  460. if (v != NULL) {
  461. PyErr_SetObject(socket_error, v);
  462. Py_DECREF(v);
  463. }
  464. return NULL;
  465. }
  466. #endif
  467. return PyErr_SetFromErrno(socket_error);
  468. }
  469. static PyObject *
  470. set_herror(int h_error)
  471. {
  472. PyObject *v;
  473. #ifdef HAVE_HSTRERROR
  474. v = Py_BuildValue("(is)", h_error, (char *)hstrerror(h_error));
  475. #else
  476. v = Py_BuildValue("(is)", h_error, "host not found");
  477. #endif
  478. if (v != NULL) {
  479. PyErr_SetObject(socket_herror, v);
  480. Py_DECREF(v);
  481. }
  482. return NULL;
  483. }
  484. static PyObject *
  485. set_gaierror(int error)
  486. {
  487. PyObject *v;
  488. #ifdef EAI_SYSTEM
  489. /* EAI_SYSTEM is not available on Windows XP. */
  490. if (error == EAI_SYSTEM)
  491. return set_error();
  492. #endif
  493. #ifdef HAVE_GAI_STRERROR
  494. v = Py_BuildValue("(is)", error, gai_strerror(error));
  495. #else
  496. v = Py_BuildValue("(is)", error, "getaddrinfo failed");
  497. #endif
  498. if (v != NULL) {
  499. PyErr_SetObject(socket_gaierror, v);
  500. Py_DECREF(v);
  501. }
  502. return NULL;
  503. }
  504. #ifdef __VMS
  505. /* Function to send in segments */
  506. static int
  507. sendsegmented(int sock_fd, char *buf, int len, int flags)
  508. {
  509. int n = 0;
  510. int remaining = len;
  511. while (remaining > 0) {
  512. unsigned int segment;
  513. segment = (remaining >= SEGMENT_SIZE ? SEGMENT_SIZE : remaining);
  514. n = send(sock_fd, buf, segment, flags);
  515. if (n < 0) {
  516. return n;
  517. }
  518. remaining -= segment;
  519. buf += segment;
  520. } /* end while */
  521. return len;
  522. }
  523. #endif
  524. /* Function to perform the setting of socket blocking mode
  525. internally. block = (1 | 0). */
  526. static int
  527. internal_setblocking(PySocketSockObject *s, int block)
  528. {
  529. #ifndef RISCOS
  530. #ifndef MS_WINDOWS
  531. int delay_flag;
  532. #endif
  533. #endif
  534. Py_BEGIN_ALLOW_THREADS
  535. #ifdef __BEOS__
  536. block = !block;
  537. setsockopt(s->sock_fd, SOL_SOCKET, SO_NONBLOCK,
  538. (void *)(&block), sizeof(int));
  539. #else
  540. #ifndef RISCOS
  541. #ifndef MS_WINDOWS
  542. #if defined(PYOS_OS2) && !defined(PYCC_GCC)
  543. block = !block;
  544. ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block));
  545. #elif defined(__VMS)
  546. block = !block;
  547. ioctl(s->sock_fd, FIONBIO, (unsigned int *)&block);
  548. #else /* !PYOS_OS2 && !__VMS */
  549. delay_flag = fcntl(s->sock_fd, F_GETFL, 0);
  550. if (block)
  551. delay_flag &= (~O_NONBLOCK);
  552. else
  553. delay_flag |= O_NONBLOCK;
  554. fcntl(s->sock_fd, F_SETFL, delay_flag);
  555. #endif /* !PYOS_OS2 */
  556. #else /* MS_WINDOWS */
  557. block = !block;
  558. ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
  559. #endif /* MS_WINDOWS */
  560. #else /* RISCOS */
  561. block = !block;
  562. socketioctl(s->sock_fd, FIONBIO, (u_long*)&block);
  563. #endif /* RISCOS */
  564. #endif /* __BEOS__ */
  565. Py_END_ALLOW_THREADS
  566. /* Since these don't return anything */
  567. return 1;
  568. }
  569. /* Do a select()/poll() on the socket, if necessary (sock_timeout > 0).
  570. The argument writing indicates the direction.
  571. This does not raise an exception; we'll let our caller do that
  572. after they've reacquired the interpreter lock.
  573. Returns 1 on timeout, -1 on error, 0 otherwise. */
  574. static int
  575. internal_select(PySocketSockObject *s, int writing)
  576. {
  577. int n;
  578. /* Nothing to do unless we're in timeout mode (not non-blocking) */
  579. if (s->sock_timeout <= 0.0)
  580. return 0;
  581. /* Guard against closed socket */
  582. if (s->sock_fd < 0)
  583. return 0;
  584. /* Prefer poll, if available, since you can poll() any fd
  585. * which can't be done with select(). */
  586. #ifdef HAVE_POLL
  587. {
  588. struct pollfd pollfd;
  589. int timeout;
  590. pollfd.fd = s->sock_fd;
  591. pollfd.events = writing ? POLLOUT : POLLIN;
  592. /* s->sock_timeout is in seconds, timeout in ms */
  593. timeout = (int)(s->sock_timeout * 1000 + 0.5);
  594. n = poll(&pollfd, 1, timeout);
  595. }
  596. #else
  597. {
  598. /* Construct the arguments to select */
  599. fd_set fds;
  600. struct timeval tv;
  601. tv.tv_sec = (int)s->sock_timeout;
  602. tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
  603. FD_ZERO(&fds);
  604. FD_SET(s->sock_fd, &fds);
  605. /* See if the socket is ready */
  606. if (writing)
  607. n = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
  608. else
  609. n = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
  610. }
  611. #endif
  612. if (n < 0)
  613. return -1;
  614. if (n == 0)
  615. return 1;
  616. return 0;
  617. }
  618. /* Initialize a new socket object. */
  619. static double defaulttimeout = -1.0; /* Default timeout for new sockets */
  620. PyMODINIT_FUNC
  621. init_sockobject(PySocketSockObject *s,
  622. SOCKET_T fd, int family, int type, int proto)
  623. {
  624. #ifdef RISCOS
  625. int block = 1;
  626. #endif
  627. s->sock_fd = fd;
  628. s->sock_family = family;
  629. s->sock_type = type;
  630. s->sock_proto = proto;
  631. s->sock_timeout = defaulttimeout;
  632. s->errorhandler = &set_error;
  633. if (defaulttimeout >= 0.0)
  634. internal_setblocking(s, 0);
  635. #ifdef RISCOS
  636. if (taskwindow)
  637. socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
  638. #endif
  639. }
  640. /* Create a new socket object.
  641. This just creates the object and initializes it.
  642. If the creation fails, return NULL and set an exception (implicit
  643. in NEWOBJ()). */
  644. static PySocketSockObject *
  645. new_sockobject(SOCKET_T fd, int family, int type, int proto)
  646. {
  647. PySocketSockObject *s;
  648. s = (PySocketSockObject *)
  649. PyType_GenericNew(&sock_type, NULL, NULL);
  650. if (s != NULL)
  651. init_sockobject(s, fd, family, type, proto);
  652. return s;
  653. }
  654. /* Lock to allow python interpreter to continue, but only allow one
  655. thread to be in gethostbyname or getaddrinfo */
  656. #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
  657. static PyThread_type_lock netdb_lock;
  658. #endif
  659. /* Convert a string specifying a host name or one of a few symbolic
  660. names to a numeric IP address. This usually calls gethostbyname()
  661. to do the work; the names "" and "<broadcast>" are special.
  662. Return the length (IPv4 should be 4 bytes), or negative if
  663. an error occurred; then an exception is raised. */
  664. static int
  665. setipaddr(char *name, struct sockaddr *addr_ret, size_t addr_ret_size, int af)
  666. {
  667. struct addrinfo hints, *res;
  668. int error;
  669. int d1, d2, d3, d4;
  670. char ch;
  671. memset((void *) addr_ret, '\0', sizeof(*addr_ret));
  672. if (name[0] == '\0') {
  673. int siz;
  674. memset(&hints, 0, sizeof(hints));
  675. hints.ai_family = af;
  676. hints.ai_socktype = SOCK_DGRAM; /*dummy*/
  677. hints.ai_flags = AI_PASSIVE;
  678. Py_BEGIN_ALLOW_THREADS
  679. ACQUIRE_GETADDRINFO_LOCK
  680. error = getaddrinfo(NULL, "0", &hints, &res);
  681. Py_END_ALLOW_THREADS
  682. /* We assume that those thread-unsafe getaddrinfo() versions
  683. *are* safe regarding their return value, ie. that a
  684. subsequent call to getaddrinfo() does not destroy the
  685. outcome of the first call. */
  686. RELEASE_GETADDRINFO_LOCK
  687. if (error) {
  688. set_gaierror(error);
  689. return -1;
  690. }
  691. switch (res->ai_family) {
  692. case AF_INET:
  693. siz = 4;
  694. break;
  695. #ifdef ENABLE_IPV6
  696. case AF_INET6:
  697. siz = 16;
  698. break;
  699. #endif
  700. default:
  701. freeaddrinfo(res);
  702. PyErr_SetString(socket_error,
  703. "unsupported address family");
  704. return -1;
  705. }
  706. if (res->ai_next) {
  707. freeaddrinfo(res);
  708. PyErr_SetString(socket_error,
  709. "wildcard resolved to multiple address");
  710. return -1;
  711. }
  712. if (res->ai_addrlen < addr_ret_size)
  713. addr_ret_size = res->ai_addrlen;
  714. memcpy(addr_ret, res->ai_addr, addr_ret_size);
  715. freeaddrinfo(res);
  716. return siz;
  717. }
  718. if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
  719. struct sockaddr_in *sin;
  720. if (af != AF_INET && af != AF_UNSPEC) {
  721. PyErr_SetString(socket_error,
  722. "address family mismatched");
  723. return -1;
  724. }
  725. sin = (struct sockaddr_in *)addr_ret;
  726. memset((void *) sin, '\0', sizeof(*sin));
  727. sin->sin_family = AF_INET;
  728. #ifdef HAVE_SOCKADDR_SA_LEN
  729. sin->sin_len = sizeof(*sin);
  730. #endif
  731. sin->sin_addr.s_addr = INADDR_BROADCAST;
  732. return sizeof(sin->sin_addr);
  733. }
  734. if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 &&
  735. 0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 &&
  736. 0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) {
  737. struct sockaddr_in *sin;
  738. sin = (struct sockaddr_in *)addr_ret;
  739. sin->sin_addr.s_addr = htonl(
  740. ((long) d1 << 24) | ((long) d2 << 16) |
  741. ((long) d3 << 8) | ((long) d4 << 0));
  742. sin->sin_family = AF_INET;
  743. #ifdef HAVE_SOCKADDR_SA_LEN
  744. sin->sin_len = sizeof(*sin);
  745. #endif
  746. return 4;
  747. }
  748. memset(&hints, 0, sizeof(hints));
  749. hints.ai_family = af;
  750. Py_BEGIN_ALLOW_THREADS
  751. ACQUIRE_GETADDRINFO_LOCK
  752. error = getaddrinfo(name, NULL, &hints, &res);
  753. #if defined(__digital__) && defined(__unix__)
  754. if (error == EAI_NONAME && af == AF_UNSPEC) {
  755. /* On Tru64 V5.1, numeric-to-addr conversion fails
  756. if no address family is given. Assume IPv4 for now.*/
  757. hints.ai_family = AF_INET;
  758. error = getaddrinfo(name, NULL, &hints, &res);
  759. }
  760. #endif
  761. Py_END_ALLOW_THREADS
  762. RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
  763. if (error) {
  764. set_gaierror(error);
  765. return -1;
  766. }
  767. if (res->ai_addrlen < addr_ret_size)
  768. addr_ret_size = res->ai_addrlen;
  769. memcpy((char *) addr_ret, res->ai_addr, addr_ret_size);
  770. freeaddrinfo(res);
  771. switch (addr_ret->sa_family) {
  772. case AF_INET:
  773. return 4;
  774. #ifdef ENABLE_IPV6
  775. case AF_INET6:
  776. return 16;
  777. #endif
  778. default:
  779. PyErr_SetString(socket_error, "unknown address family");
  780. return -1;
  781. }
  782. }
  783. /* Create a string object representing an IP address.
  784. This is always a string of the form 'dd.dd.dd.dd' (with variable
  785. size numbers). */
  786. static PyObject *
  787. makeipaddr(struct sockaddr *addr, int addrlen)
  788. {
  789. char buf[NI_MAXHOST];
  790. int error;
  791. error = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0,
  792. NI_NUMERICHOST);
  793. if (error) {
  794. set_gaierror(error);
  795. return NULL;
  796. }
  797. return PyString_FromString(buf);
  798. }
  799. #ifdef USE_BLUETOOTH
  800. /* Convert a string representation of a Bluetooth address into a numeric
  801. address. Returns the length (6), or raises an exception and returns -1 if
  802. an error occurred. */
  803. static int
  804. setbdaddr(char *name, bdaddr_t *bdaddr)
  805. {
  806. unsigned int b0, b1, b2, b3, b4, b5;
  807. char ch;
  808. int n;
  809. n = sscanf(name, "%X:%X:%X:%X:%X:%X%c",
  810. &b5, &b4, &b3, &b2, &b1, &b0, &ch);
  811. if (n == 6 && (b0 | b1 | b2 | b3 | b4 | b5) < 256) {
  812. bdaddr->b[0] = b0;
  813. bdaddr->b[1] = b1;
  814. bdaddr->b[2] = b2;
  815. bdaddr->b[3] = b3;
  816. bdaddr->b[4] = b4;
  817. bdaddr->b[5] = b5;
  818. return 6;
  819. } else {
  820. PyErr_SetString(socket_error, "bad bluetooth address");
  821. return -1;
  822. }
  823. }
  824. /* Create a string representation of the Bluetooth address. This is always a
  825. string of the form 'XX:XX:XX:XX:XX:XX' where XX is a two digit hexadecimal
  826. value (zero padded if necessary). */
  827. static PyObject *
  828. makebdaddr(bdaddr_t *bdaddr)
  829. {
  830. char buf[(6 * 2) + 5 + 1];
  831. sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
  832. bdaddr->b[5], bdaddr->b[4], bdaddr->b[3],
  833. bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]);
  834. return PyString_FromString(buf);
  835. }
  836. #endif
  837. /* Create an object representing the given socket address,
  838. suitable for passing it back to bind(), connect() etc.
  839. The family field of the sockaddr structure is inspected
  840. to determine what kind of address it really is. */
  841. /*ARGSUSED*/
  842. static PyObject *
  843. makesockaddr(int sockfd, struct sockaddr *addr, int addrlen, int proto)
  844. {
  845. if (addrlen == 0) {
  846. /* No address -- may be recvfrom() from known socket */
  847. Py_INCREF(Py_None);
  848. return Py_None;
  849. }
  850. #ifdef __BEOS__
  851. /* XXX: BeOS version of accept() doesn't set family correctly */
  852. addr->sa_family = AF_INET;
  853. #endif
  854. switch (addr->sa_family) {
  855. case AF_INET:
  856. {
  857. struct sockaddr_in *a;
  858. PyObject *addrobj = makeipaddr(addr, sizeof(*a));
  859. PyObject *ret = NULL;
  860. if (addrobj) {
  861. a = (struct sockaddr_in *)addr;
  862. ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
  863. Py_DECREF(addrobj);
  864. }
  865. return ret;
  866. }
  867. #if defined(AF_UNIX)
  868. case AF_UNIX:
  869. {
  870. struct sockaddr_un *a = (struct sockaddr_un *) addr;
  871. #ifdef linux
  872. if (a->sun_path[0] == 0) { /* Linux abstract namespace */
  873. addrlen -= offsetof(struct sockaddr_un, sun_path);
  874. return PyString_FromStringAndSize(a->sun_path,
  875. addrlen);
  876. }
  877. else
  878. #endif /* linux */
  879. {
  880. /* regular NULL-terminated string */
  881. return PyString_FromString(a->sun_path);
  882. }
  883. }
  884. #endif /* AF_UNIX */
  885. #if defined(AF_NETLINK)
  886. case AF_NETLINK:
  887. {
  888. struct sockaddr_nl *a = (struct sockaddr_nl *) addr;
  889. return Py_BuildValue("II", a->nl_pid, a->nl_groups);
  890. }
  891. #endif /* AF_NETLINK */
  892. #ifdef ENABLE_IPV6
  893. case AF_INET6:
  894. {
  895. struct sockaddr_in6 *a;
  896. PyObject *addrobj = makeipaddr(addr, sizeof(*a));
  897. PyObject *ret = NULL;
  898. if (addrobj) {
  899. a = (struct sockaddr_in6 *)addr;
  900. ret = Py_BuildValue("OiII",
  901. addrobj,
  902. ntohs(a->sin6_port),
  903. ntohl(a->sin6_flowinfo),
  904. a->sin6_scope_id);
  905. Py_DECREF(addrobj);
  906. }
  907. return ret;
  908. }
  909. #endif
  910. #ifdef USE_BLUETOOTH
  911. case AF_BLUETOOTH:
  912. switch (proto) {
  913. case BTPROTO_L2CAP:
  914. {
  915. struct sockaddr_l2 *a = (struct sockaddr_l2 *) addr;
  916. PyObject *addrobj = makebdaddr(&_BT_L2_MEMB(a, bdaddr));
  917. PyObject *ret = NULL;
  918. if (addrobj) {
  919. ret = Py_BuildValue("Oi",
  920. addrobj,
  921. _BT_L2_MEMB(a, psm));
  922. Py_DECREF(addrobj);
  923. }
  924. return ret;
  925. }
  926. case BTPROTO_RFCOMM:
  927. {
  928. struct sockaddr_rc *a = (struct sockaddr_rc *) addr;
  929. PyObject *addrobj = makebdaddr(&_BT_RC_MEMB(a, bdaddr));
  930. PyObject *ret = NULL;
  931. if (addrobj) {
  932. ret = Py_BuildValue("Oi",
  933. addrobj,
  934. _BT_RC_MEMB(a, channel));
  935. Py_DECREF(addrobj);
  936. }
  937. return ret;
  938. }
  939. case BTPROTO_HCI:
  940. {
  941. struct sockaddr_hci *a = (struct sockaddr_hci *) addr;
  942. #if defined(__NetBSD__) || defined(__DragonFly__)
  943. return makebdaddr(&_BT_HCI_MEMB(a, bdaddr));
  944. #else
  945. PyObject *ret = NULL;
  946. ret = Py_BuildValue("i", _BT_HCI_MEMB(a, dev));
  947. return ret;
  948. #endif
  949. }
  950. #if !defined(__FreeBSD__)
  951. case BTPROTO_SCO:
  952. {
  953. struct sockaddr_sco *a = (struct sockaddr_sco *) addr;
  954. return makebdaddr(&_BT_SCO_MEMB(a, bdaddr));
  955. }
  956. #endif
  957. default:
  958. PyErr_SetString(PyExc_ValueError,
  959. "Unknown Bluetooth protocol");
  960. return NULL;
  961. }
  962. #endif
  963. #if defined(HAVE_NETPACKET_PACKET_H) && defined(SIOCGIFNAME)
  964. case AF_PACKET:
  965. {
  966. struct sockaddr_ll *a = (struct sockaddr_ll *)addr;
  967. char *ifname = "";
  968. struct ifreq ifr;
  969. /* need to look up interface name give index */
  970. if (a->sll_ifindex) {
  971. ifr.ifr_ifindex = a->sll_ifindex;
  972. if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0)
  973. ifname = ifr.ifr_name;
  974. }
  975. return Py_BuildValue("shbhs#",
  976. ifname,
  977. ntohs(a->sll_protocol),
  978. a->sll_pkttype,
  979. a->sll_hatype,
  980. a->sll_addr,
  981. a->sll_halen);
  982. }
  983. #endif
  984. #ifdef HAVE_LINUX_TIPC_H
  985. case AF_TIPC:
  986. {
  987. struct sockaddr_tipc *a = (struct sockaddr_tipc *) addr;
  988. if (a->addrtype == TIPC_ADDR_NAMESEQ) {
  989. return Py_BuildValue("IIIII",
  990. a->addrtype,
  991. a->addr.nameseq.type,
  992. a->addr.nameseq.lower,
  993. a->addr.nameseq.upper,
  994. a->scope);
  995. } else if (a->addrtype == TIPC_ADDR_NAME) {
  996. return Py_BuildValue("IIIII",
  997. a->addrtype,
  998. a->addr.name.name.type,
  999. a->addr.name.name.instance,
  1000. a->addr.name.name.instance,
  1001. a->scope);
  1002. } else if (a->addrtype == TIPC_ADDR_ID) {
  1003. return Py_BuildValue("IIIII",
  1004. a->addrtype,
  1005. a->addr.id.node,
  1006. a->addr.id.ref,
  1007. 0,
  1008. a->scope);
  1009. } else {
  1010. PyErr_SetString(PyExc_ValueError,
  1011. "Invalid address type");
  1012. return NULL;
  1013. }
  1014. }
  1015. #endif
  1016. /* More cases here... */
  1017. default:
  1018. /* If we don't know the address family, don't raise an
  1019. exception -- return it as a tuple. */
  1020. return Py_BuildValue("is#",
  1021. addr->sa_family,
  1022. addr->sa_data,
  1023. sizeof(addr->sa_data));
  1024. }
  1025. }
  1026. /* Parse a socket address argument according to the socket object's
  1027. address family. Return 1 if the address was in the proper format,
  1028. 0 of not. The address is returned through addr_ret, its length
  1029. through len_ret. */
  1030. static int
  1031. getsockaddrarg(PySocketSockObject *s, PyObject *args,
  1032. struct sockaddr *addr_ret, int *len_ret)
  1033. {
  1034. switch (s->sock_family) {
  1035. #if defined(AF_UNIX)
  1036. case AF_UNIX:
  1037. {
  1038. struct sockaddr_un* addr;
  1039. char *path;
  1040. int len;
  1041. if (!PyArg_Parse(args, "t#", &path, &len))
  1042. return 0;
  1043. addr = (struct sockaddr_un*)addr_ret;
  1044. #ifdef linux
  1045. if (len > 0 && path[0] == 0) {
  1046. /* Linux abstract namespace extension */
  1047. if (len > sizeof addr->sun_path) {
  1048. PyErr_SetString(socket_error,
  1049. "AF_UNIX path too long");
  1050. return 0;
  1051. }
  1052. }
  1053. else
  1054. #endif /* linux */
  1055. {
  1056. /* regular NULL-terminated string */
  1057. if (len >= sizeof addr->sun_path) {
  1058. PyErr_SetString(socket_error,
  1059. "AF_UNIX path too long");
  1060. return 0;
  1061. }
  1062. addr->sun_path[len] = 0;
  1063. }
  1064. addr->sun_family = s->sock_family;
  1065. memcpy(addr->sun_path, path, len);
  1066. #if defined(PYOS_OS2)
  1067. *len_ret = sizeof(*addr);
  1068. #else
  1069. *len_ret = len + offsetof(struct sockaddr_un, sun_path);
  1070. #endif
  1071. return 1;
  1072. }
  1073. #endif /* AF_UNIX */
  1074. #if defined(AF_NETLINK)
  1075. case AF_NETLINK:
  1076. {
  1077. struct sockaddr_nl* addr;
  1078. int pid, groups;
  1079. addr = (struct sockaddr_nl *)addr_ret;
  1080. if (!PyTuple_Check(args)) {
  1081. PyErr_Format(
  1082. PyExc_TypeError,
  1083. "getsockaddrarg: "
  1084. "AF_NETLINK address must be tuple, not %.500s",
  1085. Py_TYPE(args)->tp_name);
  1086. return 0;
  1087. }
  1088. if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &pid, &groups))
  1089. return 0;
  1090. addr->nl_family = AF_NETLINK;
  1091. addr->nl_pid = pid;
  1092. addr->nl_groups = groups;
  1093. *len_ret = sizeof(*addr);
  1094. return 1;
  1095. }
  1096. #endif
  1097. case AF_INET:
  1098. {
  1099. struct sockaddr_in* addr;
  1100. char *host;
  1101. int port, result;
  1102. if (!PyTuple_Check(args)) {
  1103. PyErr_Format(
  1104. PyExc_TypeError,
  1105. "getsockaddrarg: "
  1106. "AF_INET address must be tuple, not %.500s",
  1107. Py_TYPE(args)->tp_name);
  1108. return 0;
  1109. }
  1110. if (!PyArg_ParseTuple(args, "eti:getsockaddrarg",
  1111. "idna", &host, &port))
  1112. return 0;
  1113. addr=(struct sockaddr_in*)addr_ret;
  1114. result = setipaddr(host, (struct sockaddr *)addr,
  1115. sizeof(*addr), AF_INET);
  1116. PyMem_Free(host);
  1117. if (result < 0)
  1118. return 0;
  1119. if (port < 0 || port > 0xffff) {
  1120. PyErr_SetString(
  1121. PyExc_OverflowError,
  1122. "getsockaddrarg: port must be 0-65535.");
  1123. return 0;
  1124. }
  1125. addr->sin_family = AF_INET;
  1126. addr->sin_port = htons((short)port);
  1127. *len_ret = sizeof *addr;
  1128. return 1;
  1129. }
  1130. #ifdef ENABLE_IPV6
  1131. case AF_INET6:
  1132. {
  1133. struct sockaddr_in6* addr;
  1134. char *host;
  1135. int port, result;
  1136. unsigned int flowinfo, scope_id;
  1137. flowinfo = scope_id = 0;
  1138. if (!PyTuple_Check(args)) {
  1139. PyErr_Format(
  1140. PyExc_TypeError,
  1141. "getsockaddrarg: "
  1142. "AF_INET6 address must be tuple, not %.500s",
  1143. Py_TYPE(args)->tp_name);
  1144. return 0;
  1145. }
  1146. if (!PyArg_ParseTuple(args, "eti|II",
  1147. "idna", &host, &port, &flowinfo,
  1148. &scope_id)) {
  1149. return 0;
  1150. }
  1151. addr = (struct sockaddr_in6*)addr_ret;
  1152. result = setipaddr(host, (struct sockaddr *)addr,
  1153. sizeof(*addr), AF_INET6);
  1154. PyMem_Free(host);
  1155. if (result < 0)
  1156. return 0;
  1157. if (port < 0 || port > 0xffff) {
  1158. PyErr_SetString(
  1159. PyExc_OverflowError,
  1160. "getsockaddrarg: port must be 0-65535.");
  1161. return 0;
  1162. }
  1163. if (flowinfo > 0xfffff) {
  1164. PyErr_SetString(
  1165. PyExc_OverflowError,
  1166. "getsockaddrarg: flowinfo must be 0-1048575.");
  1167. return 0;
  1168. }
  1169. addr->sin6_family = s->sock_family;
  1170. addr->sin6_port = htons((short)port);
  1171. addr->sin6_flowinfo = htonl(flowinfo);
  1172. addr->sin6_scope_id = scope_id;
  1173. *len_ret = sizeof *addr;
  1174. return 1;
  1175. }
  1176. #endif
  1177. #ifdef USE_BLUETOOTH
  1178. case AF_BLUETOOTH:
  1179. {
  1180. switch (s->sock_proto) {
  1181. case BTPROTO_L2CAP:
  1182. {
  1183. struct sockaddr_l2 *addr;
  1184. char *straddr;
  1185. addr = (struct sockaddr_l2 *)addr_ret;
  1186. memset(addr, 0, sizeof(struct sockaddr_l2));
  1187. _BT_L2_MEMB(addr, family) = AF_BLUETOOTH;
  1188. if (!PyArg_ParseTuple(args, "si", &straddr,
  1189. &_BT_L2_MEMB(addr, psm))) {
  1190. PyErr_SetString(socket_error, "getsockaddrarg: "
  1191. "wrong format");
  1192. return 0;
  1193. }
  1194. if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0)
  1195. return 0;
  1196. *len_ret = sizeof *addr;
  1197. return 1;
  1198. }
  1199. case BTPROTO_RFCOMM:
  1200. {
  1201. struct sockaddr_rc *addr;
  1202. char *straddr;
  1203. addr = (struct sockaddr_rc *)addr_ret;
  1204. _BT_RC_MEMB(addr, family) = AF_BLUETOOTH;
  1205. if (!PyArg_ParseTuple(args, "si", &straddr,
  1206. &_BT_RC_MEMB(addr, channel))) {
  1207. PyErr_SetString(socket_error, "getsockaddrarg: "
  1208. "wrong format");
  1209. return 0;
  1210. }
  1211. if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0)
  1212. return 0;
  1213. *len_ret = sizeof *addr;
  1214. return 1;
  1215. }
  1216. case BTPROTO_HCI:
  1217. {
  1218. struct sockaddr_hci *addr = (struct sockaddr_hci *)addr_ret;
  1219. #if defined(__NetBSD__) || defined(__DragonFly__)
  1220. char *straddr = PyBytes_AS_STRING(args);
  1221. _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH;
  1222. if (straddr == NULL) {
  1223. PyErr_SetString(socket_error, "getsockaddrarg: "
  1224. "wrong format");
  1225. return 0;
  1226. }
  1227. if (setbdaddr(straddr, &_BT_HCI_MEMB(addr, bdaddr)) < 0)
  1228. return 0;
  1229. #else
  1230. _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH;
  1231. if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) {
  1232. PyErr_SetString(socket_error, "getsockaddrarg: "
  1233. "wrong format");
  1234. return 0;
  1235. }
  1236. #endif
  1237. *len_ret = sizeof *addr;
  1238. return 1;
  1239. }
  1240. #if !defined(__FreeBSD__)
  1241. case BTPROTO_SCO:
  1242. {
  1243. struct sockaddr_sco *addr;
  1244. char *straddr;
  1245. addr = (struct sockaddr_sco *)addr_ret;
  1246. _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH;
  1247. straddr = PyString_AsString(args);
  1248. if (straddr == NULL) {
  1249. PyErr_SetString(socket_error, "getsockaddrarg: "
  1250. "wrong format");
  1251. return 0;
  1252. }
  1253. if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0)
  1254. return 0;
  1255. *len_ret = sizeof *addr;
  1256. return 1;
  1257. }
  1258. #endif
  1259. default:
  1260. PyErr_SetString(socket_error, "getsockaddrarg: unknown Bluetooth protocol");
  1261. return 0;
  1262. }
  1263. }
  1264. #endif
  1265. #if defined(HAVE_NETPACKET_PACKET_H) && defined(SIOCGIFINDEX)
  1266. case AF_PACKET:
  1267. {
  1268. struct sockaddr_ll* addr;
  1269. struct ifreq ifr;
  1270. char *interfaceName;
  1271. int protoNumber;
  1272. int hatype = 0;
  1273. int pkttype = 0;
  1274. char *haddr = NULL;
  1275. unsigned int halen = 0;
  1276. if (!PyTuple_Check(args)) {
  1277. PyErr_Format(
  1278. PyExc_TypeError,
  1279. "getsockaddrarg: "
  1280. "AF_PACKET address must be tuple, not %.500s",
  1281. Py_TYPE(args)->tp_name);
  1282. return 0;
  1283. }
  1284. if (!PyArg_ParseTuple(args, "si|iis#", &interfaceName,
  1285. &protoNumber, &pkttype, &hatype,
  1286. &haddr, &halen))
  1287. return 0;
  1288. strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name));
  1289. ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
  1290. if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
  1291. s->errorhandler();
  1292. return 0;
  1293. }
  1294. if (halen > 8) {
  1295. PyErr_SetString(PyExc_ValueError,
  1296. "Hardware address must be 8 bytes or less");
  1297. return 0;
  1298. }
  1299. if (protoNumber < 0 || protoNumber > 0xffff) {
  1300. PyErr_SetString(
  1301. PyExc_OverflowError,
  1302. "getsockaddrarg: protoNumber must be 0-65535.");
  1303. return 0;
  1304. }
  1305. addr = (struct sockaddr_ll*)addr_ret;
  1306. addr->sll_family = AF_PACKET;
  1307. addr->sll_protocol = htons((short)protoNumber);
  1308. addr->sll_ifindex = ifr.ifr_ifindex;
  1309. addr->sll_pkttype = pkttype;
  1310. addr->sll_hatype = hatype;
  1311. if (halen != 0) {
  1312. memcpy(&addr->sll_addr, haddr, halen);
  1313. }
  1314. addr->sll_halen = halen;
  1315. *len_ret = sizeof *addr;
  1316. return 1;
  1317. }
  1318. #endif
  1319. #ifdef HAVE_LINUX_TIPC_H
  1320. case AF_TIPC:
  1321. {
  1322. unsigned int atype, v1, v2, v3;
  1323. unsigned int scope = TIPC_CLUSTER_SCOPE;
  1324. struct sockaddr_tipc *addr;
  1325. if (!PyTuple_Check(args)) {
  1326. PyErr_Format(
  1327. PyExc_TypeError,
  1328. "getsockaddrarg: "
  1329. "AF_TIPC address must be tuple, not %.500s",
  1330. Py_TYPE(args)->tp_name);
  1331. return 0;
  1332. }
  1333. if (!PyArg_ParseTuple(args,
  1334. "IIII|I;Invalid TIPC address format",
  1335. &atype, &v1, &v2, &v3, &scope))
  1336. return 0;
  1337. addr = (struct sockaddr_tipc *) addr_ret;
  1338. memset(addr, 0, sizeof(struct sockaddr_tipc));
  1339. addr->family = AF_TIPC;
  1340. addr->scope = scope;
  1341. addr->addrtype = atype;
  1342. if (atype == TIPC_ADDR_NAMESEQ) {
  1343. addr->addr.nameseq.type = v1;
  1344. addr->addr.nameseq.lower = v2;
  1345. addr->addr.nameseq.upper = v3;
  1346. } else if (atype == TIPC_ADDR_NAME) {
  1347. addr->addr.name.name.type = v1;
  1348. addr->addr.name.name.instance = v2;
  1349. } else if (atype == TIPC_ADDR_ID) {
  1350. addr->addr.id.node = v1;
  1351. addr->addr.id.ref = v2;
  1352. } else {
  1353. /* Shouldn't happen */
  1354. PyErr_SetString(PyExc_TypeError, "Invalid address type");
  1355. return 0;
  1356. }
  1357. *len_ret = sizeof(*addr);
  1358. return 1;
  1359. }
  1360. #endif
  1361. /* More cases here... */
  1362. default:
  1363. PyErr_SetString(socket_error, "getsockaddrarg: bad family");
  1364. return 0;
  1365. }
  1366. }
  1367. /* Get the address length according to the socket object's address family.
  1368. Return 1 if the family is known, 0 otherwise. The length is returned
  1369. through len_ret. */
  1370. static int
  1371. getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
  1372. {
  1373. switch (s->sock_family) {
  1374. #if defined(AF_UNIX)
  1375. case AF_UNIX:
  1376. {
  1377. *len_ret = sizeof (struct sockaddr_un);
  1378. return 1;
  1379. }
  1380. #endif /* AF_UNIX */
  1381. #if defined(AF_NETLINK)
  1382. case AF_NETLINK:
  1383. {
  1384. *len_ret = sizeof (struct sockaddr_nl);
  1385. return 1;
  1386. }
  1387. #endif
  1388. case AF_INET:
  1389. {
  1390. *len_ret = sizeof (struct sockaddr_in);
  1391. return 1;
  1392. }
  1393. #ifdef ENABLE_IPV6
  1394. case AF_INET6:
  1395. {
  1396. *len_ret = sizeof (struct sockaddr_in6);
  1397. return 1;
  1398. }
  1399. #endif
  1400. #ifdef USE_BLUETOOTH
  1401. case AF_BLUETOOTH:
  1402. {
  1403. switch(s->sock_proto)
  1404. {
  1405. case BTPROTO_L2CAP:
  1406. *len_ret = sizeof (struct sockaddr_l2);
  1407. return 1;
  1408. case BTPROTO_RFCOMM:
  1409. *len_ret = sizeof (struct sockaddr_rc);
  1410. return 1;
  1411. case BTPROTO_HCI:
  1412. *len_ret = sizeof (struct sockaddr_hci);
  1413. return 1;
  1414. #if !defined(__FreeBSD__)
  1415. case BTPROTO_SCO:
  1416. *len_ret = sizeof (struct sockaddr_sco);
  1417. return 1;
  1418. #endif
  1419. default:
  1420. PyErr_SetString(socket_error, "getsockaddrlen: "
  1421. "unknown BT protocol");
  1422. return 0;
  1423. }
  1424. }
  1425. #endif
  1426. #ifdef HAVE_NETPACKET_PACKET_H
  1427. case AF_PACKET:
  1428. {
  1429. *len_ret = sizeof (struct sockaddr_ll);
  1430. return 1;
  1431. }
  1432. #endif
  1433. #ifdef HAVE_LINUX_TIPC_H
  1434. case AF_TIPC:
  1435. {
  1436. *len_ret = sizeof (struct sockaddr_tipc);
  1437. return 1;
  1438. }
  1439. #endif
  1440. /* More cases here... */
  1441. default:
  1442. PyErr_SetString(socket_error, "getsockaddrlen: bad family");
  1443. return 0;
  1444. }
  1445. }
  1446. /* s.accept() method */
  1447. static PyObject *
  1448. sock_accept(PySocketSockObject *s)
  1449. {
  1450. sock_addr_t addrbuf;
  1451. SOCKET_T newfd;
  1452. socklen_t addrlen;
  1453. PyObject *sock = NULL;
  1454. PyObject *addr = NULL;
  1455. PyObject *res = NULL;
  1456. int timeout;
  1457. if (!getsockaddrlen(s, &addrlen))
  1458. return NULL;
  1459. memset(&addrbuf, 0, addrlen);
  1460. #ifdef MS_WINDOWS
  1461. newfd = INVALID_SOCKET;
  1462. #else
  1463. newfd = -1;
  1464. #endif
  1465. if (!IS_SELECTABLE(s))
  1466. return select_error();
  1467. Py_BEGIN_ALLOW_THREADS
  1468. timeout = internal_select(s, 0);
  1469. if (!timeout)
  1470. newfd = accept(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
  1471. Py_END_ALLOW_THREADS
  1472. if (timeout == 1) {
  1473. PyErr_SetString(socket_timeout, "timed out");
  1474. return NULL;
  1475. }
  1476. #ifdef MS_WINDOWS
  1477. if (newfd == INVALID_SOCKET)
  1478. #else
  1479. if (newfd < 0)
  1480. #endif
  1481. return s->errorhandler();
  1482. /* Create the new object with unspecified family,
  1483. to avoid calls to bind() etc. on it. */
  1484. sock = (PyObject *) new_sockobject(newfd,
  1485. s->sock_family,
  1486. s->sock_type,
  1487. s->sock_proto);
  1488. if (sock == NULL) {
  1489. SOCKETCLOSE(newfd);
  1490. goto finally;
  1491. }
  1492. addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
  1493. addrlen, s->sock_proto);
  1494. if (addr == NULL)
  1495. goto finally;
  1496. res = PyTuple_Pack(2, sock, addr);
  1497. finally:
  1498. Py_XDECREF(sock);
  1499. Py_XDECREF(addr);
  1500. return res;
  1501. }
  1502. PyDoc_STRVAR(accept_doc,
  1503. "accept() -> (socket object, address info)\n\
  1504. \n\
  1505. Wait for an incoming connection. Return a new socket representing the\n\
  1506. connection, and the address of the client. For IP sockets, the address\n\
  1507. info is a pair (hostaddr, port).");
  1508. /* s.setblocking(flag) method. Argument:
  1509. False -- non-blocking mode; same as settimeout(0)
  1510. True -- blocking mode; same as settimeout(None)
  1511. */
  1512. static PyObject *
  1513. sock_setblocking(PySocketSockObject *s, PyObject *arg)
  1514. {
  1515. long block;
  1516. block = PyInt_AsLong(arg);
  1517. if (block == -1 && PyErr_Occurred())
  1518. return NULL;
  1519. s->sock_timeout = block ? -1.0 : 0.0;
  1520. internal_setblocking(s, block);
  1521. Py_INCREF(Py_None);
  1522. return Py_None;
  1523. }
  1524. PyDoc_STRVAR(setblocking_doc,
  1525. "setblocking(flag)\n\
  1526. \n\
  1527. Set the socket to blocking (flag is true) or non-blocking (false).\n\
  1528. setblocking(True) is equivalent to settimeout(None);\n\
  1529. setblocking(False) is equivalent to settimeout(0.0).");
  1530. /* s.settimeout(timeout) method. Argument:
  1531. None -- no timeout, blocking mode; same as setblocking(True)
  1532. 0.0 -- non-blocking mode; same as setblocking(False)
  1533. > 0 -- timeout mode; operations time out after timeout seconds
  1534. < 0 -- illegal; raises an exception
  1535. */
  1536. static PyObject *
  1537. sock_settimeout(PySocketSockObject *s, PyObject *arg)
  1538. {
  1539. double timeout;
  1540. if (arg == Py_None)
  1541. timeout = -1.0;
  1542. else {
  1543. timeout = PyFloat_AsDouble(arg);
  1544. if (timeout < 0.0) {
  1545. if (!PyErr_Occurred())
  1546. PyErr_SetString(PyExc_ValueError,
  1547. "Timeout value out of range");
  1548. return NULL;
  1549. }
  1550. }
  1551. s->sock_timeout = timeout;
  1552. internal_setblocking(s, timeout < 0.0);
  1553. Py_INCREF(Py_None);
  1554. return Py_None;
  1555. }
  1556. PyDoc_STRVAR(settimeout_doc,
  1557. "settimeout(timeout)\n\
  1558. \n\
  1559. Set a timeout on socket operations. 'timeout' can be a float,\n\
  1560. giving in seconds, or None. Setting a timeout of None disables\n\
  1561. the timeout feature and is equivalent to setblocking(1).\n\
  1562. Setting a timeout of zero is the same as setblocking(0).");
  1563. /* s.gettimeout() method.
  1564. Returns the timeout associated with a socket. */
  1565. static PyObject *
  1566. sock_gettimeout(PySocketSockObject *s)
  1567. {
  1568. if (s->sock_timeout < 0.0) {
  1569. Py_INCREF(Py_None);
  1570. return Py_None;
  1571. }
  1572. else
  1573. return PyFloat_FromDouble(s->sock_timeout);
  1574. }
  1575. PyDoc_STRVAR(gettimeout_doc,
  1576. "gettimeout() -> timeout\n\
  1577. \n\
  1578. Returns the timeout in seconds (float) associated with socket \n\
  1579. operations. A timeout of None indicates that timeouts on socket \n\
  1580. operations are disabled.");
  1581. #ifdef RISCOS
  1582. /* s.sleeptaskw(1 | 0) method */
  1583. static PyObject *
  1584. sock_sleeptaskw(PySocketSockObject *s,PyObject *arg)
  1585. {
  1586. int block;
  1587. block = PyInt_AsLong(arg);
  1588. if (block == -1 && PyErr_Occurred())
  1589. return NULL;
  1590. Py_BEGIN_ALLOW_THREADS
  1591. socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
  1592. Py_END_ALLOW_THREADS
  1593. Py_INCREF(Py_None);
  1594. return Py_None;
  1595. }
  1596. PyDoc_STRVAR(sleeptaskw_doc,
  1597. "sleeptaskw(flag)\n\
  1598. \n\
  1599. Allow sleeps in taskwindows.");
  1600. #endif
  1601. /* s.setsockopt() method.
  1602. With an integer third argument, sets an integer option.
  1603. With a string third argument, sets an option from a buffer;
  1604. use optional built-in module 'struct' to encode the string. */
  1605. static PyObject *
  1606. sock_setsockopt(PySocketSockObject *s, PyObject *args)
  1607. {
  1608. int level;
  1609. int optname;
  1610. int res;
  1611. char *buf;
  1612. int buflen;
  1613. int flag;
  1614. if (PyArg_ParseTuple(args, "iii:setsockopt",
  1615. &level, &optname, &flag)) {
  1616. buf = (char *) &flag;
  1617. buflen = sizeof flag;
  1618. }
  1619. else {
  1620. PyErr_Clear();
  1621. if (!PyArg_ParseTuple(args, "iis#:setsockopt",
  1622. &level, &optname, &buf, &buflen))
  1623. return NULL;
  1624. }
  1625. res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen);
  1626. if (res < 0)
  1627. return s->errorhandler();
  1628. Py_INCREF(Py_None);
  1629. return Py_None;
  1630. }
  1631. PyDoc_STRVAR(setsockopt_doc,
  1632. "setsockopt(level, option, value)\n\
  1633. \n\
  1634. Set a socket option. See the Unix manual for level and option.\n\
  1635. The value argument can either be an integer or a string.");
  1636. /* s.getsockopt() method.
  1637. With two arguments, retrieves an integer option.
  1638. With a third integer argument, retrieves a string buffer of that size;
  1639. use optional built-in module 'struct' to decode the string. */
  1640. static PyObject *
  1641. sock_getsockopt(PySocketSockObject *s, PyObject *args)
  1642. {
  1643. int level;
  1644. int optname;
  1645. int res;
  1646. PyObject *buf;
  1647. socklen_t buflen = 0;
  1648. #ifdef __BEOS__
  1649. /* We have incomplete socket support. */
  1650. PyErr_SetString(socket_error, "getsockopt not supported");
  1651. return NULL;
  1652. #else
  1653. if (!PyArg_ParseTuple(args, "ii|i:getsockopt",
  1654. &level, &optname, &buflen))
  1655. return NULL;
  1656. if (buflen == 0) {
  1657. int flag = 0;
  1658. socklen_t flagsize = sizeof flag;
  1659. res = getsockopt(s->sock_fd, level, optname,
  1660. (void *)&flag, &flagsize);
  1661. if (res < 0)
  1662. return s->errorhandler();
  1663. return PyInt_FromLong(flag);
  1664. }
  1665. #ifdef __VMS
  1666. /* socklen_t is unsigned so no negative test is needed,
  1667. test buflen == 0 is previously done */
  1668. if (buflen > 1024) {
  1669. #else
  1670. if (buflen <= 0 || buflen > 1024) {
  1671. #endif
  1672. PyErr_SetString(socket_error,
  1673. "getsockopt buflen out of range");
  1674. return NULL;
  1675. }
  1676. buf = PyString_FromStringAndSize((char *)NULL, buflen);
  1677. if (buf == NULL)
  1678. return NULL;
  1679. res = getsockopt(s->sock_fd, level, optname,
  1680. (void *)PyString_AS_STRING(buf), &buflen);
  1681. if (res < 0) {
  1682. Py_DECREF(buf);
  1683. return s->errorhandler();
  1684. }
  1685. _PyString_Resize(&buf, buflen);
  1686. return buf;
  1687. #endif /* __BEOS__ */
  1688. }
  1689. PyDoc_STRVAR(getsockopt_doc,
  1690. "getsockopt(level, option[, buffersize]) -> value\n\
  1691. \n\
  1692. Get a socket option. See the Unix manual for level and option.\n\
  1693. If a nonzero buffersize argument is given, the return value is a\n\
  1694. string of that length; otherwise it is an integer.");
  1695. /* s.bind(sockaddr) method */
  1696. static PyObject *
  1697. sock_bind(PySocketSockObject *s, PyObject *addro)
  1698. {
  1699. sock_addr_t addrbuf;
  1700. int addrlen;
  1701. int res;
  1702. if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
  1703. return NULL;
  1704. Py_BEGIN_ALLOW_THREADS
  1705. res = bind(s->sock_fd, SAS2SA(&addrbuf), addrlen);
  1706. Py_END_ALLOW_THREADS
  1707. if (res < 0)
  1708. return s->errorhandler();
  1709. Py_INCREF(Py_None);
  1710. return Py_None;
  1711. }
  1712. PyDoc_STRVAR(bind_doc,
  1713. "bind(address)\n\
  1714. \n\
  1715. Bind the socket to a local address. For IP sockets, the address is a\n\
  1716. pair (host, port); the host must refer to the local host. For raw packet\n\
  1717. sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");
  1718. /* s.close() method.
  1719. Set the file descriptor to -1 so operations tried subsequently
  1720. will surely fail. */
  1721. static PyObject *
  1722. sock_close(PySocketSockObject *s)
  1723. {
  1724. SOCKET_T fd;
  1725. if ((fd = s->sock_fd) != -1) {
  1726. s->sock_fd = -1;
  1727. Py_BEGIN_ALLOW_THREADS
  1728. (void) SOCKETCLOSE(fd);
  1729. Py_END_ALLOW_THREADS
  1730. }
  1731. Py_INCREF(Py_None);
  1732. return Py_None;
  1733. }
  1734. PyDoc_STRVAR(close_doc,
  1735. "close()\n\
  1736. \n\
  1737. Close the socket. It cannot be used after this call.");
  1738. static int
  1739. internal_connect(PySocketSockObject *s, struct sockaddr *addr, int addrlen,
  1740. int *timeoutp)
  1741. {
  1742. int res, timeout;
  1743. timeout = 0;
  1744. res = connect(s->sock_fd, addr, addrlen);
  1745. #ifdef MS_WINDOWS
  1746. if (s->sock_timeout > 0.0) {
  1747. if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK &&
  1748. IS_SELECTABLE(s)) {
  1749. /* This is a mess. Best solution: trust select */
  1750. fd_set fds;
  1751. fd_set fds_exc;
  1752. struct timeval tv;
  1753. tv.tv_sec = (int)s->sock_timeout;
  1754. tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
  1755. FD_ZERO(&fds);
  1756. FD_SET(s->sock_fd, &fds);
  1757. FD_ZERO(&fds_exc);
  1758. FD_SET(s->sock_fd, &fds_exc);
  1759. res = select(s->sock_fd+1, NULL, &fds, &fds_exc, &tv);
  1760. if (res == 0) {
  1761. res = WSAEWOULDBLOCK;
  1762. timeout = 1;
  1763. } else if (res > 0) {
  1764. if (FD_ISSET(s->sock_fd, &fds))
  1765. /* The socket is in the writeable set - this
  1766. means connected */
  1767. res = 0;
  1768. else {
  1769. /* As per MS docs, we need to call getsockopt()
  1770. to get the underlying error */
  1771. int res_size = sizeof res;
  1772. /* It must be in the exception set */
  1773. assert(FD_ISSET(s->sock_fd, &fds_exc));
  1774. if (0 == getsockopt(s->sock_fd, SOL_SOCKET, SO_ERROR,
  1775. (char *)&res, &res_size))
  1776. /* getsockopt also clears WSAGetLastError,
  1777. so reset it back. */
  1778. WSASetLastError(res);
  1779. else
  1780. res = WSAGetLastError();
  1781. }
  1782. }
  1783. /* else if (res < 0) an error occurred */
  1784. }
  1785. }
  1786. if (res < 0)
  1787. res = WSAGetLastError();
  1788. #else
  1789. if (s->sock_timeout > 0.0) {
  1790. if (res < 0 && errno == EINPROGRESS && IS_SELECTABLE(s)) {
  1791. timeout = internal_select(s, 1);
  1792. if (timeout == 0) {
  1793. /* Bug #1019808: in case of an EINPROGRESS,
  1794. use getsockopt(SO_ERROR) to get the real
  1795. error. */
  1796. socklen_t res_size = sizeof res;
  1797. (void)getsockopt(s->sock_fd, SOL_SOCKET,
  1798. SO_ERROR, &res, &res_size);
  1799. if (res == EISCONN)
  1800. res = 0;
  1801. errno = res;
  1802. }
  1803. else if (timeout == -1) {
  1804. res = errno; /* had error */
  1805. }
  1806. else
  1807. res = EWOULDBLOCK; /* timed out */
  1808. }
  1809. }
  1810. if (res < 0)
  1811. res = errno;
  1812. #endif
  1813. *timeoutp = timeout;
  1814. return res;
  1815. }
  1816. /* s.connect(sockaddr) method */
  1817. static PyObject *
  1818. sock_connect(PySocketSockObject *s, PyObject *addro)
  1819. {
  1820. sock_addr_t addrbuf;
  1821. int addrlen;
  1822. int res;
  1823. int timeout;
  1824. if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
  1825. return NULL;
  1826. Py_BEGIN_ALLOW_THREADS
  1827. res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
  1828. Py_END_ALLOW_THREADS
  1829. if (timeout == 1) {
  1830. PyErr_SetString(socket_timeout, "timed out");
  1831. return NULL;
  1832. }
  1833. if (res != 0)
  1834. return s->errorhandler();
  1835. Py_INCREF(Py_None);
  1836. return Py_None;
  1837. }
  1838. PyDoc_STRVAR(connect_doc,
  1839. "connect(address)\n\
  1840. \n\
  1841. Connect the socket to a remote address. For IP sockets, the address\n\
  1842. is a pair (host, port).");
  1843. /* s.connect_ex(sockaddr) method */
  1844. static PyObject *
  1845. sock_connect_ex(PySocketSockObject *s, PyObject *addro)
  1846. {
  1847. sock_addr_t addrbuf;
  1848. int addrlen;
  1849. int res;
  1850. int timeout;
  1851. if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
  1852. return NULL;
  1853. Py_BEGIN_ALLOW_THREADS
  1854. res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
  1855. Py_END_ALLOW_THREADS
  1856. /* Signals are not errors (though they may raise exceptions). Adapted
  1857. from PyErr_SetFromErrnoWithFilenameObject(). */
  1858. #ifdef EINTR
  1859. if (res == EINTR && PyErr_CheckSignals())
  1860. return NULL;
  1861. #endif
  1862. return PyInt_FromLong((long) res);
  1863. }
  1864. PyDoc_STRVAR(connect_ex_doc,
  1865. "connect_ex(address) -> errno\n\
  1866. \n\
  1867. This is like connect(address), but returns an error code (the errno value)\n\
  1868. instead of raising an exception when an error occurs.");
  1869. /* s.fileno() method */
  1870. static PyObject *
  1871. sock_fileno(PySocketSockObject *s)
  1872. {
  1873. #if SIZEOF_SOCKET_T <= SIZEOF_LONG
  1874. return PyInt_FromLong((long) s->sock_fd);
  1875. #else
  1876. return PyLong_FromLongLong((PY_LONG_LONG)s->sock_fd);
  1877. #endif
  1878. }
  1879. PyDoc_STRVAR(fileno_doc,
  1880. "fileno() -> integer\n\
  1881. \n\
  1882. Return the integer file descriptor of the socket.");
  1883. #ifndef NO_DUP
  1884. /* s.dup() method */
  1885. static PyObject *
  1886. sock_dup(PySocketSockObject *s)
  1887. {
  1888. SOCKET_T newfd;
  1889. PyObject *sock;
  1890. newfd = dup(s->sock_fd);
  1891. if (newfd < 0)
  1892. return s->errorhandler();
  1893. sock = (PyObject *) new_sockobject(newfd,
  1894. s->sock_family,
  1895. s->sock_type,
  1896. s->sock_proto);
  1897. if (sock == NULL)
  1898. SOCKETCLOSE(newfd);
  1899. return sock;
  1900. }
  1901. PyDoc_STRVAR(dup_doc,
  1902. "dup() -> socket object\n\
  1903. \n\
  1904. Return a new socket object connected to the same system resource.");
  1905. #endif
  1906. /* s.getsockname() method */
  1907. static PyObject *
  1908. sock_getsockname(PySocketSockObject *s)
  1909. {
  1910. sock_addr_t addrbuf;
  1911. int res;
  1912. socklen_t addrlen;
  1913. if (!getsockaddrlen(s, &addrlen))
  1914. return NULL;
  1915. memset(&addrbuf, 0, addrlen);
  1916. Py_BEGIN_ALLOW_THREADS
  1917. res = getsockname(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
  1918. Py_END_ALLOW_THREADS
  1919. if (res < 0)
  1920. return s->errorhandler();
  1921. return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
  1922. s->sock_proto);
  1923. }
  1924. PyDoc_STRVAR(getsockname_doc,
  1925. "getsockname() -> address info\n\
  1926. \n\
  1927. Return the address of the local endpoint. For IP sockets, the address\n\
  1928. info is a pair (hostaddr, port).");
  1929. #ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
  1930. /* s.getpeername() method */
  1931. static PyObject *
  1932. sock_getpeername(PySocketSockObject *s)
  1933. {
  1934. sock_addr_t addrbuf;
  1935. int res;
  1936. socklen_t addrlen;
  1937. if (!getsockaddrlen(s, &addrlen))
  1938. return NULL;
  1939. memset(&addrbuf, 0, addrlen);
  1940. Py_BEGIN_ALLOW_THREADS
  1941. res = getpeername(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
  1942. Py_END_ALLOW_THREADS
  1943. if (res < 0)
  1944. return s->errorhandler();
  1945. return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
  1946. s->sock_proto);
  1947. }
  1948. PyDoc_STRVAR(getpeername_doc,
  1949. "getpeername() -> address info\n\
  1950. \n\
  1951. Return the address of the remote endpoint. For IP sockets, the address\n\
  1952. info is a pair (hostaddr, port).");
  1953. #endif /* HAVE_GETPEERNAME */
  1954. /* s.listen(n) method */
  1955. static PyObject *
  1956. sock_listen(PySocketSockObject *s, PyObject *arg)
  1957. {
  1958. int backlog;
  1959. int res;
  1960. backlog = _PyInt_AsInt(arg);
  1961. if (backlog == -1 && PyErr_Occurred())
  1962. return NULL;
  1963. Py_BEGIN_ALLOW_THREADS
  1964. /* To avoid problems on systems that don't allow a negative backlog
  1965. * (which doesn't make sense anyway) we force a minimum value of 0. */
  1966. if (backlog < 0)
  1967. backlog = 0;
  1968. res = listen(s->sock_fd, backlog);
  1969. Py_END_ALLOW_THREADS
  1970. if (res < 0)
  1971. return s->errorhandler();
  1972. Py_INCREF(Py_None);
  1973. return Py_None;
  1974. }
  1975. PyDoc_STRVAR(listen_doc,
  1976. "listen(backlog)\n\
  1977. \n\
  1978. Enable a server to accept connections. The backlog argument must be at\n\
  1979. least 0 (if it is lower, it is set to 0); it specifies the number of\n\
  1980. unaccepted connections that the system will allow before refusing new\n\
  1981. connections.");
  1982. #ifndef NO_DUP
  1983. /* s.makefile(mode) method.
  1984. Create a new open file object referring to a dupped version of
  1985. the socket's file descriptor. (The dup() call is necessary so
  1986. that the open file and socket objects may be closed independent
  1987. of each other.)
  1988. The mode argument specifies 'r' or 'w' passed to fdopen(). */
  1989. static PyObject *
  1990. sock_makefile(PySocketSockObject *s, PyObject *args)
  1991. {
  1992. extern int fclose(FILE *);
  1993. char *mode = "r";
  1994. int bufsize = -1;
  1995. #ifdef MS_WIN32
  1996. Py_intptr_t fd;
  1997. #else
  1998. int fd;
  1999. #endif
  2000. FILE *fp;
  2001. PyObject *f;
  2002. #ifdef __VMS
  2003. char *mode_r = "r";
  2004. char *mode_w = "w";
  2005. #endif
  2006. if (!PyArg_ParseTuple(args, "|si:makefile", &mode, &bufsize))
  2007. return NULL;
  2008. #ifdef __VMS
  2009. if (strcmp(mode,"rb") == 0) {
  2010. mode = mode_r;
  2011. }
  2012. else {
  2013. if (strcmp(mode,"wb") == 0) {
  2014. mode = mode_w;
  2015. }
  2016. }
  2017. #endif
  2018. #ifdef MS_WIN32
  2019. if (((fd = _open_osfhandle(s->sock_fd, _O_BINARY)) < 0) ||
  2020. ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL))
  2021. #else
  2022. if ((fd = dup(s->sock_fd)) < 0 || (fp = fdopen(fd, mode)) == NULL)
  2023. #endif
  2024. {
  2025. if (fd >= 0)
  2026. SOCKETCLOSE(fd);
  2027. return s->errorhandler();
  2028. }
  2029. f = PyFile_FromFile(fp, "<socket>", mode, fclose);
  2030. if (f != NULL)
  2031. PyFile_SetBufSize(f, bufsize);
  2032. return f;
  2033. }
  2034. PyDoc_STRVAR(makefile_doc,
  2035. "makefile([mode[, buffersize]]) -> file object\n\
  2036. \n\
  2037. Return a regular file object corresponding to the socket.\n\
  2038. The mode and buffersize arguments are as for the built-in open() function.");
  2039. #endif /* NO_DUP */
  2040. /*
  2041. * This is the guts of the recv() and recv_into() methods, which reads into a
  2042. * char buffer. If you have any inc/dec ref to do to the objects that contain
  2043. * the buffer, do it in the caller. This function returns the number of bytes
  2044. * successfully read. If there was an error, it returns -1. Note that it is
  2045. * also possible that we return a number of bytes smaller than the request
  2046. * bytes.
  2047. */
  2048. static ssize_t
  2049. sock_recv_guts(PySocketSockObject *s, char* cbuf, int len, int flags)
  2050. {
  2051. ssize_t outlen = -1;
  2052. int timeout;
  2053. #ifdef __VMS
  2054. int remaining;
  2055. char *read_buf;
  2056. #endif
  2057. if (!IS_SELECTABLE(s)) {
  2058. select_error();
  2059. return -1;
  2060. }
  2061. #ifndef __VMS
  2062. Py_BEGIN_ALLOW_THREADS
  2063. timeout = internal_select(s, 0);
  2064. if (!timeout)
  2065. outlen = recv(s->sock_fd, cbuf, len, flags);
  2066. Py_END_ALLOW_THREADS
  2067. if (timeout == 1) {
  2068. PyErr_SetString(socket_timeout, "timed out");
  2069. return -1;
  2070. }
  2071. if (outlen < 0) {
  2072. /* Note: the call to errorhandler() ALWAYS indirectly returned
  2073. NULL, so ignore its return value */
  2074. s->errorhandler();
  2075. return -1;
  2076. }
  2077. #else
  2078. read_buf = cbuf;
  2079. remaining = len;
  2080. while (remaining != 0) {
  2081. unsigned int segment;
  2082. int nread = -1;
  2083. segment = remaining /SEGMENT_SIZE;
  2084. if (segment != 0) {
  2085. segment = SEGMENT_SIZE;
  2086. }
  2087. else {
  2088. segment = remaining;
  2089. }
  2090. Py_BEGIN_ALLOW_THREADS
  2091. timeout = internal_select(s, 0);
  2092. if (!timeout)
  2093. nread = recv(s->sock_fd, read_buf, segment, flags);
  2094. Py_END_ALLOW_THREADS
  2095. if (timeout == 1) {
  2096. PyErr_SetString(socket_timeout, "timed out");
  2097. return -1;
  2098. }
  2099. if (nread < 0) {
  2100. s->errorhandler();
  2101. return -1;
  2102. }
  2103. if (nread != remaining) {
  2104. read_buf += nread;
  2105. break;
  2106. }
  2107. remaining -= segment;
  2108. read_buf += segment;
  2109. }
  2110. outlen = read_buf - cbuf;
  2111. #endif /* !__VMS */
  2112. return outlen;
  2113. }
  2114. /* s.recv(nbytes [,flags]) method */
  2115. static PyObject *
  2116. sock_recv(PySocketSockObject *s, PyObject *args)
  2117. {
  2118. int recvlen, flags = 0;
  2119. ssize_t outlen;
  2120. PyObject *buf;
  2121. if (!PyArg_ParseTuple(args, "i|i:recv", &recvlen, &flags))
  2122. return NULL;
  2123. if (recvlen < 0) {
  2124. PyErr_SetString(PyExc_ValueError,
  2125. "negative buffersize in recv");
  2126. return NULL;
  2127. }
  2128. /* Allocate a new string. */
  2129. buf = PyString_FromStringAndSize((char *) 0, recvlen);
  2130. if (buf == NULL)
  2131. return NULL;
  2132. /* Call the guts */
  2133. outlen = sock_recv_guts(s, PyString_AS_STRING(buf), recvlen, flags);
  2134. if (outlen < 0) {
  2135. /* An error occurred, release the string and return an
  2136. error. */
  2137. Py_DECREF(buf);
  2138. return NULL;
  2139. }
  2140. if (outlen != recvlen) {
  2141. /* We did not read as many bytes as we anticipated, resize the
  2142. string if possible and be successful. */
  2143. if (_PyString_Resize(&buf, outlen) < 0)
  2144. /* Oopsy, not so successful after all. */
  2145. return NULL;
  2146. }
  2147. return buf;
  2148. }
  2149. PyDoc_STRVAR(recv_doc,
  2150. "recv(buffersize[, flags]) -> data\n\
  2151. \n\
  2152. Receive up to buffersize bytes from the socket. For the optional flags\n\
  2153. argument, see the Unix manual. When no data is available, block until\n\
  2154. at least one byte is available or until the remote end is closed. When\n\
  2155. the remote end is closed and all data is read, return the empty string.");
  2156. /* s.recv_into(buffer, [nbytes [,flags]]) method */
  2157. static PyObject*
  2158. sock_recv_into(PySocketSockObject *s, PyObject *args, PyObject *kwds)
  2159. {
  2160. static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
  2161. int recvlen = 0, flags = 0;
  2162. ssize_t readlen;
  2163. Py_buffer buf;
  2164. Py_ssize_t buflen;
  2165. /* Get the buffer's memory */
  2166. if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recv_into", kwlist,
  2167. &buf, &recvlen, &flags))
  2168. return NULL;
  2169. buflen = buf.len;
  2170. assert(buf.buf != 0 && buflen > 0);
  2171. if (recvlen < 0) {
  2172. PyErr_SetString(PyExc_ValueError,
  2173. "negative buffersize in recv_into");
  2174. goto error;
  2175. }
  2176. if (recvlen == 0) {
  2177. /* If nbytes was not specified, use the buffer's length */
  2178. recvlen = buflen;
  2179. }
  2180. /* Check if the buffer is large enough */
  2181. if (buflen < recvlen) {
  2182. PyErr_SetString(PyExc_ValueError,
  2183. "buffer too small for requested bytes");
  2184. goto error;
  2185. }
  2186. /* Call the guts */
  2187. readlen = sock_recv_guts(s, buf.buf, recvlen, flags);
  2188. if (readlen < 0) {
  2189. /* Return an error. */
  2190. goto error;
  2191. }
  2192. PyBuffer_Release(&buf);
  2193. /* Return the number of bytes read. Note that we do not do anything
  2194. special here in the case that readlen < recvlen. */
  2195. return PyInt_FromSsize_t(readlen);
  2196. error:
  2197. PyBuffer_Release(&buf);
  2198. return NULL;
  2199. }
  2200. PyDoc_STRVAR(recv_into_doc,
  2201. "recv_into(buffer, [nbytes[, flags]]) -> nbytes_read\n\
  2202. \n\
  2203. A version of recv() that stores its data into a buffer rather than creating \n\
  2204. a new string. Receive up to buffersize bytes from the socket. If buffersize \n\
  2205. is not specified (or 0), receive up to the size available in the given buffer.\n\
  2206. \n\
  2207. See recv() for documentation about the flags.");
  2208. /*
  2209. * This is the guts of the recvfrom() and recvfrom_into() methods, which reads
  2210. * into a char buffer. If you have any inc/def ref to do to the objects that
  2211. * contain the buffer, do it in the caller. This function returns the number
  2212. * of bytes successfully read. If there was an error, it returns -1. Note
  2213. * that it is also possible that we return a number of bytes smaller than the
  2214. * request bytes.
  2215. *
  2216. * 'addr' is a return value for the address object. Note that you must decref
  2217. * it yourself.
  2218. */
  2219. static ssize_t
  2220. sock_recvfrom_guts(PySocketSockObject *s, char* cbuf, int len, int flags,
  2221. PyObject** addr)
  2222. {
  2223. sock_addr_t addrbuf;
  2224. int timeout;
  2225. ssize_t n = -1;
  2226. socklen_t addrlen;
  2227. *addr = NULL;
  2228. if (!getsockaddrlen(s, &addrlen))
  2229. return -1;
  2230. if (!IS_SELECTABLE(s)) {
  2231. select_error();
  2232. return -1;
  2233. }
  2234. Py_BEGIN_ALLOW_THREADS
  2235. memset(&addrbuf, 0, addrlen);
  2236. timeout = internal_select(s, 0);
  2237. if (!timeout) {
  2238. #ifndef MS_WINDOWS
  2239. #if defined(PYOS_OS2) && !defined(PYCC_GCC)
  2240. n = recvfrom(s->sock_fd, cbuf, len, flags,
  2241. SAS2SA(&addrbuf), &addrlen);
  2242. #else
  2243. n = recvfrom(s->sock_fd, cbuf, len, flags,
  2244. (void *) &addrbuf, &addrlen);
  2245. #endif
  2246. #else
  2247. n = recvfrom(s->sock_fd, cbuf, len, flags,
  2248. SAS2SA(&addrbuf), &addrlen);
  2249. #endif
  2250. }
  2251. Py_END_ALLOW_THREADS
  2252. if (timeout == 1) {
  2253. PyErr_SetString(socket_timeout, "timed out");
  2254. return -1;
  2255. }
  2256. if (n < 0) {
  2257. s->errorhandler();
  2258. return -1;
  2259. }
  2260. if (!(*addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
  2261. addrlen, s->sock_proto)))
  2262. return -1;
  2263. return n;
  2264. }
  2265. /* s.recvfrom(nbytes [,flags]) method */
  2266. static PyObject *
  2267. sock_recvfrom(PySocketSockObject *s, PyObject *args)
  2268. {
  2269. PyObject *buf = NULL;
  2270. PyObject *addr = NULL;
  2271. PyObject *ret = NULL;
  2272. int recvlen, flags = 0;
  2273. ssize_t outlen;
  2274. if (!PyArg_ParseTuple(args, "i|i:recvfrom", &recvlen, &flags))
  2275. return NULL;
  2276. if (recvlen < 0) {
  2277. PyErr_SetString(PyExc_ValueError,
  2278. "negative buffersize in recvfrom");
  2279. return NULL;
  2280. }
  2281. buf = PyString_FromStringAndSize((char *) 0, recvlen);
  2282. if (buf == NULL)
  2283. return NULL;
  2284. outlen = sock_recvfrom_guts(s, PyString_AS_STRING(buf),
  2285. recvlen, flags, &addr);
  2286. if (outlen < 0) {
  2287. goto finally;
  2288. }
  2289. if (outlen != recvlen) {
  2290. /* We did not read as many bytes as we anticipated, resize the
  2291. string if possible and be successful. */
  2292. if (_PyString_Resize(&buf, outlen) < 0)
  2293. /* Oopsy, not so successful after all. */
  2294. goto finally;
  2295. }
  2296. ret = PyTuple_Pack(2, buf, addr);
  2297. finally:
  2298. Py_XDECREF(buf);
  2299. Py_XDECREF(addr);
  2300. return ret;
  2301. }
  2302. PyDoc_STRVAR(recvfrom_doc,
  2303. "recvfrom(buffersize[, flags]) -> (data, address info)\n\
  2304. \n\
  2305. Like recv(buffersize, flags) but also return the sender's address info.");
  2306. /* s.recvfrom_into(buffer[, nbytes [,flags]]) method */
  2307. static PyObject *
  2308. sock_recvfrom_into(PySocketSockObject *s, PyObject *args, PyObject* kwds)
  2309. {
  2310. static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
  2311. int recvlen = 0, flags = 0;
  2312. ssize_t readlen;
  2313. Py_buffer buf;
  2314. int buflen;
  2315. PyObject *addr = NULL;
  2316. if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recvfrom_into",
  2317. kwlist, &buf,
  2318. &recvlen, &flags))
  2319. return NULL;
  2320. buflen = buf.len;
  2321. assert(buf.buf != 0 && buflen > 0);
  2322. if (recvlen < 0) {
  2323. PyErr_SetString(PyExc_ValueError,
  2324. "negative buffersize in recvfrom_into");
  2325. goto error;
  2326. }
  2327. if (recvlen == 0) {
  2328. /* If nbytes was not specified, use the buffer's length */
  2329. recvlen = buflen;
  2330. }
  2331. readlen = sock_recvfrom_guts(s, buf.buf, recvlen, flags, &addr);
  2332. if (readlen < 0) {
  2333. /* Return an error */
  2334. goto error;
  2335. }
  2336. PyBuffer_Release(&buf);
  2337. /* Return the number of bytes read and the address. Note that we do
  2338. not do anything special here in the case that readlen < recvlen. */
  2339. return Py_BuildValue("lN", readlen, addr);
  2340. error:
  2341. Py_XDECREF(addr);
  2342. PyBuffer_Release(&buf);
  2343. return NULL;
  2344. }
  2345. PyDoc_STRVAR(recvfrom_into_doc,
  2346. "recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)\n\
  2347. \n\
  2348. Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.");
  2349. /* s.send(data [,flags]) method */
  2350. static PyObject *
  2351. sock_send(PySocketSockObject *s, PyObject *args)
  2352. {
  2353. char *buf;
  2354. int len, n = -1, flags = 0, timeout;
  2355. Py_buffer pbuf;
  2356. if (!PyArg_ParseTuple(args, "s*|i:send", &pbuf, &flags))
  2357. return NULL;
  2358. if (!IS_SELECTABLE(s)) {
  2359. PyBuffer_Release(&pbuf);
  2360. return select_error();
  2361. }
  2362. buf = pbuf.buf;
  2363. len = pbuf.len;
  2364. Py_BEGIN_ALLOW_THREADS
  2365. timeout = internal_select(s, 1);
  2366. if (!timeout)
  2367. #ifdef __VMS
  2368. n = sendsegmented(s->sock_fd, buf, len, flags);
  2369. #else
  2370. n = send(s->sock_fd, buf, len, flags);
  2371. #endif
  2372. Py_END_ALLOW_THREADS
  2373. PyBuffer_Release(&pbuf);
  2374. if (timeout == 1) {
  2375. PyErr_SetString(socket_timeout, "timed out");
  2376. return NULL;
  2377. }
  2378. if (n < 0)
  2379. return s->errorhandler();
  2380. return PyInt_FromLong((long)n);
  2381. }
  2382. PyDoc_STRVAR(send_doc,
  2383. "send(data[, flags]) -> count\n\
  2384. \n\
  2385. Send a data string to the socket. For the optional flags\n\
  2386. argument, see the Unix manual. Return the number of bytes\n\
  2387. sent; this may be less than len(data) if the network is busy.");
  2388. /* s.sendall(data [,flags]) method */
  2389. static PyObject *
  2390. sock_sendall(PySocketSockObject *s, PyObject *args)
  2391. {
  2392. char *buf;
  2393. int len, n = -1, flags = 0, timeout, saved_errno;
  2394. Py_buffer pbuf;
  2395. if (!PyArg_ParseTuple(args, "s*|i:sendall", &pbuf, &flags))
  2396. return NULL;
  2397. buf = pbuf.buf;
  2398. len = pbuf.len;
  2399. if (!IS_SELECTABLE(s)) {
  2400. PyBuffer_Release(&pbuf);
  2401. return select_error();
  2402. }
  2403. do {
  2404. Py_BEGIN_ALLOW_THREADS
  2405. timeout = internal_select(s, 1);
  2406. n = -1;
  2407. if (!timeout) {
  2408. #ifdef __VMS
  2409. n = sendsegmented(s->sock_fd, buf, len, flags);
  2410. #else
  2411. n = send(s->sock_fd, buf, len, flags);
  2412. #endif
  2413. }
  2414. Py_END_ALLOW_THREADS
  2415. if (timeout == 1) {
  2416. PyBuffer_Release(&pbuf);
  2417. PyErr_SetString(socket_timeout, "timed out");
  2418. return NULL;
  2419. }
  2420. /* PyErr_CheckSignals() might change errno */
  2421. saved_errno = errno;
  2422. /* We must run our signal handlers before looping again.
  2423. send() can return a successful partial write when it is
  2424. interrupted, so we can't restrict ourselves to EINTR. */
  2425. if (PyErr_CheckSignals()) {
  2426. PyBuffer_Release(&pbuf);
  2427. return NULL;
  2428. }
  2429. if (n < 0) {
  2430. /* If interrupted, try again */
  2431. if (saved_errno == EINTR)
  2432. continue;
  2433. else
  2434. break;
  2435. }
  2436. buf += n;
  2437. len -= n;
  2438. } while (len > 0);
  2439. PyBuffer_Release(&pbuf);
  2440. if (n < 0)
  2441. return s->errorhandler();
  2442. Py_INCREF(Py_None);
  2443. return Py_None;
  2444. }
  2445. PyDoc_STRVAR(sendall_doc,
  2446. "sendall(data[, flags])\n\
  2447. \n\
  2448. Send a data string to the socket. For the optional flags\n\
  2449. argument, see the Unix manual. This calls send() repeatedly\n\
  2450. until all data is sent. If an error occurs, it's impossible\n\
  2451. to tell how much data has been sent.");
  2452. /* s.sendto(data, [flags,] sockaddr) method */
  2453. static PyObject *
  2454. sock_sendto(PySocketSockObject *s, PyObject *args)
  2455. {
  2456. Py_buffer pbuf;
  2457. PyObject *addro;
  2458. char *buf;
  2459. Py_ssize_t len;
  2460. sock_addr_t addrbuf;
  2461. int addrlen, n = -1, flags, timeout;
  2462. int arglen;
  2463. flags = 0;
  2464. arglen = PyTuple_Size(args);
  2465. switch(arglen) {
  2466. case 2:
  2467. PyArg_ParseTuple(args, "s*O:sendto", &pbuf, &addro);
  2468. break;
  2469. case 3:
  2470. PyArg_ParseTuple(args, "s*iO:sendto", &pbuf, &flags, &addro);
  2471. break;
  2472. default:
  2473. PyErr_Format(PyExc_TypeError, "sendto() takes 2 or 3"
  2474. " arguments (%d given)", arglen);
  2475. }
  2476. if (PyErr_Occurred())
  2477. return NULL;
  2478. buf = pbuf.buf;
  2479. len = pbuf.len;
  2480. if (!IS_SELECTABLE(s)) {
  2481. PyBuffer_Release(&pbuf);
  2482. return select_error();
  2483. }
  2484. if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) {
  2485. PyBuffer_Release(&pbuf);
  2486. return NULL;
  2487. }
  2488. Py_BEGIN_ALLOW_THREADS
  2489. timeout = internal_select(s, 1);
  2490. if (!timeout)
  2491. n = sendto(s->sock_fd, buf, len, flags, SAS2SA(&addrbuf), addrlen);
  2492. Py_END_ALLOW_THREADS
  2493. PyBuffer_Release(&pbuf);
  2494. if (timeout == 1) {
  2495. PyErr_SetString(socket_timeout, "timed out");
  2496. return NULL;
  2497. }
  2498. if (n < 0)
  2499. return s->errorhandler();
  2500. return PyInt_FromLong((long)n);
  2501. }
  2502. PyDoc_STRVAR(sendto_doc,
  2503. "sendto(data[, flags], address) -> count\n\
  2504. \n\
  2505. Like send(data, flags) but allows specifying the destination address.\n\
  2506. For IP sockets, the address is a pair (hostaddr, port).");
  2507. /* s.shutdown(how) method */
  2508. static PyObject *
  2509. sock_shutdown(PySocketSockObject *s, PyObject *arg)
  2510. {
  2511. int how;
  2512. int res;
  2513. how = _PyInt_AsInt(arg);
  2514. if (how == -1 && PyErr_Occurred())
  2515. return NULL;
  2516. Py_BEGIN_ALLOW_THREADS
  2517. res = shutdown(s->sock_fd, how);
  2518. Py_END_ALLOW_THREADS
  2519. if (res < 0)
  2520. return s->errorhandler();
  2521. Py_INCREF(Py_None);
  2522. return Py_None;
  2523. }
  2524. PyDoc_STRVAR(shutdown_doc,
  2525. "shutdown(flag)\n\
  2526. \n\
  2527. Shut down the reading side of the socket (flag == SHUT_RD), the writing side\n\
  2528. of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).");
  2529. #if defined(MS_WINDOWS) && defined(SIO_RCVALL)
  2530. static PyObject*
  2531. sock_ioctl(PySocketSockObject *s, PyObject *arg)
  2532. {
  2533. unsigned long cmd = SIO_RCVALL;
  2534. PyObject *argO;
  2535. DWORD recv;
  2536. if (!PyArg_ParseTuple(arg, "kO:ioctl", &cmd, &argO))
  2537. return NULL;
  2538. switch (cmd) {
  2539. case SIO_RCVALL: {
  2540. unsigned int option = RCVALL_ON;
  2541. if (!PyArg_ParseTuple(arg, "kI:ioctl", &cmd, &option))
  2542. return NULL;
  2543. if (WSAIoctl(s->sock_fd, cmd, &option, sizeof(option),
  2544. NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
  2545. return set_error();
  2546. }
  2547. return PyLong_FromUnsignedLong(recv); }
  2548. case SIO_KEEPALIVE_VALS: {
  2549. struct tcp_keepalive ka;
  2550. if (!PyArg_ParseTuple(arg, "k(kkk):ioctl", &cmd,
  2551. &ka.onoff, &ka.keepalivetime, &ka.keepaliveinterval))
  2552. return NULL;
  2553. if (WSAIoctl(s->sock_fd, cmd, &ka, sizeof(ka),
  2554. NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
  2555. return set_error();
  2556. }
  2557. return PyLong_FromUnsignedLong(recv); }
  2558. default:
  2559. PyErr_Format(PyExc_ValueError, "invalid ioctl command %d", cmd);
  2560. return NULL;
  2561. }
  2562. }
  2563. PyDoc_STRVAR(sock_ioctl_doc,
  2564. "ioctl(cmd, option) -> long\n\
  2565. \n\
  2566. Control the socket with WSAIoctl syscall. Currently supported 'cmd' values are\n\
  2567. SIO_RCVALL: 'option' must be one of the socket.RCVALL_* constants.\n\
  2568. SIO_KEEPALIVE_VALS: 'option' is a tuple of (onoff, timeout, interval).");
  2569. #endif
  2570. /* List of methods for socket objects */
  2571. static PyMethodDef sock_methods[] = {
  2572. {"accept", (PyCFunction)sock_accept, METH_NOARGS,
  2573. accept_doc},
  2574. {"bind", (PyCFunction)sock_bind, METH_O,
  2575. bind_doc},
  2576. {"close", (PyCFunction)sock_close, METH_NOARGS,
  2577. close_doc},
  2578. {"connect", (PyCFunction)sock_connect, METH_O,
  2579. connect_doc},
  2580. {"connect_ex", (PyCFunction)sock_connect_ex, METH_O,
  2581. connect_ex_doc},
  2582. #ifndef NO_DUP
  2583. {"dup", (PyCFunction)sock_dup, METH_NOARGS,
  2584. dup_doc},
  2585. #endif
  2586. {"fileno", (PyCFunction)sock_fileno, METH_NOARGS,
  2587. fileno_doc},
  2588. #ifdef HAVE_GETPEERNAME
  2589. {"getpeername", (PyCFunction)sock_getpeername,
  2590. METH_NOARGS, getpeername_doc},
  2591. #endif
  2592. {"getsockname", (PyCFunction)sock_getsockname,
  2593. METH_NOARGS, getsockname_doc},
  2594. {"getsockopt", (PyCFunction)sock_getsockopt, METH_VARARGS,
  2595. getsockopt_doc},
  2596. #if defined(MS_WINDOWS) && defined(SIO_RCVALL)
  2597. {"ioctl", (PyCFunction)sock_ioctl, METH_VARARGS,
  2598. sock_ioctl_doc},
  2599. #endif
  2600. {"listen", (PyCFunction)sock_listen, METH_O,
  2601. listen_doc},
  2602. #ifndef NO_DUP
  2603. {"makefile", (PyCFunction)sock_makefile, METH_VARARGS,
  2604. makefile_doc},
  2605. #endif
  2606. {"recv", (PyCFunction)sock_recv, METH_VARARGS,
  2607. recv_doc},
  2608. {"recv_into", (PyCFunction)sock_recv_into, METH_VARARGS | METH_KEYWORDS,
  2609. recv_into_doc},
  2610. {"recvfrom", (PyCFunction)sock_recvfrom, METH_VARARGS,
  2611. recvfrom_doc},
  2612. {"recvfrom_into", (PyCFunction)sock_recvfrom_into, METH_VARARGS | METH_KEYWORDS,
  2613. recvfrom_into_doc},
  2614. {"send", (PyCFunction)sock_send, METH_VARARGS,
  2615. send_doc},
  2616. {"sendall", (PyCFunction)sock_sendall, METH_VARARGS,
  2617. sendall_doc},
  2618. {"sendto", (PyCFunction)sock_sendto, METH_VARARGS,
  2619. sendto_doc},
  2620. {"setblocking", (PyCFunction)sock_setblocking, METH_O,
  2621. setblocking_doc},
  2622. {"settimeout", (PyCFunction)sock_settimeout, METH_O,
  2623. settimeout_doc},
  2624. {"gettimeout", (PyCFunction)sock_gettimeout, METH_NOARGS,
  2625. gettimeout_doc},
  2626. {"setsockopt", (PyCFunction)sock_setsockopt, METH_VARARGS,
  2627. setsockopt_doc},
  2628. {"shutdown", (PyCFunction)sock_shutdown, METH_O,
  2629. shutdown_doc},
  2630. #ifdef RISCOS
  2631. {"sleeptaskw", (PyCFunction)sock_sleeptaskw, METH_O,
  2632. sleeptaskw_doc},
  2633. #endif
  2634. {NULL, NULL} /* sentinel */
  2635. };
  2636. /* SockObject members */
  2637. static PyMemberDef sock_memberlist[] = {
  2638. {"family", T_INT, offsetof(PySocketSockObject, sock_family), READONLY, "the socket family"},
  2639. {"type", T_INT, offsetof(PySocketSockObject, sock_type), READONLY, "the socket type"},
  2640. {"proto", T_INT, offsetof(PySocketSockObject, sock_proto), READONLY, "the socket protocol"},
  2641. {"timeout", T_DOUBLE, offsetof(PySocketSockObject, sock_timeout), READONLY, "the socket timeout"},
  2642. {0},
  2643. };
  2644. /* Deallocate a socket object in response to the last Py_DECREF().
  2645. First close the file description. */
  2646. static void
  2647. sock_dealloc(PySocketSockObject *s)
  2648. {
  2649. if (s->sock_fd != -1)
  2650. (void) SOCKETCLOSE(s->sock_fd);
  2651. Py_TYPE(s)->tp_free((PyObject *)s);
  2652. }
  2653. static PyObject *
  2654. sock_repr(PySocketSockObject *s)
  2655. {
  2656. char buf[512];
  2657. #if SIZEOF_SOCKET_T > SIZEOF_LONG
  2658. if (s->sock_fd > LONG_MAX) {
  2659. /* this can occur on Win64, and actually there is a special
  2660. ugly printf formatter for decimal pointer length integer
  2661. printing, only bother if necessary*/
  2662. PyErr_SetString(PyExc_OverflowError,
  2663. "no printf formatter to display "
  2664. "the socket descriptor in decimal");
  2665. return NULL;
  2666. }
  2667. #endif
  2668. PyOS_snprintf(
  2669. buf, sizeof(buf),
  2670. "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
  2671. (long)s->sock_fd, s->sock_family,
  2672. s->sock_type,
  2673. s->sock_proto);
  2674. return PyString_FromString(buf);
  2675. }
  2676. /* Create a new, uninitialized socket object. */
  2677. static PyObject *
  2678. sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  2679. {
  2680. PyObject *new;
  2681. new = type->tp_alloc(type, 0);
  2682. if (new != NULL) {
  2683. ((PySocketSockObject *)new)->sock_fd = -1;
  2684. ((PySocketSockObject *)new)->sock_timeout = -1.0;
  2685. ((PySocketSockObject *)new)->errorhandler = &set_error;
  2686. }
  2687. return new;
  2688. }
  2689. /* Initialize a new socket object. */
  2690. /*ARGSUSED*/
  2691. static int
  2692. sock_initobj(PyObject *self, PyObject *args, PyObject *kwds)
  2693. {
  2694. PySocketSockObject *s = (PySocketSockObject *)self;
  2695. SOCKET_T fd;
  2696. int family = AF_INET, type = SOCK_STREAM, proto = 0;
  2697. static char *keywords[] = {"family", "type", "proto", 0};
  2698. if (!PyArg_ParseTupleAndKeywords(args, kwds,
  2699. "|iii:socket", keywords,
  2700. &family, &type, &proto))
  2701. return -1;
  2702. Py_BEGIN_ALLOW_THREADS
  2703. fd = socket(family, type, proto);
  2704. Py_END_ALLOW_THREADS
  2705. #ifdef MS_WINDOWS
  2706. if (fd == INVALID_SOCKET)
  2707. #else
  2708. if (fd < 0)
  2709. #endif
  2710. {
  2711. set_error();
  2712. return -1;
  2713. }
  2714. init_sockobject(s, fd, family, type, proto);
  2715. return 0;
  2716. }
  2717. /* Type object for socket objects. */
  2718. static PyTypeObject sock_type = {
  2719. PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */
  2720. "_socket.socket", /* tp_name */
  2721. sizeof(PySocketSockObject), /* tp_basicsize */
  2722. 0, /* tp_itemsize */
  2723. (destructor)sock_dealloc, /* tp_dealloc */
  2724. 0, /* tp_print */
  2725. 0, /* tp_getattr */
  2726. 0, /* tp_setattr */
  2727. 0, /* tp_compare */
  2728. (reprfunc)sock_repr, /* tp_repr */
  2729. 0, /* tp_as_number */
  2730. 0, /* tp_as_sequence */
  2731. 0, /* tp_as_mapping */
  2732. 0, /* tp_hash */
  2733. 0, /* tp_call */
  2734. 0, /* tp_str */
  2735. PyObject_GenericGetAttr, /* tp_getattro */
  2736. 0, /* tp_setattro */
  2737. 0, /* tp_as_buffer */
  2738. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
  2739. sock_doc, /* tp_doc */
  2740. 0, /* tp_traverse */
  2741. 0, /* tp_clear */
  2742. 0, /* tp_richcompare */
  2743. 0, /* tp_weaklistoffset */
  2744. 0, /* tp_iter */
  2745. 0, /* tp_iternext */
  2746. sock_methods, /* tp_methods */
  2747. sock_memberlist, /* tp_members */
  2748. 0, /* tp_getset */
  2749. 0, /* tp_base */
  2750. 0, /* tp_dict */
  2751. 0, /* tp_descr_get */
  2752. 0, /* tp_descr_set */
  2753. 0, /* tp_dictoffset */
  2754. sock_initobj, /* tp_init */
  2755. PyType_GenericAlloc, /* tp_alloc */
  2756. sock_new, /* tp_new */
  2757. PyObject_Del, /* tp_free */
  2758. };
  2759. /* Python interface to gethostname(). */
  2760. /*ARGSUSED*/
  2761. static PyObject *
  2762. socket_gethostname(PyObject *self, PyObject *unused)
  2763. {
  2764. char buf[1024];
  2765. int res;
  2766. Py_BEGIN_ALLOW_THREADS
  2767. res = gethostname(buf, (int) sizeof buf - 1);
  2768. Py_END_ALLOW_THREADS
  2769. if (res < 0)
  2770. return set_error();
  2771. buf[sizeof buf - 1] = '\0';
  2772. return PyString_FromString(buf);
  2773. }
  2774. PyDoc_STRVAR(gethostname_doc,
  2775. "gethostname() -> string\n\
  2776. \n\
  2777. Return the current host name.");
  2778. /* Python interface to gethostbyname(name). */
  2779. /*ARGSUSED*/
  2780. static PyObject *
  2781. socket_gethostbyname(PyObject *self, PyObject *args)
  2782. {
  2783. char *name;
  2784. sock_addr_t addrbuf;
  2785. if (!PyArg_ParseTuple(args, "s:gethostbyname", &name))
  2786. return NULL;
  2787. if (setipaddr(name, SAS2SA(&addrbuf), sizeof(addrbuf), AF_INET) < 0)
  2788. return NULL;
  2789. return makeipaddr(SAS2SA(&addrbuf), sizeof(struct sockaddr_in));
  2790. }
  2791. PyDoc_STRVAR(gethostbyname_doc,
  2792. "gethostbyname(host) -> address\n\
  2793. \n\
  2794. Return the IP address (a string of the form '255.255.255.255') for a host.");
  2795. /* Convenience function common to gethostbyname_ex and gethostbyaddr */
  2796. static PyObject *
  2797. gethost_common(struct hostent *h, struct sockaddr *addr, int alen, int af)
  2798. {
  2799. char **pch;
  2800. PyObject *rtn_tuple = (PyObject *)NULL;
  2801. PyObject *name_list = (PyObject *)NULL;
  2802. PyObject *addr_list = (PyObject *)NULL;
  2803. PyObject *tmp;
  2804. if (h == NULL) {
  2805. /* Let's get real error message to return */
  2806. #ifndef RISCOS
  2807. set_herror(h_errno);
  2808. #else
  2809. PyErr_SetString(socket_error, "host not found");
  2810. #endif
  2811. return NULL;
  2812. }
  2813. if (h->h_addrtype != af) {
  2814. /* Let's get real error message to return */
  2815. PyErr_SetString(socket_error,
  2816. (char *)strerror(EAFNOSUPPORT));
  2817. return NULL;
  2818. }
  2819. switch (af) {
  2820. case AF_INET:
  2821. if (alen < sizeof(struct sockaddr_in))
  2822. return NULL;
  2823. break;
  2824. #ifdef ENABLE_IPV6
  2825. case AF_INET6:
  2826. if (alen < sizeof(struct sockaddr_in6))
  2827. return NULL;
  2828. break;
  2829. #endif
  2830. }
  2831. if ((name_list = PyList_New(0)) == NULL)
  2832. goto err;
  2833. if ((addr_list = PyList_New(0)) == NULL)
  2834. goto err;
  2835. /* SF #1511317: h_aliases can be NULL */
  2836. if (h->h_aliases) {
  2837. for (pch = h->h_aliases; *pch != NULL; pch++) {
  2838. int status;
  2839. tmp = PyString_FromString(*pch);
  2840. if (tmp == NULL)
  2841. goto err;
  2842. status = PyList_Append(name_list, tmp);
  2843. Py_DECREF(tmp);
  2844. if (status)
  2845. goto err;
  2846. }
  2847. }
  2848. for (pch = h->h_addr_list; *pch != NULL; pch++) {
  2849. int status;
  2850. switch (af) {
  2851. case AF_INET:
  2852. {
  2853. struct sockaddr_in sin;
  2854. memset(&sin, 0, sizeof(sin));
  2855. sin.sin_family = af;
  2856. #ifdef HAVE_SOCKADDR_SA_LEN
  2857. sin.sin_len = sizeof(sin);
  2858. #endif
  2859. memcpy(&sin.sin_addr, *pch, sizeof(sin.sin_addr));
  2860. tmp = makeipaddr((struct sockaddr *)&sin, sizeof(sin));
  2861. if (pch == h->h_addr_list && alen >= sizeof(sin))
  2862. memcpy((char *) addr, &sin, sizeof(sin));
  2863. break;
  2864. }
  2865. #ifdef ENABLE_IPV6
  2866. case AF_INET6:
  2867. {
  2868. struct sockaddr_in6 sin6;
  2869. memset(&sin6, 0, sizeof(sin6));
  2870. sin6.sin6_family = af;
  2871. #ifdef HAVE_SOCKADDR_SA_LEN
  2872. sin6.sin6_len = sizeof(sin6);
  2873. #endif
  2874. memcpy(&sin6.sin6_addr, *pch, sizeof(sin6.sin6_addr));
  2875. tmp = makeipaddr((struct sockaddr *)&sin6,
  2876. sizeof(sin6));
  2877. if (pch == h->h_addr_list && alen >= sizeof(sin6))
  2878. memcpy((char *) addr, &sin6, sizeof(sin6));
  2879. break;
  2880. }
  2881. #endif
  2882. default: /* can't happen */
  2883. PyErr_SetString(socket_error,
  2884. "unsupported address family");
  2885. return NULL;
  2886. }
  2887. if (tmp == NULL)
  2888. goto err;
  2889. status = PyList_Append(addr_list, tmp);
  2890. Py_DECREF(tmp);
  2891. if (status)
  2892. goto err;
  2893. }
  2894. rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list);
  2895. err:
  2896. Py_XDECREF(name_list);
  2897. Py_XDECREF(addr_list);
  2898. return rtn_tuple;
  2899. }
  2900. /* Python interface to gethostbyname_ex(name). */
  2901. /*ARGSUSED*/
  2902. static PyObject *
  2903. socket_gethostbyname_ex(PyObject *self, PyObject *args)
  2904. {
  2905. char *name;
  2906. struct hostent *h;
  2907. #ifdef ENABLE_IPV6
  2908. struct sockaddr_storage addr;
  2909. #else
  2910. struct sockaddr_in addr;
  2911. #endif
  2912. struct sockaddr *sa;
  2913. PyObject *ret;
  2914. #ifdef HAVE_GETHOSTBYNAME_R
  2915. struct hostent hp_allocated;
  2916. #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
  2917. struct hostent_data data;
  2918. #else
  2919. char buf[16384];
  2920. int buf_len = (sizeof buf) - 1;
  2921. int errnop;
  2922. #endif
  2923. #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
  2924. int result;
  2925. #endif
  2926. #endif /* HAVE_GETHOSTBYNAME_R */
  2927. if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name))
  2928. return NULL;
  2929. if (setipaddr(name, (struct sockaddr *)&addr, sizeof(addr), AF_INET) < 0)
  2930. return NULL;
  2931. Py_BEGIN_ALLOW_THREADS
  2932. #ifdef HAVE_GETHOSTBYNAME_R
  2933. #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
  2934. result = gethostbyname_r(name, &hp_allocated, buf, buf_len,
  2935. &h, &errnop);
  2936. #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
  2937. h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
  2938. #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
  2939. memset((void *) &data, '\0', sizeof(data));
  2940. result = gethostbyname_r(name, &hp_allocated, &data);
  2941. h = (result != 0) ? NULL : &hp_allocated;
  2942. #endif
  2943. #else /* not HAVE_GETHOSTBYNAME_R */
  2944. #ifdef USE_GETHOSTBYNAME_LOCK
  2945. PyThread_acquire_lock(netdb_lock, 1);
  2946. #endif
  2947. h = gethostbyname(name);
  2948. #endif /* HAVE_GETHOSTBYNAME_R */
  2949. Py_END_ALLOW_THREADS
  2950. /* Some C libraries would require addr.__ss_family instead of
  2951. addr.ss_family.
  2952. Therefore, we cast the sockaddr_storage into sockaddr to
  2953. access sa_family. */
  2954. sa = (struct sockaddr*)&addr;
  2955. ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr),
  2956. sa->sa_family);
  2957. #ifdef USE_GETHOSTBYNAME_LOCK
  2958. PyThread_release_lock(netdb_lock);
  2959. #endif
  2960. return ret;
  2961. }
  2962. PyDoc_STRVAR(ghbn_ex_doc,
  2963. "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
  2964. \n\
  2965. Return the true host name, a list of aliases, and a list of IP addresses,\n\
  2966. for a host. The host argument is a string giving a host name or IP number.");
  2967. /* Python interface to gethostbyaddr(IP). */
  2968. /*ARGSUSED*/
  2969. static PyObject *
  2970. socket_gethostbyaddr(PyObject *self, PyObject *args)
  2971. {
  2972. #ifdef ENABLE_IPV6
  2973. struct sockaddr_storage addr;
  2974. #else
  2975. struct sockaddr_in addr;
  2976. #endif
  2977. struct sockaddr *sa = (struct sockaddr *)&addr;
  2978. char *ip_num;
  2979. struct hostent *h;
  2980. PyObject *ret;
  2981. #ifdef HAVE_GETHOSTBYNAME_R
  2982. struct hostent hp_allocated;
  2983. #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
  2984. struct hostent_data data;
  2985. #else
  2986. /* glibcs up to 2.10 assume that the buf argument to
  2987. gethostbyaddr_r is 8-byte aligned, which at least llvm-gcc
  2988. does not ensure. The attribute below instructs the compiler
  2989. to maintain this alignment. */
  2990. char buf[16384] Py_ALIGNED(8);
  2991. int buf_len = (sizeof buf) - 1;
  2992. int errnop;
  2993. #endif
  2994. #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
  2995. int result;
  2996. #endif
  2997. #endif /* HAVE_GETHOSTBYNAME_R */
  2998. char *ap;
  2999. int al;
  3000. int af;
  3001. if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num))
  3002. return NULL;
  3003. af = AF_UNSPEC;
  3004. if (setipaddr(ip_num, sa, sizeof(addr), af) < 0)
  3005. return NULL;
  3006. af = sa->sa_family;
  3007. ap = NULL;
  3008. switch (af) {
  3009. case AF_INET:
  3010. ap = (char *)&((struct sockaddr_in *)sa)->sin_addr;
  3011. al = sizeof(((struct sockaddr_in *)sa)->sin_addr);
  3012. break;
  3013. #ifdef ENABLE_IPV6
  3014. case AF_INET6:
  3015. ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr;
  3016. al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr);
  3017. break;
  3018. #endif
  3019. default:
  3020. PyErr_SetString(socket_error, "unsupported address family");
  3021. return NULL;
  3022. }
  3023. Py_BEGIN_ALLOW_THREADS
  3024. #ifdef HAVE_GETHOSTBYNAME_R
  3025. #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
  3026. result = gethostbyaddr_r(ap, al, af,
  3027. &hp_allocated, buf, buf_len,
  3028. &h, &errnop);
  3029. #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
  3030. h = gethostbyaddr_r(ap, al, af,
  3031. &hp_allocated, buf, buf_len, &errnop);
  3032. #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
  3033. memset((void *) &data, '\0', sizeof(data));
  3034. result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data);
  3035. h = (result != 0) ? NULL : &hp_allocated;
  3036. #endif
  3037. #else /* not HAVE_GETHOSTBYNAME_R */
  3038. #ifdef USE_GETHOSTBYNAME_LOCK
  3039. PyThread_acquire_lock(netdb_lock, 1);
  3040. #endif
  3041. h = gethostbyaddr(ap, al, af);
  3042. #endif /* HAVE_GETHOSTBYNAME_R */
  3043. Py_END_ALLOW_THREADS
  3044. ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), af);
  3045. #ifdef USE_GETHOSTBYNAME_LOCK
  3046. PyThread_release_lock(netdb_lock);
  3047. #endif
  3048. return ret;
  3049. }
  3050. PyDoc_STRVAR(gethostbyaddr_doc,
  3051. "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
  3052. \n\
  3053. Return the true host name, a list of aliases, and a list of IP addresses,\n\
  3054. for a host. The host argument is a string giving a host name or IP number.");
  3055. /* Python interface to getservbyname(name).
  3056. This only returns the port number, since the other info is already
  3057. known or not useful (like the list of aliases). */
  3058. /*ARGSUSED*/
  3059. static PyObject *
  3060. socket_getservbyname(PyObject *self, PyObject *args)
  3061. {
  3062. char *name, *proto=NULL;
  3063. struct servent *sp;
  3064. if (!PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto))
  3065. return NULL;
  3066. Py_BEGIN_ALLOW_THREADS
  3067. sp = getservbyname(name, proto);
  3068. Py_END_ALLOW_THREADS
  3069. if (sp == NULL) {
  3070. PyErr_SetString(socket_error, "service/proto not found");
  3071. return NULL;
  3072. }
  3073. return PyInt_FromLong((long) ntohs(sp->s_port));
  3074. }
  3075. PyDoc_STRVAR(getservbyname_doc,
  3076. "getservbyname(servicename[, protocolname]) -> integer\n\
  3077. \n\
  3078. Return a port number from a service name and protocol name.\n\
  3079. The optional protocol name, if given, should be 'tcp' or 'udp',\n\
  3080. otherwise any protocol will match.");
  3081. /* Python interface to getservbyport(port).
  3082. This only returns the service name, since the other info is already
  3083. known or not useful (like the list of aliases). */
  3084. /*ARGSUSED*/
  3085. static PyObject *
  3086. socket_getservbyport(PyObject *self, PyObject *args)
  3087. {
  3088. int port;
  3089. char *proto=NULL;
  3090. struct servent *sp;
  3091. if (!PyArg_ParseTuple(args, "i|s:getservbyport", &port, &proto))
  3092. return NULL;
  3093. if (port < 0 || port > 0xffff) {
  3094. PyErr_SetString(
  3095. PyExc_OverflowError,
  3096. "getservbyport: port must be 0-65535.");
  3097. return NULL;
  3098. }
  3099. Py_BEGIN_ALLOW_THREADS
  3100. sp = getservbyport(htons((short)port), proto);
  3101. Py_END_ALLOW_THREADS
  3102. if (sp == NULL) {
  3103. PyErr_SetString(socket_error, "port/proto not found");
  3104. return NULL;
  3105. }
  3106. return PyString_FromString(sp->s_name);
  3107. }
  3108. PyDoc_STRVAR(getservbyport_doc,
  3109. "getservbyport(port[, protocolname]) -> string\n\
  3110. \n\
  3111. Return the service name from a port number and protocol name.\n\
  3112. The optional protocol name, if given, should be 'tcp' or 'udp',\n\
  3113. otherwise any protocol will match.");
  3114. /* Python interface to getprotobyname(name).
  3115. This only returns the protocol number, since the other info is
  3116. already known or not useful (like the list of aliases). */
  3117. /*ARGSUSED*/
  3118. static PyObject *
  3119. socket_getprotobyname(PyObject *self, PyObject *args)
  3120. {
  3121. char *name;
  3122. struct protoent *sp;
  3123. #ifdef __BEOS__
  3124. /* Not available in BeOS yet. - [cjh] */
  3125. PyErr_SetString(socket_error, "getprotobyname not supported");
  3126. return NULL;
  3127. #else
  3128. if (!PyArg_ParseTuple(args, "s:getprotobyname", &name))
  3129. return NULL;
  3130. Py_BEGIN_ALLOW_THREADS
  3131. sp = getprotobyname(name);
  3132. Py_END_ALLOW_THREADS
  3133. if (sp == NULL) {
  3134. PyErr_SetString(socket_error, "protocol not found");
  3135. return NULL;
  3136. }
  3137. return PyInt_FromLong((long) sp->p_proto);
  3138. #endif
  3139. }
  3140. PyDoc_STRVAR(getprotobyname_doc,
  3141. "getprotobyname(name) -> integer\n\
  3142. \n\
  3143. Return the protocol number for the named protocol. (Rarely used.)");
  3144. #ifdef HAVE_SOCKETPAIR
  3145. /* Create a pair of sockets using the socketpair() function.
  3146. Arguments as for socket() except the default family is AF_UNIX if
  3147. defined on the platform; otherwise, the default is AF_INET. */
  3148. /*ARGSUSED*/
  3149. static PyObject *
  3150. socket_socketpair(PyObject *self, PyObject *args)
  3151. {
  3152. PySocketSockObject *s0 = NULL, *s1 = NULL;
  3153. SOCKET_T sv[2];
  3154. int family, type = SOCK_STREAM, proto = 0;
  3155. PyObject *res = NULL;
  3156. #if defined(AF_UNIX)
  3157. family = AF_UNIX;
  3158. #else
  3159. family = AF_INET;
  3160. #endif
  3161. if (!PyArg_ParseTuple(args, "|iii:socketpair",
  3162. &family, &type, &proto))
  3163. return NULL;
  3164. /* Create a pair of socket fds */
  3165. if (socketpair(family, type, proto, sv) < 0)
  3166. return set_error();
  3167. s0 = new_sockobject(sv[0], family, type, proto);
  3168. if (s0 == NULL)
  3169. goto finally;
  3170. s1 = new_sockobject(sv[1], family, type, proto);
  3171. if (s1 == NULL)
  3172. goto finally;
  3173. res = PyTuple_Pack(2, s0, s1);
  3174. finally:
  3175. if (res == NULL) {
  3176. if (s0 == NULL)
  3177. SOCKETCLOSE(sv[0]);
  3178. if (s1 == NULL)
  3179. SOCKETCLOSE(sv[1]);
  3180. }
  3181. Py_XDECREF(s0);
  3182. Py_XDECREF(s1);
  3183. return res;
  3184. }
  3185. PyDoc_STRVAR(socketpair_doc,
  3186. "socketpair([family[, type[, proto]]]) -> (socket object, socket object)\n\
  3187. \n\
  3188. Create a pair of socket objects from the sockets returned by the platform\n\
  3189. socketpair() function.\n\
  3190. The arguments are the same as for socket() except the default family is\n\
  3191. AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");
  3192. #endif /* HAVE_SOCKETPAIR */
  3193. #ifndef NO_DUP
  3194. /* Create a socket object from a numeric file description.
  3195. Useful e.g. if stdin is a socket.
  3196. Additional arguments as for socket(). */
  3197. /*ARGSUSED*/
  3198. static PyObject *
  3199. socket_fromfd(PyObject *self, PyObject *args)
  3200. {
  3201. PySocketSockObject *s;
  3202. SOCKET_T fd;
  3203. int family, type, proto = 0;
  3204. if (!PyArg_ParseTuple(args, "iii|i:fromfd",
  3205. &fd, &family, &type, &proto))
  3206. return NULL;
  3207. /* Dup the fd so it and the socket can be closed independently */
  3208. fd = dup(fd);
  3209. if (fd < 0)
  3210. return set_error();
  3211. s = new_sockobject(fd, family, type, proto);
  3212. return (PyObject *) s;
  3213. }
  3214. PyDoc_STRVAR(fromfd_doc,
  3215. "fromfd(fd, family, type[, proto]) -> socket object\n\
  3216. \n\
  3217. Create a socket object from a duplicate of the given\n\
  3218. file descriptor.\n\
  3219. The remaining arguments are the same as for socket().");
  3220. #endif /* NO_DUP */
  3221. static PyObject *
  3222. socket_ntohs(PyObject *self, PyObject *args)
  3223. {
  3224. int x1, x2;
  3225. if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) {
  3226. return NULL;
  3227. }
  3228. if (x1 < 0) {
  3229. PyErr_SetString(PyExc_OverflowError,
  3230. "can't convert negative number to unsigned long");
  3231. return NULL;
  3232. }
  3233. x2 = (unsigned int)ntohs((unsigned short)x1);
  3234. return PyInt_FromLong(x2);
  3235. }
  3236. PyDoc_STRVAR(ntohs_doc,
  3237. "ntohs(integer) -> integer\n\
  3238. \n\
  3239. Convert a 16-bit integer from network to host byte order.");
  3240. static PyObject *
  3241. socket_ntohl(PyObject *self, PyObject *arg)
  3242. {
  3243. unsigned long x;
  3244. if (PyInt_Check(arg)) {
  3245. x = PyInt_AS_LONG(arg);
  3246. if (x == (unsigned long) -1 && PyErr_Occurred())
  3247. return NULL;
  3248. if ((long)x < 0) {
  3249. PyErr_SetString(PyExc_OverflowError,
  3250. "can't convert negative number to unsigned long");
  3251. return NULL;
  3252. }
  3253. }
  3254. else if (PyLong_Check(arg)) {
  3255. x = PyLong_AsUnsignedLong(arg);
  3256. if (x == (unsigned long) -1 && PyErr_Occurred())
  3257. return NULL;
  3258. #if SIZEOF_LONG > 4
  3259. {
  3260. unsigned long y;
  3261. /* only want the trailing 32 bits */
  3262. y = x & 0xFFFFFFFFUL;
  3263. if (y ^ x)
  3264. return PyErr_Format(PyExc_OverflowError,
  3265. "long int larger than 32 bits");
  3266. x = y;
  3267. }
  3268. #endif
  3269. }
  3270. else
  3271. return PyErr_Format(PyExc_TypeError,
  3272. "expected int/long, %s found",
  3273. Py_TYPE(arg)->tp_name);
  3274. if (x == (unsigned long) -1 && PyErr_Occurred())
  3275. return NULL;
  3276. return PyLong_FromUnsignedLong(ntohl(x));
  3277. }
  3278. PyDoc_STRVAR(ntohl_doc,
  3279. "ntohl(integer) -> integer\n\
  3280. \n\
  3281. Convert a 32-bit integer from network to host byte order.");
  3282. static PyObject *
  3283. socket_htons(PyObject *self, PyObject *args)
  3284. {
  3285. int x1, x2;
  3286. if (!PyArg_ParseTuple(args, "i:htons", &x1)) {
  3287. return NULL;
  3288. }
  3289. if (x1 < 0) {
  3290. PyErr_SetString(PyExc_OverflowError,
  3291. "can't convert negative number to unsigned long");
  3292. return NULL;
  3293. }
  3294. x2 = (unsigned int)htons((unsigned short)x1);
  3295. return PyInt_FromLong(x2);
  3296. }
  3297. PyDoc_STRVAR(htons_doc,
  3298. "htons(integer) -> integer\n\
  3299. \n\
  3300. Convert a 16-bit integer from host to network byte order.");
  3301. static PyObject *
  3302. socket_htonl(PyObject *self, PyObject *arg)
  3303. {
  3304. unsigned long x;
  3305. if (PyInt_Check(arg)) {
  3306. x = PyInt_AS_LONG(arg);
  3307. if (x == (unsigned long) -1 && PyErr_Occurred())
  3308. return NULL;
  3309. if ((long)x < 0) {
  3310. PyErr_SetString(PyExc_OverflowError,
  3311. "can't convert negative number to unsigned long");
  3312. return NULL;
  3313. }
  3314. }
  3315. else if (PyLong_Check(arg)) {
  3316. x = PyLong_AsUnsignedLong(arg);
  3317. if (x == (unsigned long) -1 && PyErr_Occurred())
  3318. return NULL;
  3319. #if SIZEOF_LONG > 4
  3320. {
  3321. unsigned long y;
  3322. /* only want the trailing 32 bits */
  3323. y = x & 0xFFFFFFFFUL;
  3324. if (y ^ x)
  3325. return PyErr_Format(PyExc_OverflowError,
  3326. "long int larger than 32 bits");
  3327. x = y;
  3328. }
  3329. #endif
  3330. }
  3331. else
  3332. return PyErr_Format(PyExc_TypeError,
  3333. "expected int/long, %s found",
  3334. Py_TYPE(arg)->tp_name);
  3335. return PyLong_FromUnsignedLong(htonl((unsigned long)x));
  3336. }
  3337. PyDoc_STRVAR(htonl_doc,
  3338. "htonl(integer) -> integer\n\
  3339. \n\
  3340. Convert a 32-bit integer from host to network byte order.");
  3341. /* socket.inet_aton() and socket.inet_ntoa() functions. */
  3342. PyDoc_STRVAR(inet_aton_doc,
  3343. "inet_aton(string) -> packed 32-bit IP representation\n\
  3344. \n\
  3345. Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
  3346. binary format used in low-level network functions.");
  3347. static PyObject*
  3348. socket_inet_aton(PyObject *self, PyObject *args)
  3349. {
  3350. #ifndef INADDR_NONE
  3351. #define INADDR_NONE (-1)
  3352. #endif
  3353. #ifdef HAVE_INET_ATON
  3354. struct in_addr buf;
  3355. #endif
  3356. #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
  3357. #if (SIZEOF_INT != 4)
  3358. #error "Not sure if in_addr_t exists and int is not 32-bits."
  3359. #endif
  3360. /* Have to use inet_addr() instead */
  3361. unsigned int packed_addr;
  3362. #endif
  3363. char *ip_addr;
  3364. if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr))
  3365. return NULL;
  3366. #ifdef HAVE_INET_ATON
  3367. #ifdef USE_INET_ATON_WEAKLINK
  3368. if (inet_aton != NULL) {
  3369. #endif
  3370. if (inet_aton(ip_addr, &buf))
  3371. return PyString_FromStringAndSize((char *)(&buf),
  3372. sizeof(buf));
  3373. PyErr_SetString(socket_error,
  3374. "illegal IP address string passed to inet_aton");
  3375. return NULL;
  3376. #ifdef USE_INET_ATON_WEAKLINK
  3377. } else {
  3378. #endif
  3379. #endif
  3380. #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
  3381. /* special-case this address as inet_addr might return INADDR_NONE
  3382. * for this */
  3383. if (strcmp(ip_addr, "255.255.255.255") == 0) {
  3384. packed_addr = 0xFFFFFFFF;
  3385. } else {
  3386. packed_addr = inet_addr(ip_addr);
  3387. if (packed_addr == INADDR_NONE) { /* invalid address */
  3388. PyErr_SetString(socket_error,
  3389. "illegal IP address string passed to inet_aton");
  3390. return NULL;
  3391. }
  3392. }
  3393. return PyString_FromStringAndSize((char *) &packed_addr,
  3394. sizeof(packed_addr));
  3395. #ifdef USE_INET_ATON_WEAKLINK
  3396. }
  3397. #endif
  3398. #endif
  3399. }
  3400. PyDoc_STRVAR(inet_ntoa_doc,
  3401. "inet_ntoa(packed_ip) -> ip_address_string\n\
  3402. \n\
  3403. Convert an IP address from 32-bit packed binary format to string format");
  3404. static PyObject*
  3405. socket_inet_ntoa(PyObject *self, PyObject *args)
  3406. {
  3407. char *packed_str;
  3408. int addr_len;
  3409. struct in_addr packed_addr;
  3410. if (!PyArg_ParseTuple(args, "s#:inet_ntoa", &packed_str, &addr_len)) {
  3411. return NULL;
  3412. }
  3413. if (addr_len != sizeof(packed_addr)) {
  3414. PyErr_SetString(socket_error,
  3415. "packed IP wrong length for inet_ntoa");
  3416. return NULL;
  3417. }
  3418. memcpy(&packed_addr, packed_str, addr_len);
  3419. return PyString_FromString(inet_ntoa(packed_addr));
  3420. }
  3421. #ifdef HAVE_INET_PTON
  3422. PyDoc_STRVAR(inet_pton_doc,
  3423. "inet_pton(af, ip) -> packed IP address string\n\
  3424. \n\
  3425. Convert an IP address from string format to a packed string suitable\n\
  3426. for use with low-level network functions.");
  3427. static PyObject *
  3428. socket_inet_pton(PyObject *self, PyObject *args)
  3429. {
  3430. int af;
  3431. char* ip;
  3432. int retval;
  3433. #ifdef ENABLE_IPV6
  3434. char packed[MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
  3435. #else
  3436. char packed[sizeof(struct in_addr)];
  3437. #endif
  3438. if (!PyArg_ParseTuple(args, "is:inet_pton", &af, &ip)) {
  3439. return NULL;
  3440. }
  3441. #if !defined(ENABLE_IPV6) && defined(AF_INET6)
  3442. if(af == AF_INET6) {
  3443. PyErr_SetString(socket_error,
  3444. "can't use AF_INET6, IPv6 is disabled");
  3445. return NULL;
  3446. }
  3447. #endif
  3448. retval = inet_pton(af, ip, packed);
  3449. if (retval < 0) {
  3450. PyErr_SetFromErrno(socket_error);
  3451. return NULL;
  3452. } else if (retval == 0) {
  3453. PyErr_SetString(socket_error,
  3454. "illegal IP address string passed to inet_pton");
  3455. return NULL;
  3456. } else if (af == AF_INET) {
  3457. return PyString_FromStringAndSize(packed,
  3458. sizeof(struct in_addr));
  3459. #ifdef ENABLE_IPV6
  3460. } else if (af == AF_INET6) {
  3461. return PyString_FromStringAndSize(packed,
  3462. sizeof(struct in6_addr));
  3463. #endif
  3464. } else {
  3465. PyErr_SetString(socket_error, "unknown address family");
  3466. return NULL;
  3467. }
  3468. }
  3469. PyDoc_STRVAR(inet_ntop_doc,
  3470. "inet_ntop(af, packed_ip) -> string formatted IP address\n\
  3471. \n\
  3472. Convert a packed IP address of the given family to string format.");
  3473. static PyObject *
  3474. socket_inet_ntop(PyObject *self, PyObject *args)
  3475. {
  3476. int af;
  3477. char* packed;
  3478. int len;
  3479. const char* retval;
  3480. #ifdef ENABLE_IPV6
  3481. char ip[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) + 1];
  3482. #else
  3483. char ip[INET_ADDRSTRLEN + 1];
  3484. #endif
  3485. /* Guarantee NUL-termination for PyString_FromString() below */
  3486. memset((void *) &ip[0], '\0', sizeof(ip));
  3487. if (!PyArg_ParseTuple(args, "is#:inet_ntop", &af, &packed, &len)) {
  3488. return NULL;
  3489. }
  3490. if (af == AF_INET) {
  3491. if (len != sizeof(struct in_addr)) {
  3492. PyErr_SetString(PyExc_ValueError,
  3493. "invalid length of packed IP address string");
  3494. return NULL;
  3495. }
  3496. #ifdef ENABLE_IPV6
  3497. } else if (af == AF_INET6) {
  3498. if (len != sizeof(struct in6_addr)) {
  3499. PyErr_SetString(PyExc_ValueError,
  3500. "invalid length of packed IP address string");
  3501. return NULL;
  3502. }
  3503. #endif
  3504. } else {
  3505. PyErr_Format(PyExc_ValueError,
  3506. "unknown address family %d", af);
  3507. return NULL;
  3508. }
  3509. retval = inet_ntop(af, packed, ip, sizeof(ip));
  3510. if (!retval) {
  3511. PyErr_SetFromErrno(socket_error);
  3512. return NULL;
  3513. } else {
  3514. return PyString_FromString(retval);
  3515. }
  3516. /* NOTREACHED */
  3517. PyErr_SetString(PyExc_RuntimeError, "invalid handling of inet_ntop");
  3518. return NULL;
  3519. }
  3520. #endif /* HAVE_INET_PTON */
  3521. /* Python interface to getaddrinfo(host, port). */
  3522. /*ARGSUSED*/
  3523. static PyObject *
  3524. socket_getaddrinfo(PyObject *self, PyObject *args)
  3525. {
  3526. struct addrinfo hints, *res;
  3527. struct addrinfo *res0 = NULL;
  3528. PyObject *hobj = NULL;
  3529. PyObject *pobj = (PyObject *)NULL;
  3530. char pbuf[30];
  3531. char *hptr, *pptr;
  3532. int family, socktype, protocol, flags;
  3533. int error;
  3534. PyObject *all = (PyObject *)NULL;
  3535. PyObject *single = (PyObject *)NULL;
  3536. PyObject *idna = NULL;
  3537. family = socktype = protocol = flags = 0;
  3538. family = AF_UNSPEC;
  3539. if (!PyArg_ParseTuple(args, "OO|iiii:getaddrinfo",
  3540. &hobj, &pobj, &family, &socktype,
  3541. &protocol, &flags)) {
  3542. return NULL;
  3543. }
  3544. if (hobj == Py_None) {
  3545. hptr = NULL;
  3546. } else if (PyUnicode_Check(hobj)) {
  3547. idna = PyObject_CallMethod(hobj, "encode", "s", "idna");
  3548. if (!idna)
  3549. return NULL;
  3550. hptr = PyString_AsString(idna);
  3551. } else if (PyString_Check(hobj)) {
  3552. hptr = PyString_AsString(hobj);
  3553. } else {
  3554. PyErr_SetString(PyExc_TypeError,
  3555. "getaddrinfo() argument 1 must be string or None");
  3556. return NULL;
  3557. }
  3558. if (PyInt_Check(pobj) || PyLong_Check(pobj)) {
  3559. long value = PyLong_AsLong(pobj);
  3560. if (value == -1 && PyErr_Occurred())
  3561. return NULL;
  3562. PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", value);
  3563. pptr = pbuf;
  3564. } else if (PyString_Check(pobj)) {
  3565. pptr = PyString_AsString(pobj);
  3566. } else if (pobj == Py_None) {
  3567. pptr = (char *)NULL;
  3568. } else {
  3569. PyErr_SetString(socket_error,
  3570. "getaddrinfo() argument 2 must be integer or string");
  3571. goto err;
  3572. }
  3573. memset(&hints, 0, sizeof(hints));
  3574. hints.ai_family = family;
  3575. hints.ai_socktype = socktype;
  3576. hints.ai_protocol = protocol;
  3577. hints.ai_flags = flags;
  3578. Py_BEGIN_ALLOW_THREADS
  3579. ACQUIRE_GETADDRINFO_LOCK
  3580. error = getaddrinfo(hptr, pptr, &hints, &res0);
  3581. Py_END_ALLOW_THREADS
  3582. RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
  3583. if (error) {
  3584. set_gaierror(error);
  3585. goto err;
  3586. }
  3587. if ((all = PyList_New(0)) == NULL)
  3588. goto err;
  3589. for (res = res0; res; res = res->ai_next) {
  3590. PyObject *addr =
  3591. makesockaddr(-1, res->ai_addr, res->ai_addrlen, protocol);
  3592. if (addr == NULL)
  3593. goto err;
  3594. single = Py_BuildValue("iiisO", res->ai_family,
  3595. res->ai_socktype, res->ai_protocol,
  3596. res->ai_canonname ? res->ai_canonname : "",
  3597. addr);
  3598. Py_DECREF(addr);
  3599. if (single == NULL)
  3600. goto err;
  3601. if (PyList_Append(all, single))
  3602. goto err;
  3603. Py_XDECREF(single);
  3604. }
  3605. Py_XDECREF(idna);
  3606. if (res0)
  3607. freeaddrinfo(res0);
  3608. return all;
  3609. err:
  3610. Py_XDECREF(single);
  3611. Py_XDECREF(all);
  3612. Py_XDECREF(idna);
  3613. if (res0)
  3614. freeaddrinfo(res0);
  3615. return (PyObject *)NULL;
  3616. }
  3617. PyDoc_STRVAR(getaddrinfo_doc,
  3618. "getaddrinfo(host, port [, family, socktype, proto, flags])\n\
  3619. -> list of (family, socktype, proto, canonname, sockaddr)\n\
  3620. \n\
  3621. Resolve host and port into addrinfo struct.");
  3622. /* Python interface to getnameinfo(sa, flags). */
  3623. /*ARGSUSED*/
  3624. static PyObject *
  3625. socket_getnameinfo(PyObject *self, PyObject *args)
  3626. {
  3627. PyObject *sa = (PyObject *)NULL;
  3628. int flags;
  3629. char *hostp;
  3630. int port;
  3631. unsigned int flowinfo, scope_id;
  3632. char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
  3633. struct addrinfo hints, *res = NULL;
  3634. int error;
  3635. PyObject *ret = (PyObject *)NULL;
  3636. flags = flowinfo = scope_id = 0;
  3637. if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags))
  3638. return NULL;
  3639. if (!PyTuple_Check(sa)) {
  3640. PyErr_SetString(PyExc_TypeError,
  3641. "getnameinfo() argument 1 must be a tuple");
  3642. return NULL;
  3643. }
  3644. if (!PyArg_ParseTuple(sa, "si|II",
  3645. &hostp, &port, &flowinfo, &scope_id))
  3646. return NULL;
  3647. if (flowinfo > 0xfffff) {
  3648. PyErr_SetString(PyExc_OverflowError,
  3649. "getsockaddrarg: flowinfo must be 0-1048575.");
  3650. return NULL;
  3651. }
  3652. PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port);
  3653. memset(&hints, 0, sizeof(hints));
  3654. hints.ai_family = AF_UNSPEC;
  3655. hints.ai_socktype = SOCK_DGRAM; /* make numeric port happy */
  3656. Py_BEGIN_ALLOW_THREADS
  3657. ACQUIRE_GETADDRINFO_LOCK
  3658. error = getaddrinfo(hostp, pbuf, &hints, &res);
  3659. Py_END_ALLOW_THREADS
  3660. RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
  3661. if (error) {
  3662. set_gaierror(error);
  3663. goto fail;
  3664. }
  3665. if (res->ai_next) {
  3666. PyErr_SetString(socket_error,
  3667. "sockaddr resolved to multiple addresses");
  3668. goto fail;
  3669. }
  3670. switch (res->ai_family) {
  3671. case AF_INET:
  3672. {
  3673. if (PyTuple_GET_SIZE(sa) != 2) {
  3674. PyErr_SetString(socket_error,
  3675. "IPv4 sockaddr must be 2 tuple");
  3676. goto fail;
  3677. }
  3678. break;
  3679. }
  3680. #ifdef ENABLE_IPV6
  3681. case AF_INET6:
  3682. {
  3683. struct sockaddr_in6 *sin6;
  3684. sin6 = (struct sockaddr_in6 *)res->ai_addr;
  3685. sin6->sin6_flowinfo = htonl(flowinfo);
  3686. sin6->sin6_scope_id = scope_id;
  3687. break;
  3688. }
  3689. #endif
  3690. }
  3691. error = getnameinfo(res->ai_addr, res->ai_addrlen,
  3692. hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags);
  3693. if (error) {
  3694. set_gaierror(error);
  3695. goto fail;
  3696. }
  3697. ret = Py_BuildValue("ss", hbuf, pbuf);
  3698. fail:
  3699. if (res)
  3700. freeaddrinfo(res);
  3701. return ret;
  3702. }
  3703. PyDoc_STRVAR(getnameinfo_doc,
  3704. "getnameinfo(sockaddr, flags) --> (host, port)\n\
  3705. \n\
  3706. Get host and port for a sockaddr.");
  3707. /* Python API to getting and setting the default timeout value. */
  3708. static PyObject *
  3709. socket_getdefaulttimeout(PyObject *self)
  3710. {
  3711. if (defaulttimeout < 0.0) {
  3712. Py_INCREF(Py_None);
  3713. return Py_None;
  3714. }
  3715. else
  3716. return PyFloat_FromDouble(defaulttimeout);
  3717. }
  3718. PyDoc_STRVAR(getdefaulttimeout_doc,
  3719. "getdefaulttimeout() -> timeout\n\
  3720. \n\
  3721. Returns the default timeout in seconds (float) for new socket objects.\n\
  3722. A value of None indicates that new socket objects have no timeout.\n\
  3723. When the socket module is first imported, the default is None.");
  3724. static PyObject *
  3725. socket_setdefaulttimeout(PyObject *self, PyObject *arg)
  3726. {
  3727. double timeout;
  3728. if (arg == Py_None)
  3729. timeout = -1.0;
  3730. else {
  3731. timeout = PyFloat_AsDouble(arg);
  3732. if (timeout < 0.0) {
  3733. if (!PyErr_Occurred())
  3734. PyErr_SetString(PyExc_ValueError,
  3735. "Timeout value out of range");
  3736. return NULL;
  3737. }
  3738. }
  3739. defaulttimeout = timeout;
  3740. Py_INCREF(Py_None);
  3741. return Py_None;
  3742. }
  3743. PyDoc_STRVAR(setdefaulttimeout_doc,
  3744. "setdefaulttimeout(timeout)\n\
  3745. \n\
  3746. Set the default timeout in seconds (float) for new socket objects.\n\
  3747. A value of None indicates that new socket objects have no timeout.\n\
  3748. When the socket module is first imported, the default is None.");
  3749. /* List of functions exported by this module. */
  3750. static PyMethodDef socket_methods[] = {
  3751. {"gethostbyname", socket_gethostbyname,
  3752. METH_VARARGS, gethostbyname_doc},
  3753. {"gethostbyname_ex", socket_gethostbyname_ex,
  3754. METH_VARARGS, ghbn_ex_doc},
  3755. {"gethostbyaddr", socket_gethostbyaddr,
  3756. METH_VARARGS, gethostbyaddr_doc},
  3757. {"gethostname", socket_gethostname,
  3758. METH_NOARGS, gethostname_doc},
  3759. {"getservbyname", socket_getservbyname,
  3760. METH_VARARGS, getservbyname_doc},
  3761. {"getservbyport", socket_getservbyport,
  3762. METH_VARARGS, getservbyport_doc},
  3763. {"getprotobyname", socket_getprotobyname,
  3764. METH_VARARGS, getprotobyname_doc},
  3765. #ifndef NO_DUP
  3766. {"fromfd", socket_fromfd,
  3767. METH_VARARGS, fromfd_doc},
  3768. #endif
  3769. #ifdef HAVE_SOCKETPAIR
  3770. {"socketpair", socket_socketpair,
  3771. METH_VARARGS, socketpair_doc},
  3772. #endif
  3773. {"ntohs", socket_ntohs,
  3774. METH_VARARGS, ntohs_doc},
  3775. {"ntohl", socket_ntohl,
  3776. METH_O, ntohl_doc},
  3777. {"htons", socket_htons,
  3778. METH_VARARGS, htons_doc},
  3779. {"htonl", socket_htonl,
  3780. METH_O, htonl_doc},
  3781. {"inet_aton", socket_inet_aton,
  3782. METH_VARARGS, inet_aton_doc},
  3783. {"inet_ntoa", socket_inet_ntoa,
  3784. METH_VARARGS, inet_ntoa_doc},
  3785. #ifdef HAVE_INET_PTON
  3786. {"inet_pton", socket_inet_pton,
  3787. METH_VARARGS, inet_pton_doc},
  3788. {"inet_ntop", socket_inet_ntop,
  3789. METH_VARARGS, inet_ntop_doc},
  3790. #endif
  3791. {"getaddrinfo", socket_getaddrinfo,
  3792. METH_VARARGS, getaddrinfo_doc},
  3793. {"getnameinfo", socket_getnameinfo,
  3794. METH_VARARGS, getnameinfo_doc},
  3795. {"getdefaulttimeout", (PyCFunction)socket_getdefaulttimeout,
  3796. METH_NOARGS, getdefaulttimeout_doc},
  3797. {"setdefaulttimeout", socket_setdefaulttimeout,
  3798. METH_O, setdefaulttimeout_doc},
  3799. {NULL, NULL} /* Sentinel */
  3800. };
  3801. #ifdef RISCOS
  3802. #define OS_INIT_DEFINED
  3803. static int
  3804. os_init(void)
  3805. {
  3806. _kernel_swi_regs r;
  3807. r.r[0] = 0;
  3808. _kernel_swi(0x43380, &r, &r);
  3809. taskwindow = r.r[0];
  3810. return 1;
  3811. }
  3812. #endif /* RISCOS */
  3813. #ifdef MS_WINDOWS
  3814. #define OS_INIT_DEFINED
  3815. /* Additional initialization and cleanup for Windows */
  3816. static void
  3817. os_cleanup(void)
  3818. {
  3819. WSACleanup();
  3820. }
  3821. static int
  3822. os_init(void)
  3823. {
  3824. WSADATA WSAData;
  3825. int ret;
  3826. char buf[100];
  3827. ret = WSAStartup(0x0101, &WSAData);
  3828. switch (ret) {
  3829. case 0: /* No error */
  3830. Py_AtExit(os_cleanup);
  3831. return 1; /* Success */
  3832. case WSASYSNOTREADY:
  3833. PyErr_SetString(PyExc_ImportError,
  3834. "WSAStartup failed: network not ready");
  3835. break;
  3836. case WSAVERNOTSUPPORTED:
  3837. case WSAEINVAL:
  3838. PyErr_SetString(
  3839. PyExc_ImportError,
  3840. "WSAStartup failed: requested version not supported");
  3841. break;
  3842. default:
  3843. PyOS_snprintf(buf, sizeof(buf),
  3844. "WSAStartup failed: error code %d", ret);
  3845. PyErr_SetString(PyExc_ImportError, buf);
  3846. break;
  3847. }
  3848. return 0; /* Failure */
  3849. }
  3850. #endif /* MS_WINDOWS */
  3851. #ifdef PYOS_OS2
  3852. #define OS_INIT_DEFINED
  3853. /* Additional initialization for OS/2 */
  3854. static int
  3855. os_init(void)
  3856. {
  3857. #ifndef PYCC_GCC
  3858. char reason[64];
  3859. int rc = sock_init();
  3860. if (rc == 0) {
  3861. return 1; /* Success */
  3862. }
  3863. PyOS_snprintf(reason, sizeof(reason),
  3864. "OS/2 TCP/IP Error# %d", sock_errno());
  3865. PyErr_SetString(PyExc_ImportError, reason);
  3866. return 0; /* Failure */
  3867. #else
  3868. /* No need to initialize sockets with GCC/EMX */
  3869. return 1; /* Success */
  3870. #endif
  3871. }
  3872. #endif /* PYOS_OS2 */
  3873. #ifndef OS_INIT_DEFINED
  3874. static int
  3875. os_init(void)
  3876. {
  3877. return 1; /* Success */
  3878. }
  3879. #endif
  3880. /* C API table - always add new things to the end for binary
  3881. compatibility. */
  3882. static
  3883. PySocketModule_APIObject PySocketModuleAPI =
  3884. {
  3885. &sock_type,
  3886. NULL
  3887. };
  3888. /* Initialize the _socket module.
  3889. This module is actually called "_socket", and there's a wrapper
  3890. "socket.py" which implements some additional functionality. On some
  3891. platforms (e.g. Windows and OS/2), socket.py also implements a
  3892. wrapper for the socket type that provides missing functionality such
  3893. as makefile(), dup() and fromfd(). The import of "_socket" may fail
  3894. with an ImportError exception if os-specific initialization fails.
  3895. On Windows, this does WINSOCK initialization. When WINSOCK is
  3896. initialized successfully, a call to WSACleanup() is scheduled to be
  3897. made at exit time.
  3898. */
  3899. PyDoc_STRVAR(socket_doc,
  3900. "Implementation module for socket operations.\n\
  3901. \n\
  3902. See the socket module for documentation.");
  3903. PyMODINIT_FUNC
  3904. init_socket(void)
  3905. {
  3906. PyObject *m, *has_ipv6;
  3907. if (!os_init())
  3908. return;
  3909. Py_TYPE(&sock_type) = &PyType_Type;
  3910. m = Py_InitModule3(PySocket_MODULE_NAME,
  3911. socket_methods,
  3912. socket_doc);
  3913. if (m == NULL)
  3914. return;
  3915. socket_error = PyErr_NewException("socket.error",
  3916. PyExc_IOError, NULL);
  3917. if (socket_error == NULL)
  3918. return;
  3919. PySocketModuleAPI.error = socket_error;
  3920. Py_INCREF(socket_error);
  3921. PyModule_AddObject(m, "error", socket_error);
  3922. socket_herror = PyErr_NewException("socket.herror",
  3923. socket_error, NULL);
  3924. if (socket_herror == NULL)
  3925. return;
  3926. Py_INCREF(socket_herror);
  3927. PyModule_AddObject(m, "herror", socket_herror);
  3928. socket_gaierror = PyErr_NewException("socket.gaierror", socket_error,
  3929. NULL);
  3930. if (socket_gaierror == NULL)
  3931. return;
  3932. Py_INCREF(socket_gaierror);
  3933. PyModule_AddObject(m, "gaierror", socket_gaierror);
  3934. socket_timeout = PyErr_NewException("socket.timeout",
  3935. socket_error, NULL);
  3936. if (socket_timeout == NULL)
  3937. return;
  3938. Py_INCREF(socket_timeout);
  3939. PyModule_AddObject(m, "timeout", socket_timeout);
  3940. Py_INCREF((PyObject *)&sock_type);
  3941. if (PyModule_AddObject(m, "SocketType",
  3942. (PyObject *)&sock_type) != 0)
  3943. return;
  3944. Py_INCREF((PyObject *)&sock_type);
  3945. if (PyModule_AddObject(m, "socket",
  3946. (PyObject *)&sock_type) != 0)
  3947. return;
  3948. #ifdef ENABLE_IPV6
  3949. has_ipv6 = Py_True;
  3950. #else
  3951. has_ipv6 = Py_False;
  3952. #endif
  3953. Py_INCREF(has_ipv6);
  3954. PyModule_AddObject(m, "has_ipv6", has_ipv6);
  3955. /* Export C API */
  3956. if (PyModule_AddObject(m, PySocket_CAPI_NAME,
  3957. PyCapsule_New(&PySocketModuleAPI, PySocket_CAPSULE_NAME, NULL)
  3958. ) != 0)
  3959. return;
  3960. /* Address families (we only support AF_INET and AF_UNIX) */
  3961. #ifdef AF_UNSPEC
  3962. PyModule_AddIntConstant(m, "AF_UNSPEC", AF_UNSPEC);
  3963. #endif
  3964. PyModule_AddIntConstant(m, "AF_INET", AF_INET);
  3965. #ifdef AF_INET6
  3966. PyModule_AddIntConstant(m, "AF_INET6", AF_INET6);
  3967. #endif /* AF_INET6 */
  3968. #if defined(AF_UNIX)
  3969. PyModule_AddIntConstant(m, "AF_UNIX", AF_UNIX);
  3970. #endif /* AF_UNIX */
  3971. #ifdef AF_AX25
  3972. /* Amateur Radio AX.25 */
  3973. PyModule_AddIntConstant(m, "AF_AX25", AF_AX25);
  3974. #endif
  3975. #ifdef AF_IPX
  3976. PyModule_AddIntConstant(m, "AF_IPX", AF_IPX); /* Novell IPX */
  3977. #endif
  3978. #ifdef AF_APPLETALK
  3979. /* Appletalk DDP */
  3980. PyModule_AddIntConstant(m, "AF_APPLETALK", AF_APPLETALK);
  3981. #endif
  3982. #ifdef AF_NETROM
  3983. /* Amateur radio NetROM */
  3984. PyModule_AddIntConstant(m, "AF_NETROM", AF_NETROM);
  3985. #endif
  3986. #ifdef AF_BRIDGE
  3987. /* Multiprotocol bridge */
  3988. PyModule_AddIntConstant(m, "AF_BRIDGE", AF_BRIDGE);
  3989. #endif
  3990. #ifdef AF_ATMPVC
  3991. /* ATM PVCs */
  3992. PyModule_AddIntConstant(m, "AF_ATMPVC", AF_ATMPVC);
  3993. #endif
  3994. #ifdef AF_AAL5
  3995. /* Reserved for Werner's ATM */
  3996. PyModule_AddIntConstant(m, "AF_AAL5", AF_AAL5);
  3997. #endif
  3998. #ifdef AF_X25
  3999. /* Reserved for X.25 project */
  4000. PyModule_AddIntConstant(m, "AF_X25", AF_X25);
  4001. #endif
  4002. #ifdef AF_INET6
  4003. PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); /* IP version 6 */
  4004. #endif
  4005. #ifdef AF_ROSE
  4006. /* Amateur Radio X.25 PLP */
  4007. PyModule_AddIntConstant(m, "AF_ROSE", AF_ROSE);
  4008. #endif
  4009. #ifdef AF_DECnet
  4010. /* Reserved for DECnet project */
  4011. PyModule_AddIntConstant(m, "AF_DECnet", AF_DECnet);
  4012. #endif
  4013. #ifdef AF_NETBEUI
  4014. /* Reserved for 802.2LLC project */
  4015. PyModule_AddIntConstant(m, "AF_NETBEUI", AF_NETBEUI);
  4016. #endif
  4017. #ifdef AF_SECURITY
  4018. /* Security callback pseudo AF */
  4019. PyModule_AddIntConstant(m, "AF_SECURITY", AF_SECURITY);
  4020. #endif
  4021. #ifdef AF_KEY
  4022. /* PF_KEY key management API */
  4023. PyModule_AddIntConstant(m, "AF_KEY", AF_KEY);
  4024. #endif
  4025. #ifdef AF_NETLINK
  4026. /* */
  4027. PyModule_AddIntConstant(m, "AF_NETLINK", AF_NETLINK);
  4028. PyModule_AddIntConstant(m, "NETLINK_ROUTE", NETLINK_ROUTE);
  4029. #ifdef NETLINK_SKIP
  4030. PyModule_AddIntConstant(m, "NETLINK_SKIP", NETLINK_SKIP);
  4031. #endif
  4032. #ifdef NETLINK_W1
  4033. PyModule_AddIntConstant(m, "NETLINK_W1", NETLINK_W1);
  4034. #endif
  4035. PyModule_AddIntConstant(m, "NETLINK_USERSOCK", NETLINK_USERSOCK);
  4036. PyModule_AddIntConstant(m, "NETLINK_FIREWALL", NETLINK_FIREWALL);
  4037. #ifdef NETLINK_TCPDIAG
  4038. PyModule_AddIntConstant(m, "NETLINK_TCPDIAG", NETLINK_TCPDIAG);
  4039. #endif
  4040. #ifdef NETLINK_NFLOG
  4041. PyModule_AddIntConstant(m, "NETLINK_NFLOG", NETLINK_NFLOG);
  4042. #endif
  4043. #ifdef NETLINK_XFRM
  4044. PyModule_AddIntConstant(m, "NETLINK_XFRM", NETLINK_XFRM);
  4045. #endif
  4046. #ifdef NETLINK_ARPD
  4047. PyModule_AddIntConstant(m, "NETLINK_ARPD", NETLINK_ARPD);
  4048. #endif
  4049. #ifdef NETLINK_ROUTE6
  4050. PyModule_AddIntConstant(m, "NETLINK_ROUTE6", NETLINK_ROUTE6);
  4051. #endif
  4052. PyModule_AddIntConstant(m, "NETLINK_IP6_FW", NETLINK_IP6_FW);
  4053. #ifdef NETLINK_DNRTMSG
  4054. PyModule_AddIntConstant(m, "NETLINK_DNRTMSG", NETLINK_DNRTMSG);
  4055. #endif
  4056. #ifdef NETLINK_TAPBASE
  4057. PyModule_AddIntConstant(m, "NETLINK_TAPBASE", NETLINK_TAPBASE);
  4058. #endif
  4059. #endif /* AF_NETLINK */
  4060. #ifdef AF_ROUTE
  4061. /* Alias to emulate 4.4BSD */
  4062. PyModule_AddIntConstant(m, "AF_ROUTE", AF_ROUTE);
  4063. #endif
  4064. #ifdef AF_ASH
  4065. /* Ash */
  4066. PyModule_AddIntConstant(m, "AF_ASH", AF_ASH);
  4067. #endif
  4068. #ifdef AF_ECONET
  4069. /* Acorn Econet */
  4070. PyModule_AddIntConstant(m, "AF_ECONET", AF_ECONET);
  4071. #endif
  4072. #ifdef AF_ATMSVC
  4073. /* ATM SVCs */
  4074. PyModule_AddIntConstant(m, "AF_ATMSVC", AF_ATMSVC);
  4075. #endif
  4076. #ifdef AF_SNA
  4077. /* Linux SNA Project (nutters!) */
  4078. PyModule_AddIntConstant(m, "AF_SNA", AF_SNA);
  4079. #endif
  4080. #ifdef AF_IRDA
  4081. /* IRDA sockets */
  4082. PyModule_AddIntConstant(m, "AF_IRDA", AF_IRDA);
  4083. #endif
  4084. #ifdef AF_PPPOX
  4085. /* PPPoX sockets */
  4086. PyModule_AddIntConstant(m, "AF_PPPOX", AF_PPPOX);
  4087. #endif
  4088. #ifdef AF_WANPIPE
  4089. /* Wanpipe API Sockets */
  4090. PyModule_AddIntConstant(m, "AF_WANPIPE", AF_WANPIPE);
  4091. #endif
  4092. #ifdef AF_LLC
  4093. /* Linux LLC */
  4094. PyModule_AddIntConstant(m, "AF_LLC", AF_LLC);
  4095. #endif
  4096. #ifdef USE_BLUETOOTH
  4097. PyModule_AddIntConstant(m, "AF_BLUETOOTH", AF_BLUETOOTH);
  4098. PyModule_AddIntConstant(m, "BTPROTO_L2CAP", BTPROTO_L2CAP);
  4099. PyModule_AddIntConstant(m, "BTPROTO_HCI", BTPROTO_HCI);
  4100. PyModule_AddIntConstant(m, "SOL_HCI", SOL_HCI);
  4101. #if !defined(__NetBSD__) && !defined(__DragonFly__)
  4102. PyModule_AddIntConstant(m, "HCI_FILTER", HCI_FILTER);
  4103. #endif
  4104. #if !defined(__FreeBSD__)
  4105. #if !defined(__NetBSD__) && !defined(__DragonFly__)
  4106. PyModule_AddIntConstant(m, "HCI_TIME_STAMP", HCI_TIME_STAMP);
  4107. #endif
  4108. PyModule_AddIntConstant(m, "HCI_DATA_DIR", HCI_DATA_DIR);
  4109. PyModule_AddIntConstant(m, "BTPROTO_SCO", BTPROTO_SCO);
  4110. #endif
  4111. PyModule_AddIntConstant(m, "BTPROTO_RFCOMM", BTPROTO_RFCOMM);
  4112. PyModule_AddStringConstant(m, "BDADDR_ANY", "00:00:00:00:00:00");
  4113. PyModule_AddStringConstant(m, "BDADDR_LOCAL", "00:00:00:FF:FF:FF");
  4114. #endif
  4115. #ifdef AF_PACKET
  4116. PyModule_AddIntMacro(m, AF_PACKET);
  4117. #endif
  4118. #ifdef PF_PACKET
  4119. PyModule_AddIntMacro(m, PF_PACKET);
  4120. #endif
  4121. #ifdef PACKET_HOST
  4122. PyModule_AddIntMacro(m, PACKET_HOST);
  4123. #endif
  4124. #ifdef PACKET_BROADCAST
  4125. PyModule_AddIntMacro(m, PACKET_BROADCAST);
  4126. #endif
  4127. #ifdef PACKET_MULTICAST
  4128. PyModule_AddIntMacro(m, PACKET_MULTICAST);
  4129. #endif
  4130. #ifdef PACKET_OTHERHOST
  4131. PyModule_AddIntMacro(m, PACKET_OTHERHOST);
  4132. #endif
  4133. #ifdef PACKET_OUTGOING
  4134. PyModule_AddIntMacro(m, PACKET_OUTGOING);
  4135. #endif
  4136. #ifdef PACKET_LOOPBACK
  4137. PyModule_AddIntMacro(m, PACKET_LOOPBACK);
  4138. #endif
  4139. #ifdef PACKET_FASTROUTE
  4140. PyModule_AddIntMacro(m, PACKET_FASTROUTE);
  4141. #endif
  4142. #ifdef HAVE_LINUX_TIPC_H
  4143. PyModule_AddIntConstant(m, "AF_TIPC", AF_TIPC);
  4144. /* for addresses */
  4145. PyModule_AddIntConstant(m, "TIPC_ADDR_NAMESEQ", TIPC_ADDR_NAMESEQ);
  4146. PyModule_AddIntConstant(m, "TIPC_ADDR_NAME", TIPC_ADDR_NAME);
  4147. PyModule_AddIntConstant(m, "TIPC_ADDR_ID", TIPC_ADDR_ID);
  4148. PyModule_AddIntConstant(m, "TIPC_ZONE_SCOPE", TIPC_ZONE_SCOPE);
  4149. PyModule_AddIntConstant(m, "TIPC_CLUSTER_SCOPE", TIPC_CLUSTER_SCOPE);
  4150. PyModule_AddIntConstant(m, "TIPC_NODE_SCOPE", TIPC_NODE_SCOPE);
  4151. /* for setsockopt() */
  4152. PyModule_AddIntConstant(m, "SOL_TIPC", SOL_TIPC);
  4153. PyModule_AddIntConstant(m, "TIPC_IMPORTANCE", TIPC_IMPORTANCE);
  4154. PyModule_AddIntConstant(m, "TIPC_SRC_DROPPABLE", TIPC_SRC_DROPPABLE);
  4155. PyModule_AddIntConstant(m, "TIPC_DEST_DROPPABLE",
  4156. TIPC_DEST_DROPPABLE);
  4157. PyModule_AddIntConstant(m, "TIPC_CONN_TIMEOUT", TIPC_CONN_TIMEOUT);
  4158. PyModule_AddIntConstant(m, "TIPC_LOW_IMPORTANCE",
  4159. TIPC_LOW_IMPORTANCE);
  4160. PyModule_AddIntConstant(m, "TIPC_MEDIUM_IMPORTANCE",
  4161. TIPC_MEDIUM_IMPORTANCE);
  4162. PyModule_AddIntConstant(m, "TIPC_HIGH_IMPORTANCE",
  4163. TIPC_HIGH_IMPORTANCE);
  4164. PyModule_AddIntConstant(m, "TIPC_CRITICAL_IMPORTANCE",
  4165. TIPC_CRITICAL_IMPORTANCE);
  4166. /* for subscriptions */
  4167. PyModule_AddIntConstant(m, "TIPC_SUB_PORTS", TIPC_SUB_PORTS);
  4168. PyModule_AddIntConstant(m, "TIPC_SUB_SERVICE", TIPC_SUB_SERVICE);
  4169. #ifdef TIPC_SUB_CANCEL
  4170. /* doesn't seem to be available everywhere */
  4171. PyModule_AddIntConstant(m, "TIPC_SUB_CANCEL", TIPC_SUB_CANCEL);
  4172. #endif
  4173. PyModule_AddIntConstant(m, "TIPC_WAIT_FOREVER", TIPC_WAIT_FOREVER);
  4174. PyModule_AddIntConstant(m, "TIPC_PUBLISHED", TIPC_PUBLISHED);
  4175. PyModule_AddIntConstant(m, "TIPC_WITHDRAWN", TIPC_WITHDRAWN);
  4176. PyModule_AddIntConstant(m, "TIPC_SUBSCR_TIMEOUT", TIPC_SUBSCR_TIMEOUT);
  4177. PyModule_AddIntConstant(m, "TIPC_CFG_SRV", TIPC_CFG_SRV);
  4178. PyModule_AddIntConstant(m, "TIPC_TOP_SRV", TIPC_TOP_SRV);
  4179. #endif
  4180. /* Socket types */
  4181. PyModule_AddIntConstant(m, "SOCK_STREAM", SOCK_STREAM);
  4182. PyModule_AddIntConstant(m, "SOCK_DGRAM", SOCK_DGRAM);
  4183. #ifndef __BEOS__
  4184. /* We have incomplete socket support. */
  4185. PyModule_AddIntConstant(m, "SOCK_RAW", SOCK_RAW);
  4186. PyModule_AddIntConstant(m, "SOCK_SEQPACKET", SOCK_SEQPACKET);
  4187. #if defined(SOCK_RDM)
  4188. PyModule_AddIntConstant(m, "SOCK_RDM", SOCK_RDM);
  4189. #endif
  4190. #endif
  4191. #ifdef SO_DEBUG
  4192. PyModule_AddIntConstant(m, "SO_DEBUG", SO_DEBUG);
  4193. #endif
  4194. #ifdef SO_ACCEPTCONN
  4195. PyModule_AddIntConstant(m, "SO_ACCEPTCONN", SO_ACCEPTCONN);
  4196. #endif
  4197. #ifdef SO_REUSEADDR
  4198. PyModule_AddIntConstant(m, "SO_REUSEADDR", SO_REUSEADDR);
  4199. #endif
  4200. #ifdef SO_EXCLUSIVEADDRUSE
  4201. PyModule_AddIntConstant(m, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE);
  4202. #endif
  4203. #ifdef SO_KEEPALIVE
  4204. PyModule_AddIntConstant(m, "SO_KEEPALIVE", SO_KEEPALIVE);
  4205. #endif
  4206. #ifdef SO_DONTROUTE
  4207. PyModule_AddIntConstant(m, "SO_DONTROUTE", SO_DONTROUTE);
  4208. #endif
  4209. #ifdef SO_BROADCAST
  4210. PyModule_AddIntConstant(m, "SO_BROADCAST", SO_BROADCAST);
  4211. #endif
  4212. #ifdef SO_USELOOPBACK
  4213. PyModule_AddIntConstant(m, "SO_USELOOPBACK", SO_USELOOPBACK);
  4214. #endif
  4215. #ifdef SO_LINGER
  4216. PyModule_AddIntConstant(m, "SO_LINGER", SO_LINGER);
  4217. #endif
  4218. #ifdef SO_OOBINLINE
  4219. PyModule_AddIntConstant(m, "SO_OOBINLINE", SO_OOBINLINE);
  4220. #endif
  4221. #ifdef SO_REUSEPORT
  4222. PyModule_AddIntConstant(m, "SO_REUSEPORT", SO_REUSEPORT);
  4223. #endif
  4224. #ifdef SO_SNDBUF
  4225. PyModule_AddIntConstant(m, "SO_SNDBUF", SO_SNDBUF);
  4226. #endif
  4227. #ifdef SO_RCVBUF
  4228. PyModule_AddIntConstant(m, "SO_RCVBUF", SO_RCVBUF);
  4229. #endif
  4230. #ifdef SO_SNDLOWAT
  4231. PyModule_AddIntConstant(m, "SO_SNDLOWAT", SO_SNDLOWAT);
  4232. #endif
  4233. #ifdef SO_RCVLOWAT
  4234. PyModule_AddIntConstant(m, "SO_RCVLOWAT", SO_RCVLOWAT);
  4235. #endif
  4236. #ifdef SO_SNDTIMEO
  4237. PyModule_AddIntConstant(m, "SO_SNDTIMEO", SO_SNDTIMEO);
  4238. #endif
  4239. #ifdef SO_RCVTIMEO
  4240. PyModule_AddIntConstant(m, "SO_RCVTIMEO", SO_RCVTIMEO);
  4241. #endif
  4242. #ifdef SO_ERROR
  4243. PyModule_AddIntConstant(m, "SO_ERROR", SO_ERROR);
  4244. #endif
  4245. #ifdef SO_TYPE
  4246. PyModule_AddIntConstant(m, "SO_TYPE", SO_TYPE);
  4247. #endif
  4248. #ifdef SO_SETFIB
  4249. PyModule_AddIntConstant(m, "SO_SETFIB", SO_SETFIB);
  4250. #endif
  4251. /* Maximum number of connections for "listen" */
  4252. #ifdef SOMAXCONN
  4253. PyModule_AddIntConstant(m, "SOMAXCONN", SOMAXCONN);
  4254. #else
  4255. PyModule_AddIntConstant(m, "SOMAXCONN", 5); /* Common value */
  4256. #endif
  4257. /* Flags for send, recv */
  4258. #ifdef MSG_OOB
  4259. PyModule_AddIntConstant(m, "MSG_OOB", MSG_OOB);
  4260. #endif
  4261. #ifdef MSG_PEEK
  4262. PyModule_AddIntConstant(m, "MSG_PEEK", MSG_PEEK);
  4263. #endif
  4264. #ifdef MSG_DONTROUTE
  4265. PyModule_AddIntConstant(m, "MSG_DONTROUTE", MSG_DONTROUTE);
  4266. #endif
  4267. #ifdef MSG_DONTWAIT
  4268. PyModule_AddIntConstant(m, "MSG_DONTWAIT", MSG_DONTWAIT);
  4269. #endif
  4270. #ifdef MSG_EOR
  4271. PyModule_AddIntConstant(m, "MSG_EOR", MSG_EOR);
  4272. #endif
  4273. #ifdef MSG_TRUNC
  4274. PyModule_AddIntConstant(m, "MSG_TRUNC", MSG_TRUNC);
  4275. #endif
  4276. #ifdef MSG_CTRUNC
  4277. PyModule_AddIntConstant(m, "MSG_CTRUNC", MSG_CTRUNC);
  4278. #endif
  4279. #ifdef MSG_WAITALL
  4280. PyModule_AddIntConstant(m, "MSG_WAITALL", MSG_WAITALL);
  4281. #endif
  4282. #ifdef MSG_BTAG
  4283. PyModule_AddIntConstant(m, "MSG_BTAG", MSG_BTAG);
  4284. #endif
  4285. #ifdef MSG_ETAG
  4286. PyModule_AddIntConstant(m, "MSG_ETAG", MSG_ETAG);
  4287. #endif
  4288. /* Protocol level and numbers, usable for [gs]etsockopt */
  4289. #ifdef SOL_SOCKET
  4290. PyModule_AddIntConstant(m, "SOL_SOCKET", SOL_SOCKET);
  4291. #endif
  4292. #ifdef SOL_IP
  4293. PyModule_AddIntConstant(m, "SOL_IP", SOL_IP);
  4294. #else
  4295. PyModule_AddIntConstant(m, "SOL_IP", 0);
  4296. #endif
  4297. #ifdef SOL_IPX
  4298. PyModule_AddIntConstant(m, "SOL_IPX", SOL_IPX);
  4299. #endif
  4300. #ifdef SOL_AX25
  4301. PyModule_AddIntConstant(m, "SOL_AX25", SOL_AX25);
  4302. #endif
  4303. #ifdef SOL_ATALK
  4304. PyModule_AddIntConstant(m, "SOL_ATALK", SOL_ATALK);
  4305. #endif
  4306. #ifdef SOL_NETROM
  4307. PyModule_AddIntConstant(m, "SOL_NETROM", SOL_NETROM);
  4308. #endif
  4309. #ifdef SOL_ROSE
  4310. PyModule_AddIntConstant(m, "SOL_ROSE", SOL_ROSE);
  4311. #endif
  4312. #ifdef SOL_TCP
  4313. PyModule_AddIntConstant(m, "SOL_TCP", SOL_TCP);
  4314. #else
  4315. PyModule_AddIntConstant(m, "SOL_TCP", 6);
  4316. #endif
  4317. #ifdef SOL_UDP
  4318. PyModule_AddIntConstant(m, "SOL_UDP", SOL_UDP);
  4319. #else
  4320. PyModule_AddIntConstant(m, "SOL_UDP", 17);
  4321. #endif
  4322. #ifdef IPPROTO_IP
  4323. PyModule_AddIntConstant(m, "IPPROTO_IP", IPPROTO_IP);
  4324. #else
  4325. PyModule_AddIntConstant(m, "IPPROTO_IP", 0);
  4326. #endif
  4327. #ifdef IPPROTO_HOPOPTS
  4328. PyModule_AddIntConstant(m, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS);
  4329. #endif
  4330. #ifdef IPPROTO_ICMP
  4331. PyModule_AddIntConstant(m, "IPPROTO_ICMP", IPPROTO_ICMP);
  4332. #else
  4333. PyModule_AddIntConstant(m, "IPPROTO_ICMP", 1);
  4334. #endif
  4335. #ifdef IPPROTO_IGMP
  4336. PyModule_AddIntConstant(m, "IPPROTO_IGMP", IPPROTO_IGMP);
  4337. #endif
  4338. #ifdef IPPROTO_GGP
  4339. PyModule_AddIntConstant(m, "IPPROTO_GGP", IPPROTO_GGP);
  4340. #endif
  4341. #ifdef IPPROTO_IPV4
  4342. PyModule_AddIntConstant(m, "IPPROTO_IPV4", IPPROTO_IPV4);
  4343. #endif
  4344. #ifdef IPPROTO_IPV6
  4345. PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
  4346. #endif
  4347. #ifdef IPPROTO_IPIP
  4348. PyModule_AddIntConstant(m, "IPPROTO_IPIP", IPPROTO_IPIP);
  4349. #endif
  4350. #ifdef IPPROTO_TCP
  4351. PyModule_AddIntConstant(m, "IPPROTO_TCP", IPPROTO_TCP);
  4352. #else
  4353. PyModule_AddIntConstant(m, "IPPROTO_TCP", 6);
  4354. #endif
  4355. #ifdef IPPROTO_EGP
  4356. PyModule_AddIntConstant(m, "IPPROTO_EGP", IPPROTO_EGP);
  4357. #endif
  4358. #ifdef IPPROTO_PUP
  4359. PyModule_AddIntConstant(m, "IPPROTO_PUP", IPPROTO_PUP);
  4360. #endif
  4361. #ifdef IPPROTO_UDP
  4362. PyModule_AddIntConstant(m, "IPPROTO_UDP", IPPROTO_UDP);
  4363. #else
  4364. PyModule_AddIntConstant(m, "IPPROTO_UDP", 17);
  4365. #endif
  4366. #ifdef IPPROTO_IDP
  4367. PyModule_AddIntConstant(m, "IPPROTO_IDP", IPPROTO_IDP);
  4368. #endif
  4369. #ifdef IPPROTO_HELLO
  4370. PyModule_AddIntConstant(m, "IPPROTO_HELLO", IPPROTO_HELLO);
  4371. #endif
  4372. #ifdef IPPROTO_ND
  4373. PyModule_AddIntConstant(m, "IPPROTO_ND", IPPROTO_ND);
  4374. #endif
  4375. #ifdef IPPROTO_TP
  4376. PyModule_AddIntConstant(m, "IPPROTO_TP", IPPROTO_TP);
  4377. #endif
  4378. #ifdef IPPROTO_IPV6
  4379. PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
  4380. #endif
  4381. #ifdef IPPROTO_ROUTING
  4382. PyModule_AddIntConstant(m, "IPPROTO_ROUTING", IPPROTO_ROUTING);
  4383. #endif
  4384. #ifdef IPPROTO_FRAGMENT
  4385. PyModule_AddIntConstant(m, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT);
  4386. #endif
  4387. #ifdef IPPROTO_RSVP
  4388. PyModule_AddIntConstant(m, "IPPROTO_RSVP", IPPROTO_RSVP);
  4389. #endif
  4390. #ifdef IPPROTO_GRE
  4391. PyModule_AddIntConstant(m, "IPPROTO_GRE", IPPROTO_GRE);
  4392. #endif
  4393. #ifdef IPPROTO_ESP
  4394. PyModule_AddIntConstant(m, "IPPROTO_ESP", IPPROTO_ESP);
  4395. #endif
  4396. #ifdef IPPROTO_AH
  4397. PyModule_AddIntConstant(m, "IPPROTO_AH", IPPROTO_AH);
  4398. #endif
  4399. #ifdef IPPROTO_MOBILE
  4400. PyModule_AddIntConstant(m, "IPPROTO_MOBILE", IPPROTO_MOBILE);
  4401. #endif
  4402. #ifdef IPPROTO_ICMPV6
  4403. PyModule_AddIntConstant(m, "IPPROTO_ICMPV6", IPPROTO_ICMPV6);
  4404. #endif
  4405. #ifdef IPPROTO_NONE
  4406. PyModule_AddIntConstant(m, "IPPROTO_NONE", IPPROTO_NONE);
  4407. #endif
  4408. #ifdef IPPROTO_DSTOPTS
  4409. PyModule_AddIntConstant(m, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS);
  4410. #endif
  4411. #ifdef IPPROTO_XTP
  4412. PyModule_AddIntConstant(m, "IPPROTO_XTP", IPPROTO_XTP);
  4413. #endif
  4414. #ifdef IPPROTO_EON
  4415. PyModule_AddIntConstant(m, "IPPROTO_EON", IPPROTO_EON);
  4416. #endif
  4417. #ifdef IPPROTO_PIM
  4418. PyModule_AddIntConstant(m, "IPPROTO_PIM", IPPROTO_PIM);
  4419. #endif
  4420. #ifdef IPPROTO_IPCOMP
  4421. PyModule_AddIntConstant(m, "IPPROTO_IPCOMP", IPPROTO_IPCOMP);
  4422. #endif
  4423. #ifdef IPPROTO_VRRP
  4424. PyModule_AddIntConstant(m, "IPPROTO_VRRP", IPPROTO_VRRP);
  4425. #endif
  4426. #ifdef IPPROTO_BIP
  4427. PyModule_AddIntConstant(m, "IPPROTO_BIP", IPPROTO_BIP);
  4428. #endif
  4429. /**/
  4430. #ifdef IPPROTO_RAW
  4431. PyModule_AddIntConstant(m, "IPPROTO_RAW", IPPROTO_RAW);
  4432. #else
  4433. PyModule_AddIntConstant(m, "IPPROTO_RAW", 255);
  4434. #endif
  4435. #ifdef IPPROTO_MAX
  4436. PyModule_AddIntConstant(m, "IPPROTO_MAX", IPPROTO_MAX);
  4437. #endif
  4438. /* Some port configuration */
  4439. #ifdef IPPORT_RESERVED
  4440. PyModule_AddIntConstant(m, "IPPORT_RESERVED", IPPORT_RESERVED);
  4441. #else
  4442. PyModule_AddIntConstant(m, "IPPORT_RESERVED", 1024);
  4443. #endif
  4444. #ifdef IPPORT_USERRESERVED
  4445. PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", IPPORT_USERRESERVED);
  4446. #else
  4447. PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", 5000);
  4448. #endif
  4449. /* Some reserved IP v.4 addresses */
  4450. #ifdef INADDR_ANY
  4451. PyModule_AddIntConstant(m, "INADDR_ANY", INADDR_ANY);
  4452. #else
  4453. PyModule_AddIntConstant(m, "INADDR_ANY", 0x00000000);
  4454. #endif
  4455. #ifdef INADDR_BROADCAST
  4456. PyModule_AddIntConstant(m, "INADDR_BROADCAST", INADDR_BROADCAST);
  4457. #else
  4458. PyModule_AddIntConstant(m, "INADDR_BROADCAST", 0xffffffff);
  4459. #endif
  4460. #ifdef INADDR_LOOPBACK
  4461. PyModule_AddIntConstant(m, "INADDR_LOOPBACK", INADDR_LOOPBACK);
  4462. #else
  4463. PyModule_AddIntConstant(m, "INADDR_LOOPBACK", 0x7F000001);
  4464. #endif
  4465. #ifdef INADDR_UNSPEC_GROUP
  4466. PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
  4467. #else
  4468. PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", 0xe0000000);
  4469. #endif
  4470. #ifdef INADDR_ALLHOSTS_GROUP
  4471. PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP",
  4472. INADDR_ALLHOSTS_GROUP);
  4473. #else
  4474. PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
  4475. #endif
  4476. #ifdef INADDR_MAX_LOCAL_GROUP
  4477. PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP",
  4478. INADDR_MAX_LOCAL_GROUP);
  4479. #else
  4480. PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
  4481. #endif
  4482. #ifdef INADDR_NONE
  4483. PyModule_AddIntConstant(m, "INADDR_NONE", INADDR_NONE);
  4484. #else
  4485. PyModule_AddIntConstant(m, "INADDR_NONE", 0xffffffff);
  4486. #endif
  4487. /* IPv4 [gs]etsockopt options */
  4488. #ifdef IP_OPTIONS
  4489. PyModule_AddIntConstant(m, "IP_OPTIONS", IP_OPTIONS);
  4490. #endif
  4491. #ifdef IP_HDRINCL
  4492. PyModule_AddIntConstant(m, "IP_HDRINCL", IP_HDRINCL);
  4493. #endif
  4494. #ifdef IP_TOS
  4495. PyModule_AddIntConstant(m, "IP_TOS", IP_TOS);
  4496. #endif
  4497. #ifdef IP_TTL
  4498. PyModule_AddIntConstant(m, "IP_TTL", IP_TTL);
  4499. #endif
  4500. #ifdef IP_RECVOPTS
  4501. PyModule_AddIntConstant(m, "IP_RECVOPTS", IP_RECVOPTS);
  4502. #endif
  4503. #ifdef IP_RECVRETOPTS
  4504. PyModule_AddIntConstant(m, "IP_RECVRETOPTS", IP_RECVRETOPTS);
  4505. #endif
  4506. #ifdef IP_RECVDSTADDR
  4507. PyModule_AddIntConstant(m, "IP_RECVDSTADDR", IP_RECVDSTADDR);
  4508. #endif
  4509. #ifdef IP_RETOPTS
  4510. PyModule_AddIntConstant(m, "IP_RETOPTS", IP_RETOPTS);
  4511. #endif
  4512. #ifdef IP_MULTICAST_IF
  4513. PyModule_AddIntConstant(m, "IP_MULTICAST_IF", IP_MULTICAST_IF);
  4514. #endif
  4515. #ifdef IP_MULTICAST_TTL
  4516. PyModule_AddIntConstant(m, "IP_MULTICAST_TTL", IP_MULTICAST_TTL);
  4517. #endif
  4518. #ifdef IP_MULTICAST_LOOP
  4519. PyModule_AddIntConstant(m, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
  4520. #endif
  4521. #ifdef IP_ADD_MEMBERSHIP
  4522. PyModule_AddIntConstant(m, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
  4523. #endif
  4524. #ifdef IP_DROP_MEMBERSHIP
  4525. PyModule_AddIntConstant(m, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
  4526. #endif
  4527. #ifdef IP_DEFAULT_MULTICAST_TTL
  4528. PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_TTL",
  4529. IP_DEFAULT_MULTICAST_TTL);
  4530. #endif
  4531. #ifdef IP_DEFAULT_MULTICAST_LOOP
  4532. PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_LOOP",
  4533. IP_DEFAULT_MULTICAST_LOOP);
  4534. #endif
  4535. #ifdef IP_MAX_MEMBERSHIPS
  4536. PyModule_AddIntConstant(m, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS);
  4537. #endif
  4538. /* IPv6 [gs]etsockopt options, defined in RFC2553 */
  4539. #ifdef IPV6_JOIN_GROUP
  4540. PyModule_AddIntConstant(m, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP);
  4541. #endif
  4542. #ifdef IPV6_LEAVE_GROUP
  4543. PyModule_AddIntConstant(m, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP);
  4544. #endif
  4545. #ifdef IPV6_MULTICAST_HOPS
  4546. PyModule_AddIntConstant(m, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS);
  4547. #endif
  4548. #ifdef IPV6_MULTICAST_IF
  4549. PyModule_AddIntConstant(m, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF);
  4550. #endif
  4551. #ifdef IPV6_MULTICAST_LOOP
  4552. PyModule_AddIntConstant(m, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP);
  4553. #endif
  4554. #ifdef IPV6_UNICAST_HOPS
  4555. PyModule_AddIntConstant(m, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS);
  4556. #endif
  4557. /* Additional IPV6 socket options, defined in RFC 3493 */
  4558. #ifdef IPV6_V6ONLY
  4559. PyModule_AddIntConstant(m, "IPV6_V6ONLY", IPV6_V6ONLY);
  4560. #endif
  4561. /* Advanced IPV6 socket options, from RFC 3542 */
  4562. #ifdef IPV6_CHECKSUM
  4563. PyModule_AddIntConstant(m, "IPV6_CHECKSUM", IPV6_CHECKSUM);
  4564. #endif
  4565. #ifdef IPV6_DONTFRAG
  4566. PyModule_AddIntConstant(m, "IPV6_DONTFRAG", IPV6_DONTFRAG);
  4567. #endif
  4568. #ifdef IPV6_DSTOPTS
  4569. PyModule_AddIntConstant(m, "IPV6_DSTOPTS", IPV6_DSTOPTS);
  4570. #endif
  4571. #ifdef IPV6_HOPLIMIT
  4572. PyModule_AddIntConstant(m, "IPV6_HOPLIMIT", IPV6_HOPLIMIT);
  4573. #endif
  4574. #ifdef IPV6_HOPOPTS
  4575. PyModule_AddIntConstant(m, "IPV6_HOPOPTS", IPV6_HOPOPTS);
  4576. #endif
  4577. #ifdef IPV6_NEXTHOP
  4578. PyModule_AddIntConstant(m, "IPV6_NEXTHOP", IPV6_NEXTHOP);
  4579. #endif
  4580. #ifdef IPV6_PATHMTU
  4581. PyModule_AddIntConstant(m, "IPV6_PATHMTU", IPV6_PATHMTU);
  4582. #endif
  4583. #ifdef IPV6_PKTINFO
  4584. PyModule_AddIntConstant(m, "IPV6_PKTINFO", IPV6_PKTINFO);
  4585. #endif
  4586. #ifdef IPV6_RECVDSTOPTS
  4587. PyModule_AddIntConstant(m, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS);
  4588. #endif
  4589. #ifdef IPV6_RECVHOPLIMIT
  4590. PyModule_AddIntConstant(m, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT);
  4591. #endif
  4592. #ifdef IPV6_RECVHOPOPTS
  4593. PyModule_AddIntConstant(m, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS);
  4594. #endif
  4595. #ifdef IPV6_RECVPKTINFO
  4596. PyModule_AddIntConstant(m, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO);
  4597. #endif
  4598. #ifdef IPV6_RECVRTHDR
  4599. PyModule_AddIntConstant(m, "IPV6_RECVRTHDR", IPV6_RECVRTHDR);
  4600. #endif
  4601. #ifdef IPV6_RECVTCLASS
  4602. PyModule_AddIntConstant(m, "IPV6_RECVTCLASS", IPV6_RECVTCLASS);
  4603. #endif
  4604. #ifdef IPV6_RTHDR
  4605. PyModule_AddIntConstant(m, "IPV6_RTHDR", IPV6_RTHDR);
  4606. #endif
  4607. #ifdef IPV6_RTHDRDSTOPTS
  4608. PyModule_AddIntConstant(m, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS);
  4609. #endif
  4610. #ifdef IPV6_RTHDR_TYPE_0
  4611. PyModule_AddIntConstant(m, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0);
  4612. #endif
  4613. #ifdef IPV6_RECVPATHMTU
  4614. PyModule_AddIntConstant(m, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU);
  4615. #endif
  4616. #ifdef IPV6_TCLASS
  4617. PyModule_AddIntConstant(m, "IPV6_TCLASS", IPV6_TCLASS);
  4618. #endif
  4619. #ifdef IPV6_USE_MIN_MTU
  4620. PyModule_AddIntConstant(m, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU);
  4621. #endif
  4622. /* TCP options */
  4623. #ifdef TCP_NODELAY
  4624. PyModule_AddIntConstant(m, "TCP_NODELAY", TCP_NODELAY);
  4625. #endif
  4626. #ifdef TCP_MAXSEG
  4627. PyModule_AddIntConstant(m, "TCP_MAXSEG", TCP_MAXSEG);
  4628. #endif
  4629. #ifdef TCP_CORK
  4630. PyModule_AddIntConstant(m, "TCP_CORK", TCP_CORK);
  4631. #endif
  4632. #ifdef TCP_KEEPIDLE
  4633. PyModule_AddIntConstant(m, "TCP_KEEPIDLE", TCP_KEEPIDLE);
  4634. #endif
  4635. #ifdef TCP_KEEPINTVL
  4636. PyModule_AddIntConstant(m, "TCP_KEEPINTVL", TCP_KEEPINTVL);
  4637. #endif
  4638. #ifdef TCP_KEEPCNT
  4639. PyModule_AddIntConstant(m, "TCP_KEEPCNT", TCP_KEEPCNT);
  4640. #endif
  4641. #ifdef TCP_SYNCNT
  4642. PyModule_AddIntConstant(m, "TCP_SYNCNT", TCP_SYNCNT);
  4643. #endif
  4644. #ifdef TCP_LINGER2
  4645. PyModule_AddIntConstant(m, "TCP_LINGER2", TCP_LINGER2);
  4646. #endif
  4647. #ifdef TCP_DEFER_ACCEPT
  4648. PyModule_AddIntConstant(m, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT);
  4649. #endif
  4650. #ifdef TCP_WINDOW_CLAMP
  4651. PyModule_AddIntConstant(m, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP);
  4652. #endif
  4653. #ifdef TCP_INFO
  4654. PyModule_AddIntConstant(m, "TCP_INFO", TCP_INFO);
  4655. #endif
  4656. #ifdef TCP_QUICKACK
  4657. PyModule_AddIntConstant(m, "TCP_QUICKACK", TCP_QUICKACK);
  4658. #endif
  4659. /* IPX options */
  4660. #ifdef IPX_TYPE
  4661. PyModule_AddIntConstant(m, "IPX_TYPE", IPX_TYPE);
  4662. #endif
  4663. /* get{addr,name}info parameters */
  4664. #ifdef EAI_ADDRFAMILY
  4665. PyModule_AddIntConstant(m, "EAI_ADDRFAMILY", EAI_ADDRFAMILY);
  4666. #endif
  4667. #ifdef EAI_AGAIN
  4668. PyModule_AddIntConstant(m, "EAI_AGAIN", EAI_AGAIN);
  4669. #endif
  4670. #ifdef EAI_BADFLAGS
  4671. PyModule_AddIntConstant(m, "EAI_BADFLAGS", EAI_BADFLAGS);
  4672. #endif
  4673. #ifdef EAI_FAIL
  4674. PyModule_AddIntConstant(m, "EAI_FAIL", EAI_FAIL);
  4675. #endif
  4676. #ifdef EAI_FAMILY
  4677. PyModule_AddIntConstant(m, "EAI_FAMILY", EAI_FAMILY);
  4678. #endif
  4679. #ifdef EAI_MEMORY
  4680. PyModule_AddIntConstant(m, "EAI_MEMORY", EAI_MEMORY);
  4681. #endif
  4682. #ifdef EAI_NODATA
  4683. PyModule_AddIntConstant(m, "EAI_NODATA", EAI_NODATA);
  4684. #endif
  4685. #ifdef EAI_NONAME
  4686. PyModule_AddIntConstant(m, "EAI_NONAME", EAI_NONAME);
  4687. #endif
  4688. #ifdef EAI_OVERFLOW
  4689. PyModule_AddIntConstant(m, "EAI_OVERFLOW", EAI_OVERFLOW);
  4690. #endif
  4691. #ifdef EAI_SERVICE
  4692. PyModule_AddIntConstant(m, "EAI_SERVICE", EAI_SERVICE);
  4693. #endif
  4694. #ifdef EAI_SOCKTYPE
  4695. PyModule_AddIntConstant(m, "EAI_SOCKTYPE", EAI_SOCKTYPE);
  4696. #endif
  4697. #ifdef EAI_SYSTEM
  4698. PyModule_AddIntConstant(m, "EAI_SYSTEM", EAI_SYSTEM);
  4699. #endif
  4700. #ifdef EAI_BADHINTS
  4701. PyModule_AddIntConstant(m, "EAI_BADHINTS", EAI_BADHINTS);
  4702. #endif
  4703. #ifdef EAI_PROTOCOL
  4704. PyModule_AddIntConstant(m, "EAI_PROTOCOL", EAI_PROTOCOL);
  4705. #endif
  4706. #ifdef EAI_MAX
  4707. PyModule_AddIntConstant(m, "EAI_MAX", EAI_MAX);
  4708. #endif
  4709. #ifdef AI_PASSIVE
  4710. PyModule_AddIntConstant(m, "AI_PASSIVE", AI_PASSIVE);
  4711. #endif
  4712. #ifdef AI_CANONNAME
  4713. PyModule_AddIntConstant(m, "AI_CANONNAME", AI_CANONNAME);
  4714. #endif
  4715. #ifdef AI_NUMERICHOST
  4716. PyModule_AddIntConstant(m, "AI_NUMERICHOST", AI_NUMERICHOST);
  4717. #endif
  4718. #ifdef AI_NUMERICSERV
  4719. PyModule_AddIntConstant(m, "AI_NUMERICSERV", AI_NUMERICSERV);
  4720. #endif
  4721. #ifdef AI_MASK
  4722. PyModule_AddIntConstant(m, "AI_MASK", AI_MASK);
  4723. #endif
  4724. #ifdef AI_ALL
  4725. PyModule_AddIntConstant(m, "AI_ALL", AI_ALL);
  4726. #endif
  4727. #ifdef AI_V4MAPPED_CFG
  4728. PyModule_AddIntConstant(m, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG);
  4729. #endif
  4730. #ifdef AI_ADDRCONFIG
  4731. PyModule_AddIntConstant(m, "AI_ADDRCONFIG", AI_ADDRCONFIG);
  4732. #endif
  4733. #ifdef AI_V4MAPPED
  4734. PyModule_AddIntConstant(m, "AI_V4MAPPED", AI_V4MAPPED);
  4735. #endif
  4736. #ifdef AI_DEFAULT
  4737. PyModule_AddIntConstant(m, "AI_DEFAULT", AI_DEFAULT);
  4738. #endif
  4739. #ifdef NI_MAXHOST
  4740. PyModule_AddIntConstant(m, "NI_MAXHOST", NI_MAXHOST);
  4741. #endif
  4742. #ifdef NI_MAXSERV
  4743. PyModule_AddIntConstant(m, "NI_MAXSERV", NI_MAXSERV);
  4744. #endif
  4745. #ifdef NI_NOFQDN
  4746. PyModule_AddIntConstant(m, "NI_NOFQDN", NI_NOFQDN);
  4747. #endif
  4748. #ifdef NI_NUMERICHOST
  4749. PyModule_AddIntConstant(m, "NI_NUMERICHOST", NI_NUMERICHOST);
  4750. #endif
  4751. #ifdef NI_NAMEREQD
  4752. PyModule_AddIntConstant(m, "NI_NAMEREQD", NI_NAMEREQD);
  4753. #endif
  4754. #ifdef NI_NUMERICSERV
  4755. PyModule_AddIntConstant(m, "NI_NUMERICSERV", NI_NUMERICSERV);
  4756. #endif
  4757. #ifdef NI_DGRAM
  4758. PyModule_AddIntConstant(m, "NI_DGRAM", NI_DGRAM);
  4759. #endif
  4760. /* shutdown() parameters */
  4761. #ifdef SHUT_RD
  4762. PyModule_AddIntConstant(m, "SHUT_RD", SHUT_RD);
  4763. #elif defined(SD_RECEIVE)
  4764. PyModule_AddIntConstant(m, "SHUT_RD", SD_RECEIVE);
  4765. #else
  4766. PyModule_AddIntConstant(m, "SHUT_RD", 0);
  4767. #endif
  4768. #ifdef SHUT_WR
  4769. PyModule_AddIntConstant(m, "SHUT_WR", SHUT_WR);
  4770. #elif defined(SD_SEND)
  4771. PyModule_AddIntConstant(m, "SHUT_WR", SD_SEND);
  4772. #else
  4773. PyModule_AddIntConstant(m, "SHUT_WR", 1);
  4774. #endif
  4775. #ifdef SHUT_RDWR
  4776. PyModule_AddIntConstant(m, "SHUT_RDWR", SHUT_RDWR);
  4777. #elif defined(SD_BOTH)
  4778. PyModule_AddIntConstant(m, "SHUT_RDWR", SD_BOTH);
  4779. #else
  4780. PyModule_AddIntConstant(m, "SHUT_RDWR", 2);
  4781. #endif
  4782. #ifdef SIO_RCVALL
  4783. {
  4784. DWORD codes[] = {SIO_RCVALL, SIO_KEEPALIVE_VALS};
  4785. const char *names[] = {"SIO_RCVALL", "SIO_KEEPALIVE_VALS"};
  4786. int i;
  4787. for(i = 0; i<sizeof(codes)/sizeof(*codes); ++i) {
  4788. PyObject *tmp;
  4789. tmp = PyLong_FromUnsignedLong(codes[i]);
  4790. if (tmp == NULL)
  4791. return;
  4792. PyModule_AddObject(m, names[i], tmp);
  4793. }
  4794. }
  4795. PyModule_AddIntConstant(m, "RCVALL_OFF", RCVALL_OFF);
  4796. PyModule_AddIntConstant(m, "RCVALL_ON", RCVALL_ON);
  4797. PyModule_AddIntConstant(m, "RCVALL_SOCKETLEVELONLY", RCVALL_SOCKETLEVELONLY);
  4798. #ifdef RCVALL_IPLEVEL
  4799. PyModule_AddIntConstant(m, "RCVALL_IPLEVEL", RCVALL_IPLEVEL);
  4800. #endif
  4801. #ifdef RCVALL_MAX
  4802. PyModule_AddIntConstant(m, "RCVALL_MAX", RCVALL_MAX);
  4803. #endif
  4804. #endif /* _MSTCPIP_ */
  4805. /* Initialize gethostbyname lock */
  4806. #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
  4807. netdb_lock = PyThread_allocate_lock();
  4808. #endif
  4809. }
  4810. #ifndef HAVE_INET_PTON
  4811. #if !defined(NTDDI_VERSION) || (NTDDI_VERSION < NTDDI_LONGHORN)
  4812. /* Simplistic emulation code for inet_pton that only works for IPv4 */
  4813. /* These are not exposed because they do not set errno properly */
  4814. int
  4815. inet_pton(int af, const char *src, void *dst)
  4816. {
  4817. if (af == AF_INET) {
  4818. #if (SIZEOF_INT != 4)
  4819. #error "Not sure if in_addr_t exists and int is not 32-bits."
  4820. #endif
  4821. unsigned int packed_addr;
  4822. packed_addr = inet_addr(src);
  4823. if (packed_addr == INADDR_NONE)
  4824. return 0;
  4825. memcpy(dst, &packed_addr, 4);
  4826. return 1;
  4827. }
  4828. /* Should set errno to EAFNOSUPPORT */
  4829. return -1;
  4830. }
  4831. const char *
  4832. inet_ntop(int af, const void *src, char *dst, socklen_t size)
  4833. {
  4834. if (af == AF_INET) {
  4835. struct in_addr packed_addr;
  4836. if (size < 16)
  4837. /* Should set errno to ENOSPC. */
  4838. return NULL;
  4839. memcpy(&packed_addr, src, sizeof(packed_addr));
  4840. return strncpy(dst, inet_ntoa(packed_addr), size);
  4841. }
  4842. /* Should set errno to EAFNOSUPPORT */
  4843. return NULL;
  4844. }
  4845. #endif
  4846. #endif