Python converts an IP address to an integer.

Source: Internet
Author: User

Python converts an IP address to an integer.

This example describes how python converts an IP address to an integer. Share it with you for your reference. The specific analysis is as follows:

Sometimes, when we use a database to store IP addresses, we can convert the IP addresses to integer storage. The integer storage space is small and the index is more convenient, the following python code defines a function for converting an ip address to an integer, which is very simple. The Code also provides a method for converting an integer to an ip address.

Import socket, structdef ip2long (ip): "" Convert an IP string to long "" packedIP = socket. inet_aton (ip) return struct. unpack ("! L ", packedIP) [0]

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

Print ('www .jb51.net ip address is % s' % ip2long ('61. 129.51.27 '))

Output result:

Www. jb51.net ip address is 1031877403

To convert an integer to an IP address, use the following method:

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

Output result:

'2017. 0.0.1'

I hope 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.