Python程序不显示网关和网络IP

时间:2014-11-13 18:46:46

标签: python ip output local gateway

import socket
import struct

def get_default_gateway_linux():
    with open("/proc/net/route") as fh:
        for line in fh:
            fields = line.strip().split()
            if fields[1] != '00000000' or not int(fields[3], 16) & 2:
                continue

            return socket.inet_ntoa(struct.pack("<L", int(fields[2], 16)))


def getNetworkIp():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(('bt', 0))
    return s.getsockname()[0] 


    print "Your Machine IP has been detected as "+getNetworkIp()

    print "Your Gateway IP has been detected as "+get_default_gateway_linux()

上述代码在回溯5 R3中执行时既不显示任何错误也不显示任何输出 关于这段代码请帮帮我!

2 个答案:

答案 0 :(得分:1)

您的2个打印报表是标签/间距。删除它们,它将工作,因为我已经确认这在CentOS 6.5上工作:

def getNetworkIp():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(('localhost',0))
    return s.getsockname()[0]

print "Your Machine IP has been detected as "+getNetworkIp()

print "Your Gateway IP has been detected as "+get_default_gateway_linux()

答案 1 :(得分:0)

这可能太简单了,但最后两行是getNetworkIp()的一部分,因为它们是缩进的。

当我尝试这个时,我甚至从Python中得到了缩进错误。

请注意,当我将最后2个打印语句移到第0列时,我得到另一个错误,因为我得到了“名称或服务未知”错误...但这可能是旧的Linux / Python问题,或者需要根

无论如何,请尝试取消缩进最后两个打印语句。