从argv fai获取IP

2024-04-25 23:04:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试获取args提供的网站的ip地址。当我直接在源代码中尝试使用网站时,比如“url='https://google.com”,它可以工作,但是当我尝试使用“url=sys.argv[1]”,它失败了

当我打印“url=sys.argv[1]”时,我得到了所需的网站。我试图str(url)它,但它也不工作

代码如下:

import socket
import sys

# Params
url = sys.argv[1]
# url = str(sys.argv[1])

print (type(url))   # I get the desired url

s = socket.socket()

# Get IP
ip = socket.gethostbyname(url)

# Print Infos
print ('IP Adress : ' + ip + '\n' + 15*'-')

s.close()

你知道吗

谢谢,快把我逼疯了


Tags: httpsimportipurl源代码网站地址google
1条回答
网友
1楼 · 发布于 2024-04-25 23:04:31

这是因为你在传递https//:;您需要删除它:

In [3]: ip = socket.gethostbyname("http://google.com")
                                     -
gaierror                                  Traceback (most recent call last)
<ipython-input-3-7466d856e904> in <module>()
  > 1 ip = socket.gethostbyname("http://google.com")

相反,请尝试:

In [4]: ip = socket.gethostbyname("google.com")

In [5]: ip
Out[5]: '172.217.25.238'

注意,您还需要删除任何后面的斜杠,例如,删除google.com/中的/

如果您查看man gethostbyname,您将看到您正在发出一个DNS请求:

The gethostbyname() function returns a structure of type hostent for the given host name. Here name is either a hostname or an IPv4 address in standard dot notation (as for inet_addr(3)).

因此,您需要确保清除传递给该函数调用的任何内容

相关问题 更多 >