This article summarizes Python's method of acquiring 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 of the computer, the socket object GetHostByName method can be based on the host name to obtain a native IP address, socket object Gethostbyname_ The ex method can get a list of all IP addresses in the machine
The first method: The Socket.gethostbyname method is used to obtain
Import Socketlocalip = Socket.gethostbyname (Socket.gethostname ()) #得到本地ipprint "Local ip:%s"%localip
The returned results are as follows:
' 172.16.34.102 '
Second method: Get a list of native hostname and IP address by socket.gethostbyname_ex method
Import socketiplist = SOCKET.GETHOSTBYNAME_EX (Socket.gethostname ()) print (IPList)
The returned results are as follows:
(' china-43226208c ', [], [' 192.168.5.196 '])
The above two methods can also be used under Linux, Linux also with the following code to get the native IP address
Import Socketimport fcntlimport structdef 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])
Hopefully this article will help you with Python programming.