Python methods for obtaining local IP addresses in windows and linux, pythonlinux
This example summarizes how python obtains the local IP address of a local machine in windows and linux. Share it with you for your reference. The specific analysis is as follows:
Python's socket contains rich functions and methods to obtain the IP address information of the Local Machine. The gethostbyname method of the socket object can obtain the IP address of the Local Machine Based on the host name. The gethostbyname_ex method of the socket object can obtain the list of all IP addresses of the local machine.
Method 1: Use socket. gethostbyname to obtain
Import socketlocalIP = socket. gethostbyname (socket. gethostname () # obtain the local ipprint "local ip: % s" % localIP
The returned results are as follows:
'2017. 16.34.102'
Method 2: Use socket. gethostbyname_ex to obtain the Host Name and IP address list of the local machine.
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 in linux. in linux, the local IP address is also obtained using the following code.
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])
I hope this article will help you with Python programming.