7

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
  • 69
  • 1
  • 1
  • 6

1 Answers1

3

Translate host to ip :

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

To get host by name :

import socket
print (socket.gethostbyname("www.goole.com"))
An0n
  • 705
  • 6
  • 19