python - python写的一个正在运行的服务器进程如何查找绑定(bind)地址和端口?

标签 python linux python-3.x sockets

除了源代码之外,我尝试了 $ netstat,但没有发现关于我刚刚运行的 server.py 应用程序的任何信息。

我的应用在这里:

import socket
from server_const import const

def server(port=1060):
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind(("127.0.0.1", port))
    print("The server is listening at {}".format(sock.getsockname()))
    while True:
        data, address = sock.recvfrom(const.MAX_BYTES.value)
        text = data.decode("utf-8")
        print("The client at {} says {!r}".format(address, text))
        text = "Your data was {} bytes long".format(len(data))
        data = text.encode("utf-8")
        sock.sendto(data, address)

我在终端中运行我的应用程序并按 ctrl+z 暂停进程,我如何从我的终端找到绑定(bind)的地址和端口?

最佳答案

如果您在 Linux 上运行,您可以将该程序作为后台进程运行以防止其关闭。

./server.py &

You'll need to use a program like htop or top to terminate the program once it's running in the background. (of course there are several other ways)

或者您可以打开另一个终端 session 。

一旦你让它运行起来,就使用它。

netstat -lnp | grep $(pgrep server.py)

网络统计 -l:限制监听进程,

-n:不解析名称(因为你说你想要 ip),

p: 显示程序(所以我们可以按名称搜索))

|管道组合命令

通过 PI(进程 ID)进行 grep(搜索)

$() 变量,将首先被评估

  • pgrep server.py(搜索指定程序的进程 ID)

关于python - python写的一个正在运行的服务器进程如何查找绑定(bind)地址和端口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46547399/

相关文章:

linux - 为什么 BIOS 不直接加载 Linux 内核 - 为什么是 MBR 和所有那些麻烦?

python - Pytest 失败并出现 AssertionError False is False

python - 强制Python释放对象以释放内存

java - 用于 Linux 的硬件中断 API

python - 如何重新训练自定义图像的 mobilenet 模型

c - 当我使用 fopen 从文件中读取时出现错误 No such file or directory exist

django - LDAP 身份验证在 Graphite 中不起作用

python-3.x - 在GeckoDriver中加载Firefox时权限被拒绝

python - 检查日期列是否在日期范围内 - Pandas

python - 使用python的看门狗从linux监控afp共享文件夹