Python gets a summary of the native local IP address methods under Windows and Linux

  • 2020-04-02 14:43:53
  • OfStack

This example summarizes python's approach to getting native local IP addresses under Windows and Linux. Share with you for your reference. Specific analysis is as follows:

Python sockets contain a wealth of functions and methods to get the native IP address information, socket object gethostbyname method can get the native IP address according to the host name, socket object gethostbyname_ex method can get the native IP address list

The first method is obtained by the socket.gethostbyname method


import socket
localIP = socket.gethostbyname(socket.gethostname())# Get the local ip
print "local ip:%s "%localIP

The results are as follows:

'172.16.34.102'

Second method: get a list of native hostnames and IP addresses through the socket.gethostbyname_ex method


import socket
ipList = socket.gethostbyname_ex(socket.gethostname())
print(ipList)

The results are as follows:

(' China - 43226208 - c ', [], [' 192.168.5.196 '])

Both of these methods are also available under Linux, which also gets the native IP address through the following code


import socket
import fcntl
import struct
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])
  )[20:24])

I hope this article has helped you with your Python programming.


Related articles: