python get the ip of the machine

Method 1: 
Usually socket.gethostbyname(), the IP address of the machine can be obtained by using the method, but sometimes it cannot be obtained (for example, the host name is not set correctly). The sample code is as follows:

1  import socket
 2  #Get the local computer name 
3 myname = socket.gethostname()
 4  #Get the local ip 
5 myaddr = socket.gethostbyname(myname)
 6  print (myaddr)

Method Two:

This method gets the IP of the local server. without any dependencies.

Instead, it is implemented using the UDP protocol, which generates a UDP packet, puts its own IP into the UDP protocol header, and then obtains the IP of the machine from the UDP packet.

This method does not actually send packets to the outside, so it is invisible to the packet capture tool. However, it will apply for a UDP port, so it will be time-consuming if it is called frequently. Here, if necessary, the IP queried can be cached, and the performance can be greatly improved.

 1 import socket
 2 
 3 def get_host_ip():
 4     """
 5     查询本机ip地址
 6     :return: ip
 7     """
 8     try:
 9         s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
10         s.connect(('8.8.8.8', 80))
11         ip = s.getsockname()[0]
12     finally:
13         s.close()
14 
15     return ip
16 
17 if __name__ == '__main__':
18     print(get_host_ip())

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325212079&siteId=291194637