This example summarizes Python's approach to obtaining native local IP addresses under Windows and Linux. Share to everyone for your reference. The specific analysis is as follows:
Python socket contains a wealth of functions and methods to obtain the IP address information of the machine, the gethostbyname method of the socket object can obtain the native IP address according to the host name, the socket object's Gethostbyname_ The ex method can obtain a list of all IP addresses for this machine
The first method: through the Socket.gethostbyname method of obtaining
Import socket
Localip = Socket.gethostbyname (Socket.gethostname ()) #得到本地ip
print "Local ip:%s"%localip
The returned results are as follows:
' 172.16.34.102 '
The second method: Obtain the local host name and IP Address List by SOCKET.GETHOSTBYNAME_EX method
Import socket
IPList = SOCKET.GETHOSTBYNAME_EX (Socket.gethostname ())
print (IPList)
The returned results are as follows:
(' china-43226208c ', [], [' 192.168.5.196 '])
Both of these methods can be used under Linux, Linux also to obtain the local 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 will help you with your Python programming.