Get IP address from python

I am trying to get the ip address associated with the network interface without additional processes appearing on 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 get this error:

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

How can i solve this?

+4
source share
2 answers

Translate host to ip:

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

Get host by name:

import socket
print (socket.gethostbyname("www.goole.com"))
0
source
def get_ip_address():
    """
    Function used to find out current ip address of the server
    """ 
    # create a socket object
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.connect(("8.8.8.8",80))
    return sock.getsockname()[0]
    sock.close()
-1
source

Source: https://habr.com/ru/post/1693145/


All Articles