-2

I am looking for a short command to get an network interface ip address by its name, in python. it did not work with socket.getaddr() for example, this is my details: enter image description here

I want a func so:

x=func('vEthernet (VIC Ethernet)')

so that x will be 10.10.255.254 i dont want to run ipconfig and parse it

thanks

Ron Keinan
  • 27
  • 4
  • 3
    currently this amounts to a 'write my code for me' question. Such questions are off topic here. In any case the title doesn't line up with the q: do you, or do you not, want to use `ipconfig`? – 2e0byo Jan 10 '22 at 15:06
  • I dont want to use ipconfig – Ron Keinan Jan 10 '22 at 15:10

3 Answers3

0

you can use this function to get the primary IP:

import socket
def get_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.settimeout(0)
    try:
        # doesn't even have to be reachable
        s.connect(('10.255.255.255', 1))
        IP = s.getsockname()[0]
    except Exception:
        IP = '127.0.0.1'
    finally:
        s.close()
    return IP

to get all ips you can use netifaces :

from netifaces import interfaces, ifaddresses, AF_INET
for ifaceName in interfaces():
    addresses = [i['addr'] for i in ifaddresses(ifaceName).setdefault(AF_INET, [{'addr':'No IP addr'}] )]
    print(' '.join(addresses))

output:

No IP addr
No IP addr
No IP addr
No IP addr
192.168.0.104
127.0.0.1
Tal Folkman
  • 2,368
  • 1
  • 7
  • 21
  • hi, it works only for the hostname you written. I want to choose the interface name and send it to the func – Ron Keinan Jan 10 '22 at 15:10
0

It returns the IP address and port as a tuple.

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
print(s.getsockname()[0])
0

scapy module has a func the does it - get_if_addr(iface_name) thanks for everyone

Ron Keinan
  • 27
  • 4