This article mainly introduces how to obtain the local IP address of a python machine in windows and linux. the instance analyzes the IP address acquisition technique of Python, which has some reference value, for more information about how to obtain the local IP address of python in windows and linux, see the example in this article. 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.