如何在python下读取ip地址而不泄漏资源

2024-06-28 15:07:09 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在Linux和Windows环境下用Python获取网络信息?我尝试在64位的Ubuntu12.10上使用Python2.7中的netinfo包(ver0.3.2),但是这个包的使用使得句柄没有关闭,如下所示。在我的情况下,这是不被接受的。在

import netinfo

def countOpenFiles():
    import resource, fcntl, os
    n_open = 0
    names = []
    soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
    for fd in range(0, soft):
        try:
            f = fcntl.fcntl(fd, fcntl.F_GETFD)
            n_open += 1
        except IOError:
            continue
    return n_open

for i in range(10):
    netinfo.get_ip('eth0')
    print countOpenFiles()

它产生:

^{pr2}$

我想有类似的netinfo包没有资源泄漏。在

谢谢你的帮助。在


Tags: inimport网络for环境linuxwindowsrange
1条回答
网友
1楼 · 发布于 2024-06-28 15:07:09

你到底想做什么? 就我所见,不计算eth0文件句柄,而是计算所有文件句柄。 如果您只是不打开IP文件句柄,那么可以在Linux下使用lsof(shelltool)。在

lsof-u yoursuser | grep IPv4 不只是eth0,但我不知道如何过滤接口。在

相关问题 更多 >