1 /***********************************************************
2 Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
7 Permission to use, copy, modify, and distribute this software and its
8 documentation for any purpose and without fee is hereby granted,
9 provided that the above copyright notice appear in all copies and that
10 both that copyright notice and this permission notice appear in
11 supporting documentation, and that the names of Stichting Mathematisch
12 Centrum or CWI or Corporation for National Research Initiatives or
13 CNRI not be used in advertising or publicity pertaining to
14 distribution of the software without specific, written prior
17 While CWI is the initial source for this software, a modified version
18 is made available by the Corporation for National Research Initiatives
19 (CNRI) at the Internet address ftp://ftp.python.org.
21 STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
22 REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
23 MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
24 CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
25 DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
26 PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
27 TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
28 PERFORMANCE OF THIS SOFTWARE.
30 ******************************************************************/
35 This module provides an interface to Berkeley socket IPC.
39 - only AF_INET and AF_UNIX address families are supported
40 - no read/write operations (use send/recv or makefile instead)
41 - additional restrictions apply on Windows
45 - socket.error: exception raised for socket specific errors
46 - socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')
47 - socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])
48 - socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com')
49 - socket.getprotobyname(protocolname) --> protocol number
50 - socket.getservbyname(servicename, protocolname) --> port number
51 - socket.socket(family, type [, proto]) --> new socket object
52 - socket.ntohs(16 bit value) --> new int object
53 - socket.ntohl(32 bit value) --> new int object
54 - socket.htons(16 bit value) --> new int object
55 - socket.htonl(32 bit value) --> new int object
56 - socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
57 - an Internet socket address is a pair (hostname, port)
58 where hostname can be anything recognized by gethostbyname()
59 (including the dd.dd.dd.dd notation) and port is in host byte order
60 - where a hostname is returned, the dd.dd.dd.dd notation is used
61 - a UNIX domain socket address is a string specifying the pathname
65 - s.accept() --> new socket object, sockaddr
66 - s.bind(sockaddr) --> None
68 - s.connect(sockaddr) --> None
69 - s.connect_ex(sockaddr) --> 0 or errno (handy for e.g. async connect)
70 - s.fileno() --> file descriptor
71 - s.dup() --> same as socket.fromfd(os.dup(s.fileno(), ...)
72 - s.getpeername() --> sockaddr
73 - s.getsockname() --> sockaddr
74 - s.getsockopt(level, optname[, buflen]) --> int or string
75 - s.listen(backlog) --> None
76 - s.makefile([mode[, bufsize]]) --> file object
77 - s.recv(buflen [,flags]) --> string
78 - s.recvfrom(buflen [,flags]) --> string, sockaddr
79 - s.send(string [,flags]) --> nbytes
80 - s.sendto(string, [flags,] sockaddr) --> nbytes
81 - s.setblocking(0 | 1) --> None
82 - s.setsockopt(level, optname, value) --> None
83 - s.shutdown(how) --> None
84 - repr(s) --> "<socket object, fd=%d, family=%d, type=%d, protocol=%d>"
89 #if defined(WITH_THREAD) && !defined(HAVE_GETHOSTBYNAME_R) && !defined(MS_WINDOWS)
97 #if !defined(MS_WINDOWS) && !defined(PYOS_OS2) && !defined(__BEOS__)
98 extern int gethostname(); /* For Solaris, at least */
101 #if defined(PYCC_VACPP)
104 #include <sys/ioctl.h>
109 #if defined(PYOS_OS2)
111 #define INCL_DOSERRORS
116 #if defined(__BEOS__)
117 /* It's in the libs, but not the headers... - [cjh] */
118 int shutdown( int, int );
121 #include <sys/types.h>
127 #include <sys/socket.h>
128 #include <netinet/in.h>
141 #define O_NDELAY O_NONBLOCK /* For QNX only? */
145 /* fdopen() isn't declared in stdio.h (sigh) */
150 /* Here we have some hacks to choose between K&R or ANSI style function
151 definitions. For NT to build this as an extension module (ie, DLL)
152 it must be compiled by the C++ compiler, as it takes the address of
153 a static data item exported from the main Python DLL.
155 #if defined(MS_WINDOWS) || defined(__BEOS__)
156 /* BeOS suffers from the same socket dichotomy as Win32... - [cjh] */
157 /* seem to be a few differences in the API */
158 #define close closesocket
159 #define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */
160 #define FORCE_ANSI_FUNC_DEFS
163 #if defined(PYOS_OS2)
164 #define close soclose
165 #define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
166 #define FORCE_ANSI_FUNC_DEFS
169 #ifdef FORCE_ANSI_FUNC_DEFS
170 #define BUILD_FUNC_DEF_1( fnname, arg1type, arg1name ) \
171 fnname( arg1type arg1name )
173 #define BUILD_FUNC_DEF_2( fnname, arg1type, arg1name, arg2type, arg2name ) \
174 fnname( arg1type arg1name, arg2type arg2name )
176 #define BUILD_FUNC_DEF_3( fnname, arg1type, arg1name, arg2type, arg2name , arg3type, arg3name ) \
177 fnname( arg1type arg1name, arg2type arg2name, arg3type arg3name )
179 #define BUILD_FUNC_DEF_4( fnname, arg1type, arg1name, arg2type, arg2name , arg3type, arg3name, arg4type, arg4name ) \
180 fnname( arg1type arg1name, arg2type arg2name, arg3type arg3name, arg4type arg4name )
182 #else /* !FORCE_ANSI_FN_DEFS */
183 #define BUILD_FUNC_DEF_1( fnname, arg1type, arg1name ) \
187 #define BUILD_FUNC_DEF_2( fnname, arg1type, arg1name, arg2type, arg2name ) \
188 fnname( arg1name, arg2name ) \
192 #define BUILD_FUNC_DEF_3( fnname, arg1type, arg1name, arg2type, arg2name, arg3type, arg3name ) \
193 fnname( arg1name, arg2name, arg3name ) \
198 #define BUILD_FUNC_DEF_4( fnname, arg1type, arg1name, arg2type, arg2name, arg3type, arg3name, arg4type, arg4name ) \
199 fnname( arg1name, arg2name, arg3name, arg4name ) \
205 #endif /* !FORCE_ANSI_FN_DEFS */
207 /* Global variable holding the exception type for errors detected
208 by this module (but not argument type or memory errors, etc.). */
210 static PyObject
*PySocket_Error
;
213 /* Convenience function to raise an error according to errno
214 and return a NULL pointer from a function. */
220 if (WSAGetLastError()) {
222 v
= Py_BuildValue("(is)", WSAGetLastError(), "winsock error");
224 PyErr_SetObject(PySocket_Error
, v
);
232 #if defined(PYOS_OS2)
233 if (sock_errno() != NO_ERROR
) {
237 int myerrorcode
= sock_errno();
239 /* Retrieve Socket-Related Error Message from MPTN.MSG File */
240 rc
= DosGetMessage(NULL
, 0, outbuf
, sizeof(outbuf
),
241 myerrorcode
- SOCBASEERR
+ 26, "mptn.msg", &msglen
);
242 if (rc
== NO_ERROR
) {
245 outbuf
[msglen
] = '\0'; /* OS/2 Doesn't Guarantee a Terminator */
246 if (strlen(outbuf
) > 0) { /* If Non-Empty Msg, Trim CRLF */
247 char *lastc
= &outbuf
[ strlen(outbuf
)-1 ];
248 while (lastc
> outbuf
&& isspace(*lastc
))
249 *lastc
-- = '\0'; /* Trim Trailing Whitespace (CRLF) */
251 v
= Py_BuildValue("(is)", myerrorcode
, outbuf
);
253 PyErr_SetObject(PySocket_Error
, v
);
261 return PyErr_SetFromErrno(PySocket_Error
);
265 /* The object holding a socket. It holds some extra information,
266 like the address family, which is used to decode socket address
267 arguments properly. */
271 int sock_fd
; /* Socket file descriptor */
272 int sock_family
; /* Address family, e.g., AF_INET */
273 int sock_type
; /* Socket type, e.g., SOCK_STREAM */
274 int sock_proto
; /* Protocol type, usually 0 */
276 struct sockaddr_in in
;
278 struct sockaddr_un un
;
281 } PySocketSockObject
;
284 /* A forward reference to the Socktype type object.
285 The Socktype variable contains pointers to various functions,
286 some of which call newsockobject(), which uses Socktype, so
287 there has to be a circular reference. */
289 staticforward PyTypeObject PySocketSock_Type
;
292 /* Create a new socket object.
293 This just creates the object and initializes it.
294 If the creation fails, return NULL and set an exception (implicit
297 static PySocketSockObject
*
298 BUILD_FUNC_DEF_4(PySocketSock_New
,int,fd
, int,family
, int,type
, int,proto
)
300 PySocketSockObject
*s
;
301 PySocketSock_Type
.ob_type
= &PyType_Type
;
302 s
= PyObject_NEW(PySocketSockObject
, &PySocketSock_Type
);
305 s
->sock_family
= family
;
307 s
->sock_proto
= proto
;
313 /* Lock to allow python interpreter to continue, but only allow one
314 thread to be in gethostbyname */
315 #if defined(WITH_THREAD) && !defined(HAVE_GETHOSTBYNAME_R) && !defined(MS_WINDOWS)
316 PyThread_type_lock gethostbyname_lock
;
320 /* Convert a string specifying a host name or one of a few symbolic
321 names to a numeric IP address. This usually calls gethostbyname()
322 to do the work; the names "" and "<broadcast>" are special.
323 Return the length (should always be 4 bytes), or negative if
324 an error occurred; then an exception is raised. */
327 BUILD_FUNC_DEF_2(setipaddr
, char*,name
, struct sockaddr_in
*,addr_ret
)
332 #ifdef HAVE_GETHOSTBYNAME_R
333 struct hostent hp_allocated
;
335 int buf_len
= (sizeof buf
) - 1;
337 #endif /* HAVE_GETHOSTBYNAME_R */
339 memset((void *) addr_ret
, '\0', sizeof(*addr_ret
));
340 if (name
[0] == '\0') {
341 addr_ret
->sin_addr
.s_addr
= INADDR_ANY
;
344 if (name
[0] == '<' && strcmp(name
, "<broadcast>") == 0) {
345 addr_ret
->sin_addr
.s_addr
= INADDR_BROADCAST
;
348 if (sscanf(name
, "%d.%d.%d.%d%c", &d1
, &d2
, &d3
, &d4
, &ch
) == 4 &&
349 0 <= d1
&& d1
<= 255 && 0 <= d2
&& d2
<= 255 &&
350 0 <= d3
&& d3
<= 255 && 0 <= d4
&& d4
<= 255) {
351 addr_ret
->sin_addr
.s_addr
= htonl(
352 ((long) d1
<< 24) | ((long) d2
<< 16) |
353 ((long) d3
<< 8) | ((long) d4
<< 0));
356 Py_BEGIN_ALLOW_THREADS
357 #ifdef HAVE_GETHOSTBYNAME_R
358 hp
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
, &errnop
);
359 #else /* not HAVE_GETHOSTBYNAME_R */
360 #if defined(WITH_THREAD) && !defined(MS_WINDOWS)
361 PyThread_acquire_lock(gethostbyname_lock
,1);
363 hp
= gethostbyname(name
);
364 #if defined(WITH_THREAD) && !defined(MS_WINDOWS)
365 PyThread_release_lock(gethostbyname_lock
);
367 #endif /* HAVE_GETHOSTBYNAME_R */
371 #ifdef HAVE_HSTRERROR
372 /* Let's get real error message to return */
374 PyErr_SetString(PySocket_Error
, (char *)hstrerror(h_errno
));
376 PyErr_SetString(PySocket_Error
, "host not found");
380 memcpy((char *) &addr_ret
->sin_addr
, hp
->h_addr
, hp
->h_length
);
385 /* Create a string object representing an IP address.
386 This is always a string of the form 'dd.dd.dd.dd' (with variable
390 BUILD_FUNC_DEF_1(makeipaddr
, struct sockaddr_in
*,addr
)
392 long x
= ntohl(addr
->sin_addr
.s_addr
);
394 sprintf(buf
, "%d.%d.%d.%d",
395 (int) (x
>>24) & 0xff, (int) (x
>>16) & 0xff,
396 (int) (x
>> 8) & 0xff, (int) (x
>> 0) & 0xff);
397 return PyString_FromString(buf
);
401 /* Create an object representing the given socket address,
402 suitable for passing it back to bind(), connect() etc.
403 The family field of the sockaddr structure is inspected
404 to determine what kind of address it really is. */
408 BUILD_FUNC_DEF_2(makesockaddr
,struct sockaddr
*,addr
, int,addrlen
)
411 /* No address -- may be recvfrom() from known socket */
417 /* XXX: BeOS version of accept() doesn't set family coreectly */
418 addr
->sa_family
= AF_INET
;
421 switch (addr
->sa_family
) {
425 struct sockaddr_in
*a
= (struct sockaddr_in
*) addr
;
426 PyObject
*addrobj
= makeipaddr(a
);
427 PyObject
*ret
= NULL
;
429 ret
= Py_BuildValue("Oi", addrobj
, ntohs(a
->sin_port
));
438 struct sockaddr_un
*a
= (struct sockaddr_un
*) addr
;
439 return PyString_FromString(a
->sun_path
);
443 /* More cases here... */
446 /* If we don't know the address family, don't raise an
447 exception -- return it as a tuple. */
448 return Py_BuildValue("is#",
451 sizeof(addr
->sa_data
));
457 /* Parse a socket address argument according to the socket object's
458 address family. Return 1 if the address was in the proper format,
459 0 of not. The address is returned through addr_ret, its length
464 getsockaddrarg
,PySocketSockObject
*,s
, PyObject
*,args
, struct sockaddr
**,addr_ret
, int *,len_ret
)
466 switch (s
->sock_family
) {
471 struct sockaddr_un
* addr
;
474 addr
= (struct sockaddr_un
* )&(s
->sock_addr
).un
;
475 if (!PyArg_Parse(args
, "t#", &path
, &len
))
477 if (len
> sizeof addr
->sun_path
) {
478 PyErr_SetString(PySocket_Error
,
479 "AF_UNIX path too long");
482 addr
->sun_family
= AF_UNIX
;
483 memcpy(addr
->sun_path
, path
, len
);
484 addr
->sun_path
[len
] = 0;
485 *addr_ret
= (struct sockaddr
*) addr
;
486 *len_ret
= len
+ sizeof(*addr
) - sizeof(addr
->sun_path
);
493 struct sockaddr_in
* addr
;
496 addr
=(struct sockaddr_in
*)&(s
->sock_addr
).in
;
497 if (!PyArg_Parse(args
, "(si)", &host
, &port
))
499 if (setipaddr(host
, addr
) < 0)
501 addr
->sin_family
= AF_INET
;
502 addr
->sin_port
= htons((short)port
);
503 *addr_ret
= (struct sockaddr
*) addr
;
504 *len_ret
= sizeof *addr
;
508 /* More cases here... */
511 PyErr_SetString(PySocket_Error
, "getsockaddrarg: bad family");
518 /* Get the address length according to the socket object's address family.
519 Return 1 if the family is known, 0 otherwise. The length is returned
523 BUILD_FUNC_DEF_2(getsockaddrlen
,PySocketSockObject
*,s
, int *,len_ret
)
525 switch (s
->sock_family
) {
530 *len_ret
= sizeof (struct sockaddr_un
);
537 *len_ret
= sizeof (struct sockaddr_in
);
541 /* More cases here... */
544 PyErr_SetString(PySocket_Error
, "getsockaddrarg: bad family");
551 /* s.accept() method */
554 BUILD_FUNC_DEF_2(PySocketSock_accept
,PySocketSockObject
*,s
, PyObject
*,args
)
558 PyObject
*sock
= NULL
;
559 PyObject
*addr
= NULL
;
560 PyObject
*res
= NULL
;
562 if (!PyArg_NoArgs(args
))
564 if (!getsockaddrlen(s
, &addrlen
))
566 Py_BEGIN_ALLOW_THREADS
567 newfd
= accept(s
->sock_fd
, (struct sockaddr
*) addrbuf
, &addrlen
);
570 return PySocket_Err();
572 /* Create the new object with unspecified family,
573 to avoid calls to bind() etc. on it. */
574 sock
= (PyObject
*) PySocketSock_New(newfd
,
582 if (!(addr
= makesockaddr((struct sockaddr
*) addrbuf
, addrlen
)))
585 if (!(res
= Py_BuildValue("OO", sock
, addr
)))
594 static char accept_doc
[] =
595 "accept() -> (socket object, address info)\n\
597 Wait for an incoming connection. Return a new socket representing the\n\
598 connection, and the address of the client. For IP sockets, the address\n\
599 info is a pair (hostaddr, port).";
602 /* s.setblocking(1 | 0) method */
605 BUILD_FUNC_DEF_2(PySocketSock_setblocking
,PySocketSockObject
*,s
,PyObject
*,args
)
611 if (!PyArg_Parse(args
, "i", &block
))
613 Py_BEGIN_ALLOW_THREADS
616 setsockopt( s
->sock_fd
, SOL_SOCKET
, SO_NONBLOCK
,
617 (void *)(&block
), sizeof( int ) );
622 ioctl(s
->sock_fd
, FIONBIO
, (caddr_t
)&block
, sizeof(block
));
623 #else /* !PYOS_OS2 */
624 delay_flag
= fcntl (s
->sock_fd
, F_GETFL
, 0);
626 delay_flag
&= (~O_NDELAY
);
628 delay_flag
|= O_NDELAY
;
629 fcntl (s
->sock_fd
, F_SETFL
, delay_flag
);
630 #endif /* !PYOS_OS2 */
631 #else /* MS_WINDOWS */
633 ioctlsocket(s
->sock_fd
, FIONBIO
, (u_long
*)&block
);
634 #endif /* MS_WINDOWS */
635 #endif /* __BEOS__ */
642 static char setblocking_doc
[] =
643 "setblocking(flag)\n\
645 Set the socket to blocking (flag is true) or non-blocking (false).\n\
646 This uses the FIONBIO ioctl with the O_NDELAY flag.";
649 /* s.setsockopt() method.
650 With an integer third argument, sets an integer option.
651 With a string third argument, sets an option from a buffer;
652 use optional built-in module 'struct' to encode the string. */
655 BUILD_FUNC_DEF_2(PySocketSock_setsockopt
,PySocketSockObject
*,s
, PyObject
*,args
)
664 if (PyArg_Parse(args
, "(iii)", &level
, &optname
, &flag
)) {
665 buf
= (char *) &flag
;
666 buflen
= sizeof flag
;
670 if (!PyArg_Parse(args
, "(iis#)", &level
, &optname
,
674 res
= setsockopt(s
->sock_fd
, level
, optname
, (ANY
*)buf
, buflen
);
676 return PySocket_Err();
681 static char setsockopt_doc
[] =
682 "setsockopt(level, option, value)\n\
684 Set a socket option. See the Unix manual for level and option.\n\
685 The value argument can either be an integer or a string.";
688 /* s.getsockopt() method.
689 With two arguments, retrieves an integer option.
690 With a third integer argument, retrieves a string buffer of that size;
691 use optional built-in module 'struct' to decode the string. */
694 BUILD_FUNC_DEF_2(PySocketSock_getsockopt
,PySocketSockObject
*,s
, PyObject
*,args
)
703 /* We have incomplete socket support. */
704 PyErr_SetString( PySocket_Error
, "getsockopt not supported" );
708 if (!PyArg_ParseTuple(args
, "ii|i", &level
, &optname
, &buflen
))
713 int flagsize
= sizeof flag
;
714 res
= getsockopt(s
->sock_fd
, level
, optname
,
715 (ANY
*)&flag
, &flagsize
);
717 return PySocket_Err();
718 return PyInt_FromLong(flag
);
720 if (buflen
<= 0 || buflen
> 1024) {
721 PyErr_SetString(PySocket_Error
,
722 "getsockopt buflen out of range");
725 buf
= PyString_FromStringAndSize((char *)NULL
, buflen
);
728 res
= getsockopt(s
->sock_fd
, level
, optname
,
729 (ANY
*)PyString_AsString(buf
), &buflen
);
732 return PySocket_Err();
734 _PyString_Resize(&buf
, buflen
);
736 #endif /* __BEOS__ */
739 static char getsockopt_doc
[] =
740 "getsockopt(level, option[, buffersize]) -> value\n\
742 Get a socket option. See the Unix manual for level and option.\n\
743 If a nonzero buffersize argument is given, the return value is a\n\
744 string of that length; otherwise it is an integer.";
747 /* s.bind(sockaddr) method */
750 BUILD_FUNC_DEF_2(PySocketSock_bind
,PySocketSockObject
*,s
, PyObject
*,args
)
752 struct sockaddr
*addr
;
755 if (!getsockaddrarg(s
, args
, &addr
, &addrlen
))
757 Py_BEGIN_ALLOW_THREADS
758 res
= bind(s
->sock_fd
, addr
, addrlen
);
761 return PySocket_Err();
766 static char bind_doc
[] =
769 Bind the socket to a local address. For IP sockets, the address is a\n\
770 pair (host, port); the host must refer to the local host.";
774 Set the file descriptor to -1 so operations tried subsequently
778 BUILD_FUNC_DEF_2(PySocketSock_close
,PySocketSockObject
*,s
, PyObject
*,args
)
780 if (!PyArg_NoArgs(args
))
782 if (s
->sock_fd
!= -1) {
783 Py_BEGIN_ALLOW_THREADS
784 (void) close(s
->sock_fd
);
792 static char close_doc
[] =
795 Close the socket. It cannot be used after this call.";
798 /* s.connect(sockaddr) method */
801 BUILD_FUNC_DEF_2(PySocketSock_connect
,PySocketSockObject
*,s
, PyObject
*,args
)
803 struct sockaddr
*addr
;
806 if (!getsockaddrarg(s
, args
, &addr
, &addrlen
))
808 Py_BEGIN_ALLOW_THREADS
809 res
= connect(s
->sock_fd
, addr
, addrlen
);
812 return PySocket_Err();
817 static char connect_doc
[] =
820 Connect the socket to a remote address. For IP sockets, the address\n\
821 is a pair (host, port).";
824 /* s.connect_ex(sockaddr) method */
827 BUILD_FUNC_DEF_2(PySocketSock_connect_ex
,PySocketSockObject
*,s
, PyObject
*,args
)
829 struct sockaddr
*addr
;
832 if (!getsockaddrarg(s
, args
, &addr
, &addrlen
))
834 Py_BEGIN_ALLOW_THREADS
835 res
= connect(s
->sock_fd
, addr
, addrlen
);
839 return PyInt_FromLong((long) res
);
842 static char connect_ex_doc
[] =
843 "connect_ex(address)\n\
845 This is like connect(address), but returns an error code (the errno value)\n\
846 instead of raising an exception when an error occurs.";
849 /* s.fileno() method */
852 BUILD_FUNC_DEF_2(PySocketSock_fileno
,PySocketSockObject
*,s
, PyObject
*,args
)
854 if (!PyArg_NoArgs(args
))
856 return PyInt_FromLong((long) s
->sock_fd
);
859 static char fileno_doc
[] =
860 "fileno() -> integer\n\
862 Return the integer file descriptor of the socket.";
869 BUILD_FUNC_DEF_2(PySocketSock_dup
,PySocketSockObject
*,s
, PyObject
*,args
)
873 if (!PyArg_NoArgs(args
))
875 newfd
= dup(s
->sock_fd
);
877 return PySocket_Err();
878 sock
= (PyObject
*) PySocketSock_New(newfd
,
887 static char dup_doc
[] =
888 "dup() -> socket object\n\
890 Return a new socket object connected to the same system resource.";
895 /* s.getsockname() method */
898 BUILD_FUNC_DEF_2(PySocketSock_getsockname
,PySocketSockObject
*,s
, PyObject
*,args
)
902 if (!PyArg_NoArgs(args
))
904 if (!getsockaddrlen(s
, &addrlen
))
906 memset(addrbuf
, 0, addrlen
);
907 Py_BEGIN_ALLOW_THREADS
908 res
= getsockname(s
->sock_fd
, (struct sockaddr
*) addrbuf
, &addrlen
);
911 return PySocket_Err();
912 return makesockaddr((struct sockaddr
*) addrbuf
, addrlen
);
915 static char getsockname_doc
[] =
916 "getsockname() -> address info\n\
918 Return the address of the local endpoint. For IP sockets, the address\n\
919 info is a pair (hostaddr, port).";
922 #ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
923 /* s.getpeername() method */
926 BUILD_FUNC_DEF_2(PySocketSock_getpeername
,PySocketSockObject
*,s
, PyObject
*,args
)
930 if (!PyArg_NoArgs(args
))
932 if (!getsockaddrlen(s
, &addrlen
))
934 Py_BEGIN_ALLOW_THREADS
935 res
= getpeername(s
->sock_fd
, (struct sockaddr
*) addrbuf
, &addrlen
);
938 return PySocket_Err();
939 return makesockaddr((struct sockaddr
*) addrbuf
, addrlen
);
942 static char getpeername_doc
[] =
943 "getpeername() -> address info\n\
945 Return the address of the remote endpoint. For IP sockets, the address\n\
946 info is a pair (hostaddr, port).";
948 #endif /* HAVE_GETPEERNAME */
951 /* s.listen(n) method */
954 BUILD_FUNC_DEF_2(PySocketSock_listen
,PySocketSockObject
*,s
, PyObject
*,args
)
958 if (!PyArg_Parse(args
, "i", &backlog
))
960 Py_BEGIN_ALLOW_THREADS
963 res
= listen(s
->sock_fd
, backlog
);
966 return PySocket_Err();
971 static char listen_doc
[] =
974 Enable a server to accept connections. The backlog argument must be at\n\
975 least 1; it specifies the number of unaccepted connection that the system\n\
976 will allow before refusing new connections.";
980 /* s.makefile(mode) method.
981 Create a new open file object referring to a dupped version of
982 the socket's file descriptor. (The dup() call is necessary so
983 that the open file and socket objects may be closed independent
985 The mode argument specifies 'r' or 'w' passed to fdopen(). */
988 BUILD_FUNC_DEF_2(PySocketSock_makefile
,PySocketSockObject
*,s
, PyObject
*,args
)
990 extern int fclose
Py_PROTO((FILE *));
997 if (!PyArg_ParseTuple(args
, "|si", &mode
, &bufsize
))
1000 if (((fd
= _open_osfhandle(s
->sock_fd
, _O_BINARY
)) < 0) ||
1001 ((fd
= dup(fd
)) < 0) || ((fp
= fdopen(fd
, mode
)) == NULL
))
1003 if ((fd
= dup(s
->sock_fd
)) < 0 || (fp
= fdopen(fd
, mode
)) == NULL
)
1008 return PySocket_Err();
1010 f
= PyFile_FromFile(fp
, "<socket>", mode
, fclose
);
1012 PyFile_SetBufSize(f
, bufsize
);
1016 static char makefile_doc
[] =
1017 "makefile([mode[, buffersize]]) -> file object\n\
1019 Return a regular file object corresponding to the socket.\n\
1020 The mode and buffersize arguments are as for the built-in open() function.";
1025 /* s.recv(nbytes [,flags]) method */
1028 BUILD_FUNC_DEF_2(PySocketSock_recv
,PySocketSockObject
*,s
, PyObject
*,args
)
1030 int len
, n
, flags
= 0;
1032 if (!PyArg_ParseTuple(args
, "i|i", &len
, &flags
))
1034 buf
= PyString_FromStringAndSize((char *) 0, len
);
1037 Py_BEGIN_ALLOW_THREADS
1038 n
= recv(s
->sock_fd
, PyString_AsString(buf
), len
, flags
);
1039 Py_END_ALLOW_THREADS
1042 return PySocket_Err();
1044 if (n
!= len
&& _PyString_Resize(&buf
, n
) < 0)
1049 static char recv_doc
[] =
1050 "recv(buffersize[, flags]) -> data\n\
1052 Receive up to buffersize bytes from the socket. For the optional flags\n\
1053 argument, see the Unix manual. When no data is available, block until\n\
1054 at least one byte is available or until the remote end is closed. When\n\
1055 the remote end is closed and all data is read, return the empty string.";
1058 /* s.recvfrom(nbytes [,flags]) method */
1061 BUILD_FUNC_DEF_2(PySocketSock_recvfrom
,PySocketSockObject
*,s
, PyObject
*,args
)
1064 PyObject
*buf
= NULL
;
1065 PyObject
*addr
= NULL
;
1066 PyObject
*ret
= NULL
;
1068 int addrlen
, len
, n
, flags
= 0;
1069 if (!PyArg_ParseTuple(args
, "i|i", &len
, &flags
))
1071 if (!getsockaddrlen(s
, &addrlen
))
1073 buf
= PyString_FromStringAndSize((char *) 0, len
);
1076 Py_BEGIN_ALLOW_THREADS
1077 n
= recvfrom(s
->sock_fd
, PyString_AsString(buf
), len
, flags
,
1079 #if defined(PYOS_OS2)
1080 (struct sockaddr
*)addrbuf
, &addrlen
1082 (ANY
*)addrbuf
, &addrlen
1085 (struct sockaddr
*)addrbuf
, &addrlen
1088 Py_END_ALLOW_THREADS
1091 return PySocket_Err();
1093 if (n
!= len
&& _PyString_Resize(&buf
, n
) < 0)
1096 if (!(addr
= makesockaddr((struct sockaddr
*)addrbuf
, addrlen
)))
1099 ret
= Py_BuildValue("OO", buf
, addr
);
1106 static char recvfrom_doc
[] =
1107 "recvfrom(buffersize[, flags]) -> (data, address info)\n\
1109 Like recv(buffersize, flags) but also return the sender's address info.";
1112 /* s.send(data [,flags]) method */
1115 BUILD_FUNC_DEF_2(PySocketSock_send
,PySocketSockObject
*,s
, PyObject
*,args
)
1118 int len
, n
, flags
= 0;
1119 if (!PyArg_ParseTuple(args
, "s#|i", &buf
, &len
, &flags
))
1121 Py_BEGIN_ALLOW_THREADS
1122 n
= send(s
->sock_fd
, buf
, len
, flags
);
1123 Py_END_ALLOW_THREADS
1125 return PySocket_Err();
1126 return PyInt_FromLong((long)n
);
1129 static char send_doc
[] =
1130 "send(data[, flags])\n\
1132 Send a data string to the socket. For the optional flags\n\
1133 argument, see the Unix manual.";
1136 /* s.sendto(data, [flags,] sockaddr) method */
1139 BUILD_FUNC_DEF_2(PySocketSock_sendto
,PySocketSockObject
*,s
, PyObject
*,args
)
1143 struct sockaddr
*addr
;
1144 int addrlen
, len
, n
, flags
;
1146 if (!PyArg_Parse(args
, "(s#O)", &buf
, &len
, &addro
)) {
1148 if (!PyArg_Parse(args
, "(s#iO)", &buf
, &len
, &flags
, &addro
))
1151 if (!getsockaddrarg(s
, addro
, &addr
, &addrlen
))
1153 Py_BEGIN_ALLOW_THREADS
1154 n
= sendto(s
->sock_fd
, buf
, len
, flags
, addr
, addrlen
);
1155 Py_END_ALLOW_THREADS
1157 return PySocket_Err();
1158 return PyInt_FromLong((long)n
);
1161 static char sendto_doc
[] =
1162 "sendto(data[, flags], address)\n\
1164 Like send(data, flags) but allows specifying the destination address.\n\
1165 For IP sockets, the address is a pair (hostaddr, port).";
1168 /* s.shutdown(how) method */
1171 BUILD_FUNC_DEF_2(PySocketSock_shutdown
,PySocketSockObject
*,s
, PyObject
*,args
)
1175 if (!PyArg_Parse(args
, "i", &how
))
1177 Py_BEGIN_ALLOW_THREADS
1178 res
= shutdown(s
->sock_fd
, how
);
1179 Py_END_ALLOW_THREADS
1181 return PySocket_Err();
1186 static char shutdown_doc
[] =
1189 Shut down the reading side of the socket (flag == 0), the writing side\n\
1190 of the socket (flag == 1), or both ends (flag == 2).";
1193 /* List of methods for socket objects */
1195 static PyMethodDef PySocketSock_methods
[] = {
1196 {"accept", (PyCFunction
)PySocketSock_accept
, 0,
1198 {"bind", (PyCFunction
)PySocketSock_bind
, 0,
1200 {"close", (PyCFunction
)PySocketSock_close
, 0,
1202 {"connect", (PyCFunction
)PySocketSock_connect
, 0,
1204 {"connect_ex", (PyCFunction
)PySocketSock_connect_ex
, 0,
1207 {"dup", (PyCFunction
)PySocketSock_dup
, 0,
1210 {"fileno", (PyCFunction
)PySocketSock_fileno
, 0,
1212 #ifdef HAVE_GETPEERNAME
1213 {"getpeername", (PyCFunction
)PySocketSock_getpeername
, 0,
1216 {"getsockname", (PyCFunction
)PySocketSock_getsockname
, 0,
1218 {"getsockopt", (PyCFunction
)PySocketSock_getsockopt
, 1,
1220 {"listen", (PyCFunction
)PySocketSock_listen
, 0,
1223 {"makefile", (PyCFunction
)PySocketSock_makefile
, 1,
1226 {"recv", (PyCFunction
)PySocketSock_recv
, 1,
1228 {"recvfrom", (PyCFunction
)PySocketSock_recvfrom
, 1,
1230 {"send", (PyCFunction
)PySocketSock_send
, 1,
1232 {"sendto", (PyCFunction
)PySocketSock_sendto
, 0,
1234 {"setblocking", (PyCFunction
)PySocketSock_setblocking
, 0,
1236 {"setsockopt", (PyCFunction
)PySocketSock_setsockopt
, 0,
1238 {"shutdown", (PyCFunction
)PySocketSock_shutdown
, 0,
1240 {NULL
, NULL
} /* sentinel */
1244 /* Deallocate a socket object in response to the last Py_DECREF().
1245 First close the file description. */
1248 BUILD_FUNC_DEF_1(PySocketSock_dealloc
,PySocketSockObject
*,s
)
1250 (void) close(s
->sock_fd
);
1255 /* Return a socket object's named attribute. */
1258 BUILD_FUNC_DEF_2(PySocketSock_getattr
,PySocketSockObject
*,s
, char *,name
)
1260 return Py_FindMethod(PySocketSock_methods
, (PyObject
*) s
, name
);
1265 BUILD_FUNC_DEF_1(PySocketSock_repr
,PySocketSockObject
*,s
)
1269 "<socket object, fd=%d, family=%d, type=%d, protocol=%d>",
1270 s
->sock_fd
, s
->sock_family
, s
->sock_type
, s
->sock_proto
);
1271 return PyString_FromString(buf
);
1275 /* Type object for socket objects. */
1277 static PyTypeObject PySocketSock_Type
= {
1278 PyObject_HEAD_INIT(0) /* Must fill in type value later */
1281 sizeof(PySocketSockObject
),
1283 (destructor
)PySocketSock_dealloc
, /*tp_dealloc*/
1285 (getattrfunc
)PySocketSock_getattr
, /*tp_getattr*/
1288 (reprfunc
)PySocketSock_repr
, /*tp_repr*/
1290 0, /*tp_as_sequence*/
1291 0, /*tp_as_mapping*/
1295 /* Python interface to gethostname(). */
1299 BUILD_FUNC_DEF_2(PySocket_gethostname
,PyObject
*,self
, PyObject
*,args
)
1303 if (!PyArg_NoArgs(args
))
1305 Py_BEGIN_ALLOW_THREADS
1306 res
= gethostname(buf
, (int) sizeof buf
- 1);
1307 Py_END_ALLOW_THREADS
1309 return PySocket_Err();
1310 buf
[sizeof buf
- 1] = '\0';
1311 return PyString_FromString(buf
);
1314 static char gethostname_doc
[] =
1315 "gethostname() -> string\n\
1317 Return the current host name.";
1320 /* Python interface to gethostbyname(name). */
1324 BUILD_FUNC_DEF_2(PySocket_gethostbyname
,PyObject
*,self
, PyObject
*,args
)
1327 struct sockaddr_in addrbuf
;
1328 if (!PyArg_Parse(args
, "s", &name
))
1330 if (setipaddr(name
, &addrbuf
) < 0)
1332 return makeipaddr(&addrbuf
);
1335 static char gethostbyname_doc
[] =
1336 "gethostbyname(host) -> address\n\
1338 Return the IP address (a string of the form '255.255.255.255') for a host.";
1341 /* Convenience function common to gethostbyname_ex and gethostbyaddr */
1344 gethost_common(h
, addr
)
1346 struct sockaddr_in
*addr
;
1349 PyObject
*rtn_tuple
= (PyObject
*)NULL
;
1350 PyObject
*name_list
= (PyObject
*)NULL
;
1351 PyObject
*addr_list
= (PyObject
*)NULL
;
1354 #ifdef HAVE_HSTRERROR
1355 /* Let's get real error message to return */
1357 PyErr_SetString(PySocket_Error
, (char *)hstrerror(h_errno
));
1359 PyErr_SetString(PySocket_Error
, "host not found");
1363 if ((name_list
= PyList_New(0)) == NULL
)
1365 if ((addr_list
= PyList_New(0)) == NULL
)
1367 for (pch
= h
->h_aliases
; *pch
!= NULL
; pch
++) {
1369 tmp
= PyString_FromString(*pch
);
1372 status
= PyList_Append(name_list
, tmp
);
1377 for (pch
= h
->h_addr_list
; *pch
!= NULL
; pch
++) {
1379 memcpy((char *) &addr
->sin_addr
, *pch
, h
->h_length
);
1380 tmp
= makeipaddr(addr
);
1383 status
= PyList_Append(addr_list
, tmp
);
1388 rtn_tuple
= Py_BuildValue("sOO", h
->h_name
, name_list
, addr_list
);
1390 Py_XDECREF(name_list
);
1391 Py_XDECREF(addr_list
);
1396 /* Python interface to gethostbyname_ex(name). */
1400 BUILD_FUNC_DEF_2(PySocket_gethostbyname_ex
,PyObject
*,self
, PyObject
*,args
)
1404 struct sockaddr_in addr
;
1405 #ifdef HAVE_GETHOSTBYNAME_R
1406 struct hostent hp_allocated
;
1408 int buf_len
= (sizeof buf
) - 1;
1410 #endif /* HAVE_GETHOSTBYNAME_R */
1411 if (!PyArg_Parse(args
, "s", &name
))
1413 if (setipaddr(name
, &addr
) < 0)
1415 Py_BEGIN_ALLOW_THREADS
1416 #ifdef HAVE_GETHOSTBYNAME_R
1417 h
= gethostbyname_r(name
, &hp_allocated
, buf
, buf_len
, &errnop
);
1418 #else /* not HAVE_GETHOSTBYNAME_R */
1419 #if defined(WITH_THREAD) && !defined(MS_WINDOWS)
1420 PyThread_acquire_lock(gethostbyname_lock
,1);
1422 h
= gethostbyname(name
);
1423 #if defined(WITH_THREAD) && !defined(MS_WINDOWS)
1424 PyThread_release_lock(gethostbyname_lock
);
1426 #endif /* HAVE_GETHOSTBYNAME_R */
1427 Py_END_ALLOW_THREADS
1428 return gethost_common(h
,&addr
);
1431 static char ghbn_ex_doc
[] =
1432 "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
1434 Return the true host name, a list of aliases, and a list of IP addresses,\n\
1435 for a host. The host argument is a string giving a host name or IP number.";
1438 /* Python interface to gethostbyaddr(IP). */
1442 BUILD_FUNC_DEF_2(PySocket_gethostbyaddr
,PyObject
*,self
, PyObject
*, args
)
1444 struct sockaddr_in addr
;
1447 #ifdef HAVE_GETHOSTBYNAME_R
1448 struct hostent hp_allocated
;
1450 int buf_len
= (sizeof buf
) - 1;
1452 #endif /* HAVE_GETHOSTBYNAME_R */
1454 if (!PyArg_Parse(args
, "s", &ip_num
))
1456 if (setipaddr(ip_num
, &addr
) < 0)
1458 Py_BEGIN_ALLOW_THREADS
1459 #ifdef HAVE_GETHOSTBYNAME_R
1460 h
= gethostbyaddr_r((char *)&addr
.sin_addr
,
1461 sizeof(addr
.sin_addr
),
1463 &hp_allocated
, buf
, buf_len
, &errnop
);
1464 #else /* not HAVE_GETHOSTBYNAME_R */
1465 #if defined(WITH_THREAD) && !defined(MS_WINDOWS)
1466 PyThread_acquire_lock(gethostbyname_lock
,1);
1468 h
= gethostbyaddr((char *)&addr
.sin_addr
,
1469 sizeof(addr
.sin_addr
),
1471 #if defined(WITH_THREAD) && !defined(MS_WINDOWS)
1472 PyThread_release_lock(gethostbyname_lock
);
1474 #endif /* HAVE_GETHOSTBYNAME_R */
1475 Py_END_ALLOW_THREADS
1476 return gethost_common(h
,&addr
);
1479 static char gethostbyaddr_doc
[] =
1480 "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
1482 Return the true host name, a list of aliases, and a list of IP addresses,\n\
1483 for a host. The host argument is a string giving a host name or IP number.";
1486 /* Python interface to getservbyname(name).
1487 This only returns the port number, since the other info is already
1488 known or not useful (like the list of aliases). */
1492 BUILD_FUNC_DEF_2(PySocket_getservbyname
,PyObject
*,self
, PyObject
*,args
)
1496 if (!PyArg_Parse(args
, "(ss)", &name
, &proto
))
1498 Py_BEGIN_ALLOW_THREADS
1499 sp
= getservbyname(name
, proto
);
1500 Py_END_ALLOW_THREADS
1502 PyErr_SetString(PySocket_Error
, "service/proto not found");
1505 return PyInt_FromLong((long) ntohs(sp
->s_port
));
1508 static char getservbyname_doc
[] =
1509 "getservbyname(servicename, protocolname) -> integer\n\
1511 Return a port number from a service name and protocol name.\n\
1512 The protocol name should be 'tcp' or 'udp'.";
1515 /* Python interface to getprotobyname(name).
1516 This only returns the protocol number, since the other info is
1517 already known or not useful (like the list of aliases). */
1521 BUILD_FUNC_DEF_2(PySocket_getprotobyname
,PyObject
*,self
, PyObject
*,args
)
1524 struct protoent
*sp
;
1526 /* Not available in BeOS yet. - [cjh] */
1527 PyErr_SetString( PySocket_Error
, "getprotobyname not supported" );
1530 if (!PyArg_Parse(args
, "s", &name
))
1532 Py_BEGIN_ALLOW_THREADS
1533 sp
= getprotobyname(name
);
1534 Py_END_ALLOW_THREADS
1536 PyErr_SetString(PySocket_Error
, "protocol not found");
1539 return PyInt_FromLong((long) sp
->p_proto
);
1543 static char getprotobyname_doc
[] =
1544 "getprotobyname(name) -> integer\n\
1546 Return the protocol number for the named protocol. (Rarely used.)";
1549 /* Python interface to socket(family, type, proto).
1550 The third (protocol) argument is optional.
1551 Return a new socket object. */
1555 BUILD_FUNC_DEF_2(PySocket_socket
,PyObject
*,self
, PyObject
*,args
)
1557 PySocketSockObject
*s
;
1563 int family
, type
, proto
= 0;
1564 if (!PyArg_ParseTuple(args
, "ii|i", &family
, &type
, &proto
))
1566 Py_BEGIN_ALLOW_THREADS
1567 fd
= socket(family
, type
, proto
);
1568 Py_END_ALLOW_THREADS
1570 if (fd
== INVALID_SOCKET
)
1574 return PySocket_Err();
1575 s
= PySocketSock_New(fd
, family
, type
, proto
);
1576 /* If the object can't be created, don't forget to close the
1577 file descriptor again! */
1580 /* From now on, ignore SIGPIPE and let the error checking
1583 (void) signal(SIGPIPE
, SIG_IGN
);
1585 return (PyObject
*) s
;
1588 static char socket_doc
[] =
1589 "socket(family, type[, proto]) -> socket object\n\
1591 Open a socket of the given type. The family argument specifies the\n\
1592 address family; it is normally AF_INET, sometimes AF_UNIX.\n\
1593 The type argument specifies whether this is a stream (SOCK_STREAM)\n\
1594 or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0,\n\
1595 specifying the default protocol.";
1599 /* Create a socket object from a numeric file description.
1600 Useful e.g. if stdin is a socket.
1601 Additional arguments as for socket(). */
1605 BUILD_FUNC_DEF_2(PySocket_fromfd
,PyObject
*,self
, PyObject
*,args
)
1607 PySocketSockObject
*s
;
1608 int fd
, family
, type
, proto
= 0;
1609 if (!PyArg_ParseTuple(args
, "iii|i", &fd
, &family
, &type
, &proto
))
1611 /* Dup the fd so it and the socket can be closed independently */
1614 return PySocket_Err();
1615 s
= PySocketSock_New(fd
, family
, type
, proto
);
1616 /* From now on, ignore SIGPIPE and let the error checking
1619 (void) signal(SIGPIPE
, SIG_IGN
);
1621 return (PyObject
*) s
;
1624 static char fromfd_doc
[] =
1625 "fromfd(fd, family, type[, proto]) -> socket object\n\
1627 Create a socket object from the given file descriptor.\n\
1628 The remaining arguments are the same as for socket().";
1634 BUILD_FUNC_DEF_2(PySocket_ntohs
, PyObject
*, self
, PyObject
*, args
)
1638 if (!PyArg_Parse(args
, "i", &x1
)) {
1641 x2
= (int)ntohs((short)x1
);
1642 return PyInt_FromLong(x2
);
1645 static char ntohs_doc
[] =
1646 "ntohs(integer) -> integer\n\
1648 Convert a 16-bit integer from network to host byte order.";
1652 BUILD_FUNC_DEF_2(PySocket_ntohl
, PyObject
*, self
, PyObject
*, args
)
1656 if (!PyArg_Parse(args
, "i", &x1
)) {
1660 return PyInt_FromLong(x2
);
1663 static char ntohl_doc
[] =
1664 "ntohl(integer) -> integer\n\
1666 Convert a 32-bit integer from network to host byte order.";
1670 BUILD_FUNC_DEF_2(PySocket_htons
, PyObject
*, self
, PyObject
*, args
)
1674 if (!PyArg_Parse(args
, "i", &x1
)) {
1677 x2
= (int)htons((short)x1
);
1678 return PyInt_FromLong(x2
);
1681 static char htons_doc
[] =
1682 "htons(integer) -> integer\n\
1684 Convert a 16-bit integer from host to network byte order.";
1688 BUILD_FUNC_DEF_2(PySocket_htonl
, PyObject
*, self
, PyObject
*, args
)
1692 if (!PyArg_Parse(args
, "i", &x1
)) {
1696 return PyInt_FromLong(x2
);
1699 static char htonl_doc
[] =
1700 "htonl(integer) -> integer\n\
1702 Convert a 32-bit integer from host to network byte order.";
1705 /* List of functions exported by this module. */
1707 static PyMethodDef PySocket_methods
[] = {
1708 {"gethostbyname", PySocket_gethostbyname
, 0, gethostbyname_doc
},
1709 {"gethostbyname_ex", PySocket_gethostbyname_ex
, 0, ghbn_ex_doc
},
1710 {"gethostbyaddr", PySocket_gethostbyaddr
, 0, gethostbyaddr_doc
},
1711 {"gethostname", PySocket_gethostname
, 0, gethostname_doc
},
1712 {"getservbyname", PySocket_getservbyname
, 0, getservbyname_doc
},
1713 {"getprotobyname", PySocket_getprotobyname
, 0,getprotobyname_doc
},
1714 {"socket", PySocket_socket
, 1, socket_doc
},
1716 {"fromfd", PySocket_fromfd
, 1, fromfd_doc
},
1718 {"ntohs", PySocket_ntohs
, 0, ntohs_doc
},
1719 {"ntohl", PySocket_ntohl
, 0, ntohl_doc
},
1720 {"htons", PySocket_htons
, 0, htons_doc
},
1721 {"htonl", PySocket_htonl
, 0, htonl_doc
},
1722 {NULL
, NULL
} /* Sentinel */
1726 /* Convenience routine to export an integer value.
1728 * Errors are silently ignored, for better or for worse...
1731 BUILD_FUNC_DEF_3(insint
,PyObject
*,d
, char *,name
, int,value
)
1733 PyObject
*v
= PyInt_FromLong((long) value
);
1734 if (!v
|| PyDict_SetItemString(d
, name
, v
))
1743 /* Additional initialization and cleanup for NT/Windows */
1757 ret
= WSAStartup(0x0101, &WSAData
);
1759 case 0: /* no error */
1762 case WSASYSNOTREADY
:
1763 PyErr_SetString(PyExc_ImportError
,
1764 "WSAStartup failed: network not ready");
1766 case WSAVERNOTSUPPORTED
:
1768 PyErr_SetString(PyExc_ImportError
,
1769 "WSAStartup failed: requested version not supported");
1772 sprintf(buf
, "WSAStartup failed: error code %d", ret
);
1773 PyErr_SetString(PyExc_ImportError
, buf
);
1779 #endif /* MS_WINDOWS */
1781 #if defined(PYOS_OS2)
1783 /* Additional initialization and cleanup for OS/2 */
1788 /* No cleanup is necessary for OS/2 Sockets */
1795 int rc
= sock_init();
1799 return 1; /* Indicate Success */
1802 sprintf(reason
, "OS/2 TCP/IP Error# %d", sock_errno());
1803 PyErr_SetString(PyExc_ImportError
, reason
);
1805 return 0; /* Indicate Failure */
1808 #endif /* PYOS_OS2 */
1811 /* Initialize this module.
1812 * This is called when the first 'import socket' is done,
1813 * via a table in config.c, if config.c is compiled with USE_SOCKET
1816 * For MS_WINDOWS (which means any Windows variant), this module
1817 * is actually called "_socket", and there's a wrapper "socket.py"
1818 * which implements some missing functionality (such as makefile(),
1819 * dup() and fromfd()). The import of "_socket" may fail with an
1820 * ImportError exception if initialization of WINSOCK fails. When
1821 * WINSOCK is initialized succesfully, a call to WSACleanup() is
1822 * scheduled to be made at exit time.
1824 * For OS/2, this module is also called "_socket" and uses a wrapper
1825 * "socket.py" which implements that functionality that is missing
1826 * when PC operating systems don't put socket descriptors in the
1827 * operating system's filesystem layer.
1830 static char module_doc
[] =
1831 "This module provides socket operations and some related functions.\n\
1832 On Unix, it supports IP (Internet Protocol) and Unix domain sockets.\n\
1833 On other systems, it only supports IP.\n\
1837 socket() -- create a new socket object\n\
1838 fromfd() -- create a socket object from an open file descriptor (*)\n\
1839 gethostname() -- return the current hostname\n\
1840 gethostbyname() -- map a hostname to its IP number\n\
1841 gethostbyaddr() -- map an IP number or hostname to DNS info\n\
1842 getservbyname() -- map a service name and a protocol name to a port number\n\
1843 getprotobyname() -- mape a protocol name (e.g. 'tcp') to a number\n\
1844 ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order\n\
1845 htons(), htonl() -- convert 16, 32 bit int from host to network byte order\n\
1847 (*) not available on all platforms!)\n\
1851 SocketType -- type object for socket objects\n\
1852 error -- exception raised for I/O errors\n\
1854 Integer constants:\n\
1856 AF_INET, AF_UNIX -- socket domains (first argument to socket() call)\n\
1857 SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument)\n\
1859 Many other constants may be defined; these may be used in calls to\n\
1860 the setsockopt() and getsockopt() methods.\n\
1863 static char sockettype_doc
[] =
1864 "A socket represents one endpoint of a network connection.\n\
1868 accept() -- accept a connection, returning new socket and client address\n\
1869 bind() -- bind the socket to a local address\n\
1870 close() -- close the socket\n\
1871 connect() -- connect the socket to a remote address\n\
1872 connect_ex() -- connect, return an error code instead of an exception \n\
1873 dup() -- return a new socket object identical to the current one (*)\n\
1874 fileno() -- return underlying file descriptor\n\
1875 getpeername() -- return remote address (*)\n\
1876 getsockname() -- return local address\n\
1877 getsockopt() -- get socket options\n\
1878 listen() -- start listening for incoming connections\n\
1879 makefile() -- return a file object corresponding tot the socket (*)\n\
1880 recv() -- receive data\n\
1881 recvfrom() -- receive data and sender's address\n\
1882 send() -- send data\n\
1883 sendto() -- send data to a given address\n\
1884 setblocking() -- set or clear the blocking I/O flag\n\
1885 setsockopt() -- set socket options\n\
1886 shutdown() -- shut down traffic in one or both directions\n\
1888 (*) not available on all platforms!)";
1891 #if defined(MS_WINDOWS) || defined(PYOS_OS2) || defined(__BEOS__)
1901 m
= Py_InitModule3("_socket", PySocket_methods
, module_doc
);
1903 #if defined(__TOS_OS2__)
1906 m
= Py_InitModule3("_socket", PySocket_methods
, module_doc
);
1908 #if defined(__BEOS__)
1909 m
= Py_InitModule3("_socket", PySocket_methods
, module_doc
);
1911 m
= Py_InitModule3("socket", PySocket_methods
, module_doc
);
1912 #endif /* __BEOS__ */
1915 d
= PyModule_GetDict(m
);
1916 PySocket_Error
= PyErr_NewException("socket.error", NULL
, NULL
);
1917 if (PySocket_Error
== NULL
)
1919 PyDict_SetItemString(d
, "error", PySocket_Error
);
1920 PySocketSock_Type
.ob_type
= &PyType_Type
;
1921 PySocketSock_Type
.tp_doc
= sockettype_doc
;
1922 Py_INCREF(&PySocketSock_Type
);
1923 if (PyDict_SetItemString(d
, "SocketType",
1924 (PyObject
*)&PySocketSock_Type
) != 0)
1926 insint(d
, "AF_INET", AF_INET
);
1928 insint(d
, "AF_UNIX", AF_UNIX
);
1929 #endif /* AF_UNIX */
1930 insint(d
, "SOCK_STREAM", SOCK_STREAM
);
1931 insint(d
, "SOCK_DGRAM", SOCK_DGRAM
);
1933 /* We have incomplete socket support. */
1934 insint(d
, "SOCK_RAW", SOCK_RAW
);
1935 insint(d
, "SOCK_SEQPACKET", SOCK_SEQPACKET
);
1936 insint(d
, "SOCK_RDM", SOCK_RDM
);
1940 insint(d
, "SO_DEBUG", SO_DEBUG
);
1942 #ifdef SO_ACCEPTCONN
1943 insint(d
, "SO_ACCEPTCONN", SO_ACCEPTCONN
);
1946 insint(d
, "SO_REUSEADDR", SO_REUSEADDR
);
1949 insint(d
, "SO_KEEPALIVE", SO_KEEPALIVE
);
1952 insint(d
, "SO_DONTROUTE", SO_DONTROUTE
);
1955 insint(d
, "SO_BROADCAST", SO_BROADCAST
);
1957 #ifdef SO_USELOOPBACK
1958 insint(d
, "SO_USELOOPBACK", SO_USELOOPBACK
);
1961 insint(d
, "SO_LINGER", SO_LINGER
);
1964 insint(d
, "SO_OOBINLINE", SO_OOBINLINE
);
1967 insint(d
, "SO_REUSEPORT", SO_REUSEPORT
);
1971 insint(d
, "SO_SNDBUF", SO_SNDBUF
);
1974 insint(d
, "SO_RCVBUF", SO_RCVBUF
);
1977 insint(d
, "SO_SNDLOWAT", SO_SNDLOWAT
);
1980 insint(d
, "SO_RCVLOWAT", SO_RCVLOWAT
);
1983 insint(d
, "SO_SNDTIMEO", SO_SNDTIMEO
);
1986 insint(d
, "SO_RCVTIMEO", SO_RCVTIMEO
);
1989 insint(d
, "SO_ERROR", SO_ERROR
);
1992 insint(d
, "SO_TYPE", SO_TYPE
);
1995 /* Maximum number of connections for "listen" */
1997 insint(d
, "SOMAXCONN", SOMAXCONN
);
1999 insint(d
, "SOMAXCONN", 5); /* Common value */
2002 /* Flags for send, recv */
2004 insint(d
, "MSG_OOB", MSG_OOB
);
2007 insint(d
, "MSG_PEEK", MSG_PEEK
);
2009 #ifdef MSG_DONTROUTE
2010 insint(d
, "MSG_DONTROUTE", MSG_DONTROUTE
);
2013 insint(d
, "MSG_EOR", MSG_EOR
);
2016 insint(d
, "MSG_TRUNC", MSG_TRUNC
);
2019 insint(d
, "MSG_CTRUNC", MSG_CTRUNC
);
2022 insint(d
, "MSG_WAITALL", MSG_WAITALL
);
2025 insint(d
, "MSG_BTAG", MSG_BTAG
);
2028 insint(d
, "MSG_ETAG", MSG_ETAG
);
2031 /* Protocol level and numbers, usable for [gs]etsockopt */
2032 /* Sigh -- some systems (e.g. Linux) use enums for these. */
2034 insint(d
, "SOL_SOCKET", SOL_SOCKET
);
2037 insint(d
, "IPPROTO_IP", IPPROTO_IP
);
2039 insint(d
, "IPPROTO_IP", 0);
2042 insint(d
, "IPPROTO_ICMP", IPPROTO_ICMP
);
2044 insint(d
, "IPPROTO_ICMP", 1);
2047 insint(d
, "IPPROTO_IGMP", IPPROTO_IGMP
);
2050 insint(d
, "IPPROTO_GGP", IPPROTO_GGP
);
2053 insint(d
, "IPPROTO_TCP", IPPROTO_TCP
);
2055 insint(d
, "IPPROTO_TCP", 6);
2058 insint(d
, "IPPROTO_EGP", IPPROTO_EGP
);
2061 insint(d
, "IPPROTO_PUP", IPPROTO_PUP
);
2064 insint(d
, "IPPROTO_UDP", IPPROTO_UDP
);
2066 insint(d
, "IPPROTO_UDP", 17);
2069 insint(d
, "IPPROTO_IDP", IPPROTO_IDP
);
2071 #ifdef IPPROTO_HELLO
2072 insint(d
, "IPPROTO_HELLO", IPPROTO_HELLO
);
2075 insint(d
, "IPPROTO_ND", IPPROTO_ND
);
2078 insint(d
, "IPPROTO_TP", IPPROTO_TP
);
2081 insint(d
, "IPPROTO_XTP", IPPROTO_XTP
);
2084 insint(d
, "IPPROTO_EON", IPPROTO_EON
);
2087 insint(d
, "IPPROTO_BIP", IPPROTO_BIP
);
2091 insint(d
, "IPPROTO_RAW", IPPROTO_RAW
);
2093 insint(d
, "IPPROTO_RAW", 255);
2096 insint(d
, "IPPROTO_MAX", IPPROTO_MAX
);
2099 /* Some port configuration */
2100 #ifdef IPPORT_RESERVED
2101 insint(d
, "IPPORT_RESERVED", IPPORT_RESERVED
);
2103 insint(d
, "IPPORT_RESERVED", 1024);
2105 #ifdef IPPORT_USERRESERVED
2106 insint(d
, "IPPORT_USERRESERVED", IPPORT_USERRESERVED
);
2108 insint(d
, "IPPORT_USERRESERVED", 5000);
2111 /* Some reserved IP v.4 addresses */
2113 insint(d
, "INADDR_ANY", INADDR_ANY
);
2115 insint(d
, "INADDR_ANY", 0x00000000);
2117 #ifdef INADDR_BROADCAST
2118 insint(d
, "INADDR_BROADCAST", INADDR_BROADCAST
);
2120 insint(d
, "INADDR_BROADCAST", 0xffffffff);
2122 #ifdef INADDR_LOOPBACK
2123 insint(d
, "INADDR_LOOPBACK", INADDR_LOOPBACK
);
2125 insint(d
, "INADDR_LOOPBACK", 0x7F000001);
2127 #ifdef INADDR_UNSPEC_GROUP
2128 insint(d
, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP
);
2130 insint(d
, "INADDR_UNSPEC_GROUP", 0xe0000000);
2132 #ifdef INADDR_ALLHOSTS_GROUP
2133 insint(d
, "INADDR_ALLHOSTS_GROUP", INADDR_ALLHOSTS_GROUP
);
2135 insint(d
, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
2137 #ifdef INADDR_MAX_LOCAL_GROUP
2138 insint(d
, "INADDR_MAX_LOCAL_GROUP", INADDR_MAX_LOCAL_GROUP
);
2140 insint(d
, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
2143 insint(d
, "INADDR_NONE", INADDR_NONE
);
2145 insint(d
, "INADDR_NONE", 0xffffffff);
2148 /* IP [gs]etsockopt options */
2150 insint(d
, "IP_OPTIONS", IP_OPTIONS
);
2153 insint(d
, "IP_HDRINCL", IP_HDRINCL
);
2156 insint(d
, "IP_TOS", IP_TOS
);
2159 insint(d
, "IP_TTL", IP_TTL
);
2162 insint(d
, "IP_RECVOPTS", IP_RECVOPTS
);
2164 #ifdef IP_RECVRETOPTS
2165 insint(d
, "IP_RECVRETOPTS", IP_RECVRETOPTS
);
2167 #ifdef IP_RECVDSTADDR
2168 insint(d
, "IP_RECVDSTADDR", IP_RECVDSTADDR
);
2171 insint(d
, "IP_RETOPTS", IP_RETOPTS
);
2173 #ifdef IP_MULTICAST_IF
2174 insint(d
, "IP_MULTICAST_IF", IP_MULTICAST_IF
);
2176 #ifdef IP_MULTICAST_TTL
2177 insint(d
, "IP_MULTICAST_TTL", IP_MULTICAST_TTL
);
2179 #ifdef IP_MULTICAST_LOOP
2180 insint(d
, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP
);
2182 #ifdef IP_ADD_MEMBERSHIP
2183 insint(d
, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP
);
2185 #ifdef IP_DROP_MEMBERSHIP
2186 insint(d
, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP
);
2189 /* Initialize gethostbyname lock */
2190 #if defined(WITH_THREAD) && !defined(HAVE_GETHOSTBYNAME_R) && !defined(MS_WINDOWS)
2191 gethostbyname_lock
= PyThread_allocate_lock();