получить локальный ip компьютера

import socket

hostname = socket.gethostname()
local_ip = socket.gethostbyname(hostname)

получаю socket.gaierror: [Errno 11004] getaddrinfofailed
как получить ip?
в C# делаю так и все работает

ipEntry = Dns.GetHostByName(Dns.GetHostName());
addr = ipEntry.AddressList;
addr[0]; //192.168.0.158

Ответы (4 шт):

Автор решения: eri

hostname не записан ни в etc/hosts, ни в winbind, ни в какомто ещё ресолвере - поэтому возникает такая ошибка. В настроенных компьютерах там обычно 127.0.0.1

Запусти любой UDP сокет на любой внешний адрес и ядро построит маршрут. На сокете будет адрес который смаршрутизирован в данном направлении.

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

Запросы никуда не отправляются

→ Ссылка
Автор решения: Alex Zab

Используйте бибилиотеку geocoder, Установить можно здесь https://pypi.org/project/geocoder/ с помощью команды pip install geocoder

# IP компьютера (g.ip)
g = geocoder.ip('me')
print("Your IP adress is..." + str(g.ip))

# Вся инфа по IP (g.json)
g = geocoder.ip('me')
print(str(g.json))

# Имя провайдера (g.hostname)
g = geocoder.ip('me')
print("Your hostname is..." + str(g.hostname))

# Название улицы (g.street)
g = geocoder.ip('me')
print("Your street name is..." + str(g.street))

# Почтовый код (g.postal)
g = geocoder.ip('me')
print("Your postcode number is..." + str(g.postal))

# Номер дома (g.housenumber)
g = geocoder.ip('me')
print("Your house number is..." + str(g.housenumber))

# Страна (g.country)
g = geocoder.ip('me')
print("Your country is..." + str(g.country))

# Город (g.city)
g = geocoder.ip('me')
print("Your city is..." + str(g.city))

# Штат (g.state)
g = geocoder.ip('me')
print("Your state is..." + str(g.state))

# Координаты (g.osm)
g = geocoder.ip('me')
print(str(g.osm))
→ Ссылка
Автор решения: Victor VosMottor

А еще так (pip3 install 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('%s: %s' % (ifaceName, ', '.join(addresses)))
→ Ссылка
Автор решения: Victor VosMottor

Только под windows:

def getIPAddresses():
      from ctypes import Structure, windll, sizeof
      from ctypes import POINTER, byref
      from ctypes import c_ulong, c_uint, c_ubyte, c_char
      MAX_ADAPTER_DESCRIPTION_LENGTH = 128
      MAX_ADAPTER_NAME_LENGTH = 256
      MAX_ADAPTER_ADDRESS_LENGTH = 8
      class IP_ADDR_STRING(Structure):
          pass
      LP_IP_ADDR_STRING = POINTER(IP_ADDR_STRING)
      IP_ADDR_STRING._fields_ = [
          ("next", LP_IP_ADDR_STRING),
          ("ipAddress", c_char * 16),
          ("ipMask", c_char * 16),
          ("context", c_ulong)]
      class IP_ADAPTER_INFO (Structure):
          pass
      LP_IP_ADAPTER_INFO = POINTER(IP_ADAPTER_INFO)
      IP_ADAPTER_INFO._fields_ = [
          ("next", LP_IP_ADAPTER_INFO),
          ("comboIndex", c_ulong),
            ("adapterName", c_char * (MAX_ADAPTER_NAME_LENGTH + 4)),
          ("description", c_char * (MAX_ADAPTER_DESCRIPTION_LENGTH + 4)),
          ("addressLength", c_uint),
          ("address", c_ubyte * MAX_ADAPTER_ADDRESS_LENGTH),
          ("index", c_ulong),
          ("type", c_uint),
          ("dhcpEnabled", c_uint),
          ("currentIpAddress", LP_IP_ADDR_STRING),
          ("ipAddressList", IP_ADDR_STRING),
          ("gatewayList", IP_ADDR_STRING),
          ("dhcpServer", IP_ADDR_STRING),
          ("haveWins", c_uint),
          ("primaryWinsServer", IP_ADDR_STRING),
          ("secondaryWinsServer", IP_ADDR_STRING),
          ("leaseObtained", c_ulong),
          ("leaseExpires", c_ulong)]
      GetAdaptersInfo = windll.iphlpapi.GetAdaptersInfo
      GetAdaptersInfo.restype = c_ulong
      GetAdaptersInfo.argtypes = [LP_IP_ADAPTER_INFO, POINTER(c_ulong)]
      adapterList = (IP_ADAPTER_INFO * 10)()
      buflen = c_ulong(sizeof(adapterList))
      rc = GetAdaptersInfo(byref(adapterList[0]), byref(buflen))
      if rc == 0:
          for a in adapterList:
              adNode = a.ipAddressList
              while True:
                  ipAddr = adNode.ipAddress
                  if ipAddr:
                      yield ipAddr
                  adNode = adNode.next
                  if not adNode:
                      break

source

→ Ссылка