How can I get the default gateway IP address with Python?

I want to get the IP address of the default gateway (internal IP router) using Python. I'm really new to Python, so I don't know how this works.

I know that you can get the IP address of your machine:

import socket
internal_ip = socket.gethostbyname(socket.gethostname())
print internal_ip

So, I think it should be something like that?

+3
source share
1 answer

On Windows, you must use WMI along with the correct search for object search properties (such as network devices). The following Python code prints IPv4 and default gateway addresses on my Windows 7 machine:

The code:

import wmi

wmi_obj = wmi.WMI()
wmi_sql = "select IPAddress,DefaultIPGateway from Win32_NetworkAdapterConfiguration where IPEnabled=TRUE"
wmi_out = wmi_obj.query( wmi_sql )

for dev in wmi_out:
    print "IPv4Address:", dev.IPAddress[0], "DefaultIPGateway:", dev.DefaultIPGateway[0]

Conclusion:

IPv4Address: 192.168.0.2 DefaultIPGateway: 192.168.0.1

WMI .

Linux PyNetInfo, , . Linux , PROC import os; os.system(...).

+3

Source: https://habr.com/ru/post/1790109/


All Articles