Python gets ip address from URL

       (Creating is not easy, remember to like it)

         In the information age, we often need to obtain IP addresses from URLs. I searched for a way to achieve it on the Internet for more than ten minutes, but it either couldn't run or was too bloated. So I had a flash of inspiration and thought of a simple method.

        Since the gethostbyname function of the socket module can only receive the host name, first write a function to obtain the host name from the URL.

        A normal URL always consists of several parts:

        <protocol>://<server type> . <domain name>/<directory>/<file name>

        Such as https://www.baidu.com/ , https://www.csdn.net/

        And the hostname we need is the string in the middle:

        <server type> . <domain name>

        Namely www.baidu.com , www.csdn.net

        It can be found that the host name is between the first "//" and the first "/". From this, we can easily write a function to separate the hostname from the URL.

def gethost(url):
    output = ''
    if '//' in url:
        output = url.split('//')[1]
        if '/' in output:
            output = output.split('/')[0]
    elif '/' in url:
        output = url.split('/')[0]
    return output

        This is a simple function that only works as expected if the input URL is relatively normal. But it is good enough for URLs copied and pasted from the browser. Encapsulate it if necessary, or separating the hostnames can be done using regular expressions.

        Then bring the return value into gethostbyname to get the result..

        The complete procedure is as follows:

from socket import gethostbyname

def gethost(url):
    output = ''
    if '//' in url:
        output = url.split('//')[1]
        if '/' in output:
            output = output.split('/')[0]
    elif '/' in url:
        output = url.split('/')[0]
    return output

def getip(url):
    return gethostbyname(gethost(url))

        You can get the ip from the URL by calling the getip function.

        The test is as follows:

url = (
    'https://www.baidu.com/',
    'https://www.csdn.net/',
    'https://mirrors.tuna.tsinghua.edu.cn/#'
)

for i in url:
    print(i, getip(i))

        result:

f505137e49574aefb09552f482929cab.png

References:

 

Baidu Encyclopedia - Verification

 

 

Guess you like

Origin blog.csdn.net/m0_71713477/article/details/127174636