Search code examples
pythonipoutputlocalgateway

Python program not displaying gateway and network ip


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()

the above code neither shows any error nor any output when executed in backtrack 5 R3 please help me regarding this code!


Solution

  • Your 2 print statements are tabbed/spaced. Remove them and it will work as I have confirmed this to work on 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()