python - Python如何访问socket()等OS API函数?

标签 python sockets

更新的问题:

  1. 套接字对象实际上是在哪里创建的?我在 socketmodule.c 的第 4188 行找到了这个, 但它看起来像 sock_new 而不是 socket?

    static PyObject *sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
    
  2. 是否有一些约定来确定导入 socketmodule.c 等模块的位置?换句话说,当我看到“from _socket import *”时,我知道谁在导入什么(无需搜索整个存储库)?


原创:

sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)

我试图了解这段代码是如何工作的,特别是 Python 如何/在何处实际调用 socket() 的操作系统函数:

class _socketobject(object):

    __doc__ = _realsocket.__doc__

    __slots__ = ["_sock", "__weakref__"] + list(_delegate_methods)

    def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, _sock=None):
        if _sock is None:
            _sock = _realsocket(family, type, proto)
        self._sock = _sock
        for method in _delegate_methods:
            setattr(self, method, getattr(_sock, method))

当我在维基百科上查找 BSD 套接字时,我看到了这个例子,它很有意义,因为套接字函数是在 types.h 下定义的。在上面,我看到了对 realsocket 的调用,它看起来像一个操作系统函数调用,但我没有在任何地方定义 realsocket(我在 Python27/include 头文件中根本看不到任何关于套接字的信息)。

  /* Server code in C */

  #include <sys/types.h>
  #include <sys/socket.h>
  #include <netinet/in.h>
  #include <arpa/inet.h>
  #include <stdio.h>
  #include <stdlib.h>
  #include <string.h>
  #include <unistd.h>

  int main(void)
  {
    struct sockaddr_in stSockAddr;
    int SocketFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);

最佳答案

它与 socket.py 的第 1st 和第 2nd 行有关:

import _socket
from _socket import *

如果您启动 Python 并运行以下代码:

import socket
print dir(socket)
print dir(socket._socket)

您会注意到,与 socket._socket 相比,socket 只导出了一些额外的东西。

现在,socket._socket 是什么?它是一个 Python 动态模块(意味着它可以像任何其他 python 模块一样使用),但它是用 C 编写的(因此编译后它有一个 OS 特定的 native 形式:Nix 下的 .so.dll (.pyd) em>赢)。它的位置在 python lib 文件夹中(socket.py 也位于该文件夹中):lib-dynload/_socket*.so

您可以通过打印模块来查看模块的位置(在您运行上述代码的同一控制台中,您可以键入):

print socket
print socket._socket

如果您更感兴趣,它的源代码位于 ${PYTHON_SRC_DIR}/Modules/socketmodule.c 中的 Python 源压缩包中(它还有一个头文件)。在这些文件中,定义了包装器函数(在 Python 中可见)并调用 native 函数(例如 socket/usr/include/sys/socket.h).

关于python - Python如何访问socket()等OS API函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31190375/

相关文章:

c - UDP 套接字编程——recvfrom() 一个端口和 sendto() 另一个端口

sockets - 如何向此 TCP 服务器添加 TLS 加密?

c# - 将 PayPal 与控制台应用程序集成

java - "Software caused connection abort: socket write error"的官方原因

python - 如何简化 IF 语句

python - 是否有 "pandas"方法来识别 DataFrame 中的哪些行不存在于合并结果中?

python - 使用networkx打印python图表时保留左右 child

Python 计数单词

python 套接字服务器超时

python - Django Rest Framework 嵌套序列化器对象为 null