Catch internal IP via Python (Router)

Asked

Viewed 129 times

-1

I’m a long time doing research on this, and I wanted to know how to get the local ip (obviously) of my router in python in a Linux environment, I searched it in Google several times and always came with

hostname = socket.gethostname
ip = gethostbyname(hostname)

This here returns at 127.0.0.1 I definitely do not want this, actually what I seek is to save the router ip (here is 192.168.0.1) in a variable

3 answers

0

After a time of study I came to a final resolution:

ip = os.popen("ip route get 8.8.8.8 | awk '{printf $3}'").read().strip()

Works for Linux, wired and Wi-Fi.

0


In Windows, you can achieve using the netifaces, you can install it by Pip and will need the Microsoft Visual C++ 14.0:

import netifaces

gateways = netifaces.gateways()
gateway_padrao = gateways['default'][netifaces.AF_INET][0]
print(gateway_padrao)
  • I assume it was my mistake not to add this information, but I want to do it in a Linux environment

  • I think this answer might help you: https://stackoverflow.com/a/6556951/14100521

0

Create an underlying process with the class Popen to execute the command line:

$ hostname -I

Use the method Popen.communicate to return STDOUT.

import subprocess

#O argumento stdout=subprocess.PIPE que informa Popen deve abrir um Pipe para STDOUT.
#O argumento stderr=subprocess.STDOUT que informa Popen redirecionar STDERR para STDOUT.
out = subprocess.Popen(['hostname', '-I'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout,_ = out.communicate()
print(stdout)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.