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:
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
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
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])
scapy module has a func the does it - get_if_addr(iface_name)
thanks for everyone
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.