SoFunction
Updated on 2024-11-17

Python how to elegantly get the local IP method

I've seen a lot of code to get the local IP of the server, and personally I don't think it's very good, such as these

NOT RECOMMENDED: Guessing to get a local IP address.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import socket
import fcntl
import struct

def get_ip_address(ifname):
  s = (socket.AF_INET, socket.SOCK_DGRAM)
  return socket.inet_ntoa((
    (),
    0x8915, # SIOCGIFADDR
    ('256s', ifname[:15])
  )[20:24])

print "br1 = "+ get_ip_address('br1')
print "lo = " + get_ip_address('lo')
print "virbr0 = " + get_ip_address('virbr0')

This type of code comes with guesswork behavior.

If the machine has only eth0 or only bond0 with an IP on it, then this type of code is likely to fail and is not easily portable to other platforms.

Not recommended: get local IP via hostname

import socket
print((()))

# There's a possibility that this could happen
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
: [Errno -2] Name or service not known

This method is to get the hostname, and then through the hostname to countercheck the machine's IP. this method is also not recommended. Because many machines do not standardize the hostname setting.

Another thing is that some servers will add the address of the hostname of the local machine in /etc/hosts, this practice is not impossible, but if you set it to 127.0.0.1, then all the IPs obtained will be this address.

Getting the local IP via UDP, the most elegant method I've seen so far.

This method is the most elegant way to get the IP of a local server that I've seen so far. There are no dependencies and no guessing about the network device information on the machine.

And it's done using the UDP protocol. Generate a UDP packet, put your IP as in the UDP protocol header, and then get the local IP from the UDP packet.

This method does not really send packets to the outside, so the packet capture tool is not visible. But will apply for a UDP port, so if often called will be more time-consuming, here if you need to query the IP to the cache, performance can be greatly improved.

# One line call in the shell to get the local IP.
python -c "import socket;print([((('8.8.8.8', 53)), ()[0], ()) for s in [(socket.AF_INET, socket.SOCK_DGRAM)]][0][1])"
10.12.189.16

# Can be encapsulated into functions that Python programs can easily call
import socket

def get_host_ip():
  try:
    s = (socket.AF_INET, socket.SOCK_DGRAM)
    (('8.8.8.8', 80))
    ip = ()[0]
  finally:
    ()

  return ip

This is the whole content of this article.