Python 查找客户端的IP地址
在本教程中,我们将使用socket模块在Python中查找客户端的IP地址。每台笔记本电脑、手机、平板等设备都有自己独特的IP地址。我们将使用socket模块来查找它。让我们来看看找出设备的IP地址的步骤。
算法
- 导入socket模块。
- 使用socket.gethostname()方法获取主机名并将其存储在一个变量中。
- 通过将主机名作为参数传递给socket.gethostbyname()方法来查找IP地址,并将其存储在一个变量中。
- 打印IP地址。
让我们为上述算法编写代码。
示例
## 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
结论
如果对教程有任何疑问,请在评论部分提到。