How Python converts IP addresses to integers

Source: Internet
Author: User
The example in this article describes how Python translates IP addresses into integers. Share to everyone for your reference. The specific analysis is as follows:

Sometimes when we use the database to store IP addresses can be converted to integer storage IP address, integer occupies a small space, the index will be more convenient, the following Python code to customize a function of IP conversion to integer, very simple, the code also provides a method of converting integers to IP addresses.

Import socket, structdef Ip2long (IP): "" "  Convert a IP string to Long" "  Packedip = Socket.inet_aton ( IP)  return struct.unpack ("! L ", Packedip) [0]

For example, the IP address of www.jb51.net is: 61.129.51.27, call the Ip2long conversion function above:

Print (' www.jb51.net IP address is%s '%ip2long (' 61.129.51.27 '))

The output is:

Www.jb51.net IP Address is 1031877403

If you want to convert an integer to an IP address, you can use the following method:

Socket.inet_ntoa (Struct.pack ('! L ', 2130706433))

The output is:

' 127.0.0.1 '

Hopefully this article will help you with Python programming.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.