⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 socketmodule.c

📁 python s60 1.4.5版本的源代码
💻 C
📖 第 1 页 / 共 5 页
字号:
	/* Workaround for bug in Metrowerks MSL vs. GUSI I/O library */
	if (strchr(mode, 'b') != NULL )
		bufsize = 0;
#endif
	f = PyFile_FromFile(fp, "<socket>", mode, fclose);
	if (f != NULL)
		PyFile_SetBufSize(f, bufsize);
	return f;
}

static char makefile_doc[] =
"makefile([mode[, buffersize]]) -> file object\n\
\n\
Return a regular file object corresponding to the socket.\n\
The mode and buffersize arguments are as for the built-in open() function.";

#endif /* NO_DUP */


/* s.recv(nbytes [,flags]) method */

static PyObject *
PySocketSock_recv(PySocketSockObject *s, PyObject *args)
{
	int len, n, flags = 0;
	PyObject *buf;
	if (!PyArg_ParseTuple(args, "i|i:recv", &len, &flags))
		return NULL;
        if (len < 0) {
		PyErr_SetString(PyExc_ValueError,
				"negative buffersize in connect");
		return NULL;
	}
	buf = PyString_FromStringAndSize((char *) 0, len);
	if (buf == NULL)
		return NULL;
	Py_BEGIN_ALLOW_THREADS
	n = recv(s->sock_fd, PyString_AS_STRING(buf), len, flags);
	Py_END_ALLOW_THREADS
	if (n < 0) {
		Py_DECREF(buf);
		return PySocket_Err();
	}
	if (n != len && _PyString_Resize(&buf, n) < 0)
		return NULL;
	return buf;
}

static char recv_doc[] =
"recv(buffersize[, flags]) -> data\n\
\n\
Receive up to buffersize bytes from the socket.  For the optional flags\n\
argument, see the Unix manual.  When no data is available, block until\n\
at least one byte is available or until the remote end is closed.  When\n\
the remote end is closed and all data is read, return the empty string.";


/* s.recvfrom(nbytes [,flags]) method */

static PyObject *
PySocketSock_recvfrom(PySocketSockObject *s, PyObject *args)
{
	char addrbuf[256];
	PyObject *buf = NULL;
	PyObject *addr = NULL;
	PyObject *ret = NULL;

	int len, n, flags = 0;
	socklen_t addrlen;
	if (!PyArg_ParseTuple(args, "i|i:recvfrom", &len, &flags))
		return NULL;
	if (!getsockaddrlen(s, &addrlen))
		return NULL;
	buf = PyString_FromStringAndSize((char *) 0, len);
	if (buf == NULL)
		return NULL;
	Py_BEGIN_ALLOW_THREADS
	memset(addrbuf, 0, addrlen);
	n = recvfrom(s->sock_fd, PyString_AS_STRING(buf), len, flags,
#ifndef MS_WINDOWS
#if defined(PYOS_OS2)
		     (struct sockaddr *)addrbuf, &addrlen
#else
		     (void *)addrbuf, &addrlen
#endif
#else
		     (struct sockaddr *)addrbuf, &addrlen
#endif
		     );
	Py_END_ALLOW_THREADS
	if (n < 0) {
		Py_DECREF(buf);
		return PySocket_Err();
	}
	if (n != len && _PyString_Resize(&buf, n) < 0)
		return NULL;

	if (!(addr = makesockaddr(s->sock_fd, (struct sockaddr *)addrbuf, addrlen)))
		goto finally;

	ret = Py_BuildValue("OO", buf, addr);
  finally:
	Py_XDECREF(addr);
	Py_XDECREF(buf);
	return ret;
}

static char recvfrom_doc[] =
"recvfrom(buffersize[, flags]) -> (data, address info)\n\
\n\
Like recv(buffersize, flags) but also return the sender's address info.";


/* s.send(data [,flags]) method */

static PyObject *
PySocketSock_send(PySocketSockObject *s, PyObject *args)
{
	char *buf;
	int len, n, flags = 0;
	if (!PyArg_ParseTuple(args, "s#|i:send", &buf, &len, &flags))
		return NULL;
	Py_BEGIN_ALLOW_THREADS
	n = send(s->sock_fd, buf, len, flags);
	Py_END_ALLOW_THREADS
	if (n < 0)
		return PySocket_Err();
	return PyInt_FromLong((long)n);
}

static char send_doc[] =
"send(data[, flags]) -> count\n\
\n\
Send a data string to the socket.  For the optional flags\n\
argument, see the Unix manual.  Return the number of bytes\n\
sent; this may be less than len(data) if the network is busy.";


/* s.sendall(data [,flags]) method */

static PyObject *
PySocketSock_sendall(PySocketSockObject *s, PyObject *args)
{
	char *buf;
	int len, n, flags = 0, total = 0;
	if (!PyArg_ParseTuple(args, "s#|i:sendall", &buf, &len, &flags))
		return NULL;
	Py_BEGIN_ALLOW_THREADS
	do {
		n = send(s->sock_fd, buf, len, flags);
		if (n < 0)
			break;
		total += n;
		buf += n;
		len -= n;
	} while (len > 0);
	Py_END_ALLOW_THREADS
	if (n < 0)
		return PySocket_Err();
	Py_INCREF(Py_None);
	return Py_None;
}

static char sendall_doc[] =
"sendall(data[, flags])\n\
\n\
Send a data string to the socket.  For the optional flags\n\
argument, see the Unix manual.  This calls send() repeatedly\n\
until all data is sent.  If an error occurs, it's impossible\n\
to tell how much data has been sent.";


/* s.sendto(data, [flags,] sockaddr) method */

static PyObject *
PySocketSock_sendto(PySocketSockObject *s, PyObject *args)
{
	PyObject *addro;
	char *buf;
	struct sockaddr *addr;
	int addrlen, len, n, flags;
	flags = 0;
	if (!PyArg_ParseTuple(args, "s#O:sendto", &buf, &len, &addro)) {
		PyErr_Clear();
		if (!PyArg_ParseTuple(args, "s#iO:sendto",
				      &buf, &len, &flags, &addro))
			return NULL;
	}
	if (!getsockaddrarg(s, addro, &addr, &addrlen))
		return NULL;
	Py_BEGIN_ALLOW_THREADS
	n = sendto(s->sock_fd, buf, len, flags, addr, addrlen);
	Py_END_ALLOW_THREADS
	if (n < 0)
		return PySocket_Err();
	return PyInt_FromLong((long)n);
}

static char sendto_doc[] =
"sendto(data[, flags], address)\n\
\n\
Like send(data, flags) but allows specifying the destination address.\n\
For IP sockets, the address is a pair (hostaddr, port).";


/* s.shutdown(how) method */

static PyObject *
PySocketSock_shutdown(PySocketSockObject *s, PyObject *arg)
{
	int how;
	int res;

	how = PyInt_AsLong(arg);
	if (how == -1 && PyErr_Occurred())
		return NULL;
	Py_BEGIN_ALLOW_THREADS
	res = shutdown(s->sock_fd, how);
	Py_END_ALLOW_THREADS
	if (res < 0)
		return PySocket_Err();
	Py_INCREF(Py_None);
	return Py_None;
}

static char shutdown_doc[] =
"shutdown(flag)\n\
\n\
Shut down the reading side of the socket (flag == 0), the writing side\n\
of the socket (flag == 1), or both ends (flag == 2).";


/* List of methods for socket objects */

static PyMethodDef PySocketSock_methods[] = {
	{"accept",	(PyCFunction)PySocketSock_accept, METH_NOARGS,
			accept_doc},
	{"bind",	(PyCFunction)PySocketSock_bind, METH_O,
			bind_doc},
	{"close",	(PyCFunction)PySocketSock_close, METH_NOARGS,
			close_doc},
	{"connect",	(PyCFunction)PySocketSock_connect, METH_O,
			connect_doc},
	{"connect_ex",	(PyCFunction)PySocketSock_connect_ex, METH_O,
			connect_ex_doc},
#ifndef NO_DUP
	{"dup",		(PyCFunction)PySocketSock_dup, METH_NOARGS,
			dup_doc},
#endif
	{"fileno",	(PyCFunction)PySocketSock_fileno, METH_NOARGS,
			fileno_doc},
#ifdef HAVE_GETPEERNAME
	{"getpeername",	(PyCFunction)PySocketSock_getpeername, 
	                METH_NOARGS, getpeername_doc},
#endif
	{"getsockname",	(PyCFunction)PySocketSock_getsockname,
	                METH_NOARGS, getsockname_doc},
	{"getsockopt",	(PyCFunction)PySocketSock_getsockopt, METH_VARARGS,
			getsockopt_doc},
	{"listen",	(PyCFunction)PySocketSock_listen, METH_O,
			listen_doc},
#ifndef NO_DUP
	{"makefile",	(PyCFunction)PySocketSock_makefile, METH_VARARGS,
			makefile_doc},
#endif
	{"recv",	(PyCFunction)PySocketSock_recv, METH_VARARGS,
			recv_doc},
	{"recvfrom",	(PyCFunction)PySocketSock_recvfrom, METH_VARARGS,
			recvfrom_doc},
	{"send",	(PyCFunction)PySocketSock_send, METH_VARARGS,
			send_doc},
	{"sendall",	(PyCFunction)PySocketSock_sendall, METH_VARARGS,
			sendall_doc},
	{"sendto",	(PyCFunction)PySocketSock_sendto, METH_VARARGS,
			sendto_doc},
#ifndef SYMBIAN
	{"setblocking",	(PyCFunction)PySocketSock_setblocking, METH_O,
			setblocking_doc},
#endif
	{"setsockopt",	(PyCFunction)PySocketSock_setsockopt, METH_VARARGS,
			setsockopt_doc},
	{"shutdown",	(PyCFunction)PySocketSock_shutdown, METH_O,
			shutdown_doc},
#ifdef RISCOS
	{"sleeptaskw",	(PyCFunction)PySocketSock_sleeptaskw, METH_VARARGS,
	 		sleeptaskw_doc},
#endif
	{NULL,			NULL}		/* sentinel */
};


/* Deallocate a socket object in response to the last Py_DECREF().
   First close the file description. */

static void
PySocketSock_dealloc(PySocketSockObject *s)
{
	if (s->sock_fd != -1)
		(void) SOCKETCLOSE(s->sock_fd);
	s->ob_type->tp_free((PyObject *)s);
}


static PyObject *
PySocketSock_repr(PySocketSockObject *s)
{
	char buf[512];
#if SIZEOF_SOCKET_T > SIZEOF_LONG
	if (s->sock_fd > LONG_MAX) {
		/* this can occur on Win64, and actually there is a special
		   ugly printf formatter for decimal pointer length integer
		   printing, only bother if necessary*/
		PyErr_SetString(PyExc_OverflowError,
			"no printf formatter to display the socket descriptor in decimal");
		return NULL;
	}
#endif
	PyOS_snprintf(buf, sizeof(buf),
		      "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
		      (long)s->sock_fd, s->sock_family,
		      s->sock_type,
		      s->sock_proto);
	return PyString_FromString(buf);
}


/* Create a new, uninitialized socket object. */

static PyObject *
PySocketSock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
	PyObject *new;

	new = type->tp_alloc(type, 0);
	if (new != NULL)
		((PySocketSockObject *)new)->sock_fd = -1;
	return new;
}


/* Initialize a new socket object. */

/*ARGSUSED*/
static int
PySocketSock_init(PyObject *self, PyObject *args, PyObject *kwds)
{
	PySocketSockObject *s = (PySocketSockObject *)self;
	SOCKET_T fd;
	int family = AF_INET, type = SOCK_STREAM, proto = 0;
	static char *keywords[] = {"family", "type", "proto", 0};

	if (!PyArg_ParseTupleAndKeywords(args, kwds,
					 "|iii:socket", keywords,
					 &family, &type, &proto))
		return -1;
	Py_BEGIN_ALLOW_THREADS
	fd = socket(family, type, proto);
	Py_END_ALLOW_THREADS
#ifdef MS_WINDOWS
	if (fd == INVALID_SOCKET)
#else
	if (fd < 0)
#endif
	{
		PySocket_Err();
		return -1;
	}
	init_sockobject(s, fd, family, type, proto);
	/* From now on, ignore SIGPIPE and let the error checking
	   do the work. */
#ifdef HAVE_SIGNAL_H  //MM
#ifdef SIGPIPE
	(void) signal(SIGPIPE, SIG_IGN);
#endif
#endif  //MM
	return 0;
}


/* Type object for socket objects. */

static char socket_doc[] =
"socket([family[, type[, proto]]]) -> socket object\n\
\n\
Open a socket of the given type.  The family argument specifies the\n\
address family; it defaults to AF_INET.  The type argument specifies\n\
whether this is a stream (SOCK_STREAM, this is the default)\n\
or datagram (SOCK_DGRAM) socket.  The protocol argument defaults to 0,\n\
specifying the default protocol.\n\
\n\
A socket represents one endpoint of a network connection.\n\
\n\
Methods:\n\
\n\
accept() -- accept a connection, returning new socket and client address\n\
bind() -- bind the socket to a local address\n\
close() -- close the socket\n\
connect() -- connect the socket to a remote address\n\
connect_ex() -- connect, return an error code instead of an exception \n\
dup() -- return a new socket object identical to the current one (*)\n\
fileno() -- return underlying file descriptor\n\
getpeername() -- return remote address (*)\n\
getsockname() -- return local address\n\
getsockopt() -- get socket options\n\
listen() -- start listening for incoming connections\n\
makefile() -- return a file object corresponding to the socket (*)\n\
recv() -- receive data\n\
recvfrom() -- receive data and sender's address\n\
send() -- send data, may not send all of it\n\
sendall() -- send all data\n\
sendto() -- send data to a given address\n\
setblocking() -- set or clear the blocking I/O flag\n\
setsockopt() -- set socket options\n\
shutdown() -- shut down traffic in one or both directions\n\
\n\
(*) not available on all platforms!)";

static PyTypeObject PySocketSock_Type = {
	PyObject_HEAD_INIT(0)	/* Must fill in type value later */
	0,					/* ob_size */
	"_socket.socket",			/* tp_name */
	sizeof(PySocketSockObject),		/* tp_basicsize */
	0,					/* tp_itemsize */
	(destructor)PySocketSock_dealloc,	/* tp_dealloc */
	0,					/* tp_print */
	0,					/* tp_getattr */
	0,					/* tp_setattr */
	0,					/* tp_compare */
	(reprfunc)PySocketSock_repr,		/* tp_repr */
	0,					/* tp_as_number */
	0,					/* tp_as_sequence */
	0,					/* tp_as_mapping */
	0,					/* tp_hash */
	0,					/* tp_call */
	0,					/* tp_str */
	0,	/* set below */			/* tp_getattro */
	0,					/* tp_setattro */
	0,					/* tp_as_buffer */
	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
	socket_doc,				/* tp_doc */
	0,					/* tp_traverse */
	0,					/* tp_clear */
	0,					/* tp_richcompare */
	0,					/* tp_weaklistoffset */
	0,					/* tp_iter */
	0,					/* tp_iternext */
	PySocketSock_methods,			/* tp_methods */
	0,					/* tp_members */
	0,					/* tp_getset */
	0,					/* tp_base */
	0,					/* tp_dict */
	0,					/* tp_descr_get */
	0,					/* tp_descr_set */
	0,					/* tp_dictoffset */
	PySocketSock_init,			/* tp_init */
	0,	/* set below */			/* tp_alloc */
	PySocketSock_new,			/* tp_new */
	0,	/* set below */			/* tp_free */
};


/* Python interface to gethostname(). */

/*ARGSUSED*/
static PyObject *
PySocket_gethostname(PyObject *self, PyObject *args)
{
	char buf[1024];
	int res;
	if (!PyArg_ParseTuple(args, ":gethostname"))
		return NULL;
	Py_BEGIN_ALLOW_THREADS
	res = gethostname(buf, (int) sizeof buf - 1);
	Py_END_ALLOW_THREADS
	if (res < 0)
		return PySocket_Err();
	buf[sizeof buf - 1] = '\0';
	return PyString_FromString(buf);
}

static char gethostname_doc[] =
"gethostname() -> string\n\
\n\
Return the current host name.";


/* Python interface to gethostbyname(name). */

/*ARGSUSED*/
static PyObject *
PySocket_gethostbyname(PyObject *self, PyObject *args)
{
	char *name;
	struct sockaddr_storage addrbuf;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -