How to get hostname and IP address in Python

In Python, you can obtain local and remote host names and IP addresses through the gethostname(), getfqdn(), and gethostbyname() methods in the socket module.

1 Get local and remote hostnames

1.1 Get the local host name

You can get the local host name, which is the host name of the local machine, through the gethostname() method. The code is as follows.

host_name = socket.gethostname()
print('本机主机名是:%s'%host_name)

At this time, the running effect is shown in Figure 1.

Figure 1 Local host name

Among them, the local host name obtained by the gethostname() method is in string format.

1.2 Get the remote host name

Use the getfqdn() method to obtain the remote host name, and use the IP address of the remote host as a parameter of the method. The code is as follows.

remote_host_name = socket.getfqdn('192.168.147.129')
print('IP地址是192.168.147.129的远程主机,其主机名是:%s'%remote_host_name)

At this time, the running effect is shown in Figure 2.

Figure 2 Remote host name

Note 1. To successfully obtain the remote host name, you need to ensure that the local host and the remote host are connected on the network.

2 Get the IP addresses of local and remote hosts

You can obtain the IP address of the local or remote host through the gethostbyname() method. You only need to use the host name of the local or remote host as a parameter of this method.

ip_address = socket.gethostbyname(host_name)
print('本机的IP地址是%s'%ip_address)
remote_host_addr = socket.gethostbyname(remote_host_name)
print('名为WIN-EC116TBKMQH的主机,其IP地址是:%s'%remote_host_addr)

In the above code, host_name, which is the local host name obtained in "1 Get the local and remote host name", is passed as a parameter to the gethostbyname() method to get the IP address of the local host; change "1 Get the local and remote host name" The remote host name obtained in "Host Name" is passed as a parameter to the gethostbyname() method to obtain the IP address of the remote host. The running effect is shown in Figure 3.

Figure 3 Obtain IP address

3 Get the IP address of the website

In addition to getting the IP addresses of local and remote hosts, the gethostbyname() method can also get the IP address of the website. Just pass the domain name of the website as a parameter to this method. The following code is to obtain the IP address of Baidu website.

baidu_addr = socket.gethostbyname('www.baidu.com')
print('百度网站的IP地址是:%s'%baidu_addr)

Its operation effect is shown in Figure 4.

Figure 4 Obtaining the IP address of Baidu website

Note 2: Before using the above code, you need to import the socket module, that is

import socket

Guess you like

Origin blog.csdn.net/hou09tian/article/details/133071156