Python-ip conversion between an address and an integer

Source: Internet
Author: User

1. Convert Integers to IP:

Idea: Convert IP address to unsigned 32-bit binary, and then 8 bits to divide, every 8 bits into decimal.

#!usr/bin/python2#Encoding=utf-83#1. Converting integers to 32-bit unsigned binary4defInttoip (num):5 S = []  6 g = []  7 h = []  8 forIinchRange (32):  9 A = num%2 10S.insert (0,a)num = NUM/2 12Prints13#2. Divide every 8 bits, convert 4 8-bit binary into decimal, plus. Connect. 14 forIinchXrange (0,32,8): G.append (s[i:i+8]) 16Printg17 forTempinchg:sum =0j =020 forTemp2inchTemp:sum = sum + temp2* (2** (7-j))J + = 1 23Printsum24h.append (str (sum))25return '.'. Join (H[::1]) A=inttoip (123456789) 27PrintA

2. Convert the IP address to an integer:

Idea: Convert four bits of IP to 8-bit binary, go to "." After the integration, and then converted into decimal.

#!usr/bin/python2#Encoding=utf-83#converts an IP address to a numeric string, such as "123456789" after 7.91.205.21 conversion4#1. Split, 2. Multiply the first bit by 256**4, the second is multiplied by 256**3, the third is multiplied by the 256**2, the fourth bit is multiplied by 256, and the result is added .5defiptoint (num):6#1. Convert the IP address to a 32-bit binary. 7 s = num.split ('.')  8 h = []  9 g = [] 10 forTempinchS:11 while(temp!=0):temp =Int (temp)A = temp% 2 14H.insert (0,a)temp = TEMP/2 16ifLen (h)! = 8: 17 forIinchRange (8-Len (h)):18H.insert (0,0)19g.extend (h)h = [] 21st#Print G22#2. Convert the binary into integers:sum =0j =025 forTemp2inchg:sum = sum + temp2* (2** (31-j))J + = 1 28PrintsumIptoint ("7.91.205.21")

Note: Beginner python, the code is a bit low, please forgive me!

Python-ip conversion between an address and an integer

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.