Python integer and IP address translation [go]

Source: Internet
Author: User

We sometimes swap an integer with an IP address, and the Python code makes it simple.
Converts an integer, such as 2000000, into an IP address
Import Socket Import struct>>> int_ip = 123456789>>> ip = Socket.inet_ntoa (struct.pack ('I ', socket.htonl (int_ip))      #int to IP address'7.91.205.21  '>>> Socket.ntohl (Struct.unpack ("I", Socket.inet_aton (str (IP))) [ 0])     #IP address to int123456789L

Actually this is the conversion of the binary number, we can write our own code

# Integer to IP address format
def ch1 (num):              = []             for in Range (                  4):                  %256)/=        return  '. '. Join (s[::-1])>>> ch1 (123456789)'7.91.205.21 '

In a lambda way, integer TOIP address a line of code to fix

Lambda ' . '  for  in range (3,-1,-1)])>>> CH2 (123456789)'7.91.205.21' 

In lambda mode, IP addresses are converted to integers

Lambda  for  in Enumerate (X.split ('. ') [:: -1]]) >>> CH3 ('7.91.205.21')123456789

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.