本文共 3009 字,大约阅读时间需要 10 分钟。
python获取主机ip
can be used to get the IP address from a hostname.
可用于从主机名获取IP地址。
The socket module is part of the Python core libraries, so we don’t need to install it separately.
socket模块是Python核心库的一部分,因此我们不需要单独安装它。
Python socket module gethostbyname()
function accepts hostname argument and returns the IP address in the string format.
Python套接字模块的gethostbyname()
函数接受主机名参数,并以字符串格式返回IP地址。
Here is a simple example in the Python interpreter to find out the IP address of some of the websites.
这是Python解释器中的一个简单示例,用于查找某些网站的IP地址。
# python3.7Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 16:52:21) [Clang 6.0 (clang-600.0.57)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> >>> import socket>>> socket.gethostbyname('journaldev.com')'45.79.77.230'>>> socket.gethostbyname('google.com')'172.217.166.110'>>>
Note: If the website is behind a load-balancer or working in the cloud, you might get a different result for the IP address lookup.
注意 :如果网站在负载均衡器后面或在云中运行,则IP地址查找可能会得到不同的结果。
For example, try to run the above command for google.com or facebook.com. If you are not in the same location as mine (India), chances are that you will get a different IP address as output.
例如,尝试对google.com或facebook.com运行以上命令。 如果您与我的位置不同(印度),则可能会获得不同的IP地址作为输出。
Let’s look at an example where we ask user to enter a website address and then print its IP address.
让我们看一个示例,其中要求用户输入一个网站地址,然后打印其IP地址。
import sockethostname = input("Please enter website address:\n")# IP lookup from hostnameprint(f'The {hostname} IP Address is {socket.gethostbyname(hostname)}')
Here is another example to pass the hostname as a to the script. The script will find the IP address and print it.
这是将主机名作为传递给脚本的另一个示例。 该脚本将找到IP地址并进行打印。
import socketimport sys# no error handling is done here, excuse me for thathostname = sys.argv[1]# IP lookup from hostnameprint(f'The {hostname} IP Address is {socket.gethostbyname(hostname)}')
Output:
输出 :
# python3.7 ip_address.py facebook.comThe facebook.com IP Address is 157.240.23.35
If the hostname doesn’t resolve to a valid IP address, socket.gaierror
is raised. We can catch this error in our program using block.
如果主机名不能解析为有效的IP地址,则会引发socket.gaierror
。 我们可以使用块在程序中捕获此错误。
Here is the updated script with exception handling for invalid hostname.
这是更新的脚本,其中包含对无效主机名的异常处理。
import socketimport syshostname = sys.argv[1]# IP lookup from hostnametry: ip = socket.gethostbyname(hostname) print(f'The {hostname} IP Address is {ip}')except socket.gaierror as e: print(f'Invalid hostname, error raised is {e}')
Output:
输出:
# python3.7 ip_address.py jasjdkks.com Invalid hostname, error raised is [Errno 8] nodename nor servname provided, or not known#
Reference:
参考 :
翻译自:
python获取主机ip
转载地址:http://ywlzd.baihongyu.com/