Get IP address from python

13,227

Translate host to ip :

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

To get host by name :

import socket
print (socket.gethostbyname("www.goole.com"))
Share:
13,227
lichb0rn
Author by

lichb0rn

Updated on June 22, 2022

Comments

  • lichb0rn
    lichb0rn almost 2 years

    I'm trying to get the ip address associated with network interface without spawning additional processes in Linux:

    def get_ip_address(ifname):
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        return socket.inet_ntoa(fcntl.ioctl(
            s.fileno(), 0x8915,  # SIOCGIFADDR
            struct.pack('256s', ifname[:15].encode('utf-8'))
            )[20:24])
    

    But always getting this error:

    struct.pack('256s', ifname[:15].encode('utf-8'))
    OSError: [Errno 99] Cannot assign requested address
    

    How can I solve this?

  • lichb0rn
    lichb0rn about 6 years
    And what if I have multiple network interfaces without any internet connection?
  • Ricky Levi
    Ricky Levi about 5 years
    the first comment returns 127.0.0.1 ....
  • Mohith7548
    Mohith7548 about 5 years
    It always returns the output as '127.0.0.1'. But I need both public and private IP addresses.
  • An0n
    An0n about 5 years
    Do you have a working internet connection?