使用Python程序查找客户端的IP地址

在本教程中,我们将使用Python中套接字模块找到客户端的IP地址 。每个笔记本电脑,手机,平板电脑等都有其唯一的IP地址。我们将使用套接字模块找到它。让我们看看找出设备IP地址的步骤 。

算法

1. Import the socket module.
2. Get the hostname using the socket.gethostname() method and store it in a variable.
3. Find the IP address by passing the hostname as an argument to the
socket.gethostbyname() method and store it in a variable.
4. Print the IP address.

让我们为上述算法编写代码。

示例

## importing socket module
import socket
## getting the hostname by socket.gethostname() method
hostname = socket.gethostname()
## getting the IP address using socket.gethostbyname() method
ip_address = socket.gethostbyname(hostname)
## printing the hostname and ip_address
print(f"Hostname: {hostname}")
print(f"IP Address: {ip_address}")

输出结果

如果运行上述程序,将得到以下输出。

Hostname: DESKTOP-A0PM5GD
IP Address: 192.168.43.15

结论