IP地址是一个32位的二进制数,通常被分割为4个“8位二进制数”(也就是4个字节)。IP地址通常用“点分十进制”表示成(a.b.c.d)的形式,其中,a,b,c,d都是0~255之间的十进制整数。例:点分十进IP地址(100.4.5.6),实际上是32位二进制数(01100100.00000100.00000101.00000110)。
根据这些特性就能解析出ip地址
代码:
- #!/usr/bin/python
- # -*- coding: UTF-8 -*-
- print "IP str转IP int 解决函数解决方案"
- def to_int(ip_str):
- print "ip_str: ", ip_str
- i = 0
- ip_int = 0
- for ip_part in ip_str.split('.')[::-1]:
- # for ip_part in ip_str.split('.'):
- print ip_part
- ip_int = ip_int + int(ip_part) * 256**i
- i += 1
- print "ip_int: ", ip_int
- return ip_int
-
-
- ip_int = to_int("7.91.205.21")
输出:
- IP str转IP int 解决函数解决方案
- ip_str: 7.91.205.21
- 21
- 205
- 91
- 7
- ip_int: 123456789
- print "IP str转IP int 一行lambda 解决"
- ip_str_to_int = lambda x: sum([256**j*int(i) for j,i in enumerate(x.split('.')[::-1])])
- print ip_str_to_int('7.91.205.21')
代码:
- print "IP int转IP str 函数解决方案"
- def to_ip(ip_int):
- s = []
- for i in range(4):
- ip_part = str(ip_int % 256)
- s.append(ip_part)
- ip_int /= 256
- print "ip_part: ", ip_part
- print s
- print s[::-1]
- return '.'.join(s[::-1])
-
-
- print to_ip(ip_int=123456789)
输出:
- IP int转IP str 一行lambda 解决
- ip_part: 21
- ip_part: 205
- ip_part: 91
- ip_part: 7
- ['21', '205', '91', '7']
- ['7', '91', '205', '21']
- 7.91.205.21
- print "IP int转IP str 一行lambda 解决"
- ip_int_to_str = lambda x: '.'.join([str(x/(256**i) % 256) for i in range(4)][::-1])
- print ip_int_to_str(123456789)
- #1、 开多次方的写法
- print "2**3: ", 2**3 # 8
- print "3**4: ", 3**4 # 81
-
- tmp_list = [1,2,3,4,5,6,7]
-
- #2、 提示 [::-1]是数组元素反转
- print "tmp_list: ", tmp_list
- # tmp_list: [1, 2, 3, 4, 5, 6, 7]
- print "reverse tmp_list:", tmp_list[::-1]
- # reverse tmp_list: [7, 6, 5, 4, 3, 2, 1]
-
- #3、打印下表小于end_pos的元素[0,end_pos)
- end_pos=2
- for e in tmp_list[:end_pos]:
- print e
- '''
- 1
- 2
- '''
- #4、打印list中一段元素[start_pos,end_pos)
- start_pos=1
- end_pos=4
- for e in tmp_list[start_pos:end_pos]:
- print e
- '''
- 2
- 3
- 4
- '''
- #5、从下标0开始,每隔 正step元素 打印元素
- step=2
- for e in tmp_list[::step]:
- print e
- '''
- 1
- 3
- 5
- 7
- '''
- #6、从下标len(tmp_list)-1开始,每隔 负step元素 打印元素
- step=-2
- for e in tmp_list[::step]:
- print e
- '''
- 7
- 5
- 3
- 1
- '''
- #7、 enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,
- # 一般用在 for 循环当中。Python 2.3. 以上版本可用,2.6 添加 start 参数。
- for j, i in enumerate('7.91.205.21'.split('.')):
- print j, i
- '''
- 0 7
- 1 91
- 2 205
- 3 21
- '''
- for j, i in enumerate('7.91.205.21'.split('.')[::-1]):
- print j, i
- '''
- 0 21
- 1 205
- 2 91
- 3 7
- '''
- package com.guozz.mianshiti.test19;
-
- import java.net.InetAddress;
-
- public class IPv4Util {
-
- private final static int INADDRSZ = 4;
-
- /**
- * 把IP地址转化为字节数组
- * @param ipAddr
- * @return byte[]
- */
- public static byte[] ipToBytesByInet(String ipAddr) {
- try {
- return InetAddress.getByName(ipAddr).getAddress();
- } catch (Exception e) {
- throw new IllegalArgumentException(ipAddr + " is invalid IP");
- }
- }
-
- /**
- * 把IP地址转化为int
- * @param ipAddr
- * @return int
- */
- public static byte[] ipToBytesByReg(String ipAddr) {
- byte[] ret = new byte[4];
- try {
- String[] ipArr = ipAddr.split("\\.");
- ret[0] = (byte) (Integer.parseInt(ipArr[0]) & 0xFF);
- ret[1] = (byte) (Integer.parseInt(ipArr[1]) & 0xFF);
- ret[2] = (byte) (Integer.parseInt(ipArr[2]) & 0xFF);
- ret[3] = (byte) (Integer.parseInt(ipArr[3]) & 0xFF);
- return ret;
- } catch (Exception e) {
- throw new IllegalArgumentException(ipAddr + " is invalid IP");
- }
-
- }
-
- /**
- * 字节数组转化为IP
- * @param bytes
- * @return int
- */
- public static String bytesToIp(byte[] bytes) {
- return new StringBuffer().append(bytes[0] & 0xFF).append('.').append(
- bytes[1] & 0xFF).append('.').append(bytes[2] & 0xFF)
- .append('.').append(bytes[3] & 0xFF).toString();
- }
-
- /**
- * 根据位运算把 byte[] -> int
- * @param bytes
- * @return int
- */
- public static int bytesToInt(byte[] bytes) {
- int addr = bytes[3] & 0xFF;
- addr |= ((bytes[2] << 8) & 0xFF00);
- addr |= ((bytes[1] << 16) & 0xFF0000);
- addr |= ((bytes[0] << 24) & 0xFF000000);
- return addr;
- }
-
- /**
- * 把IP地址转化为int
- * @param ipAddr
- * @return int
- */
- public static int ipToInt(String ipAddr) {
- try {
- return bytesToInt(ipToBytesByInet(ipAddr));
- } catch (Exception e) {
- throw new IllegalArgumentException(ipAddr + " is invalid IP");
- }
- }
-
- /**
- * ipInt -> byte[]
- * @param ipInt
- * @return byte[]
- */
- public static byte[] intToBytes(int ipInt) {
- byte[] ipAddr = new byte[INADDRSZ];
- ipAddr[0] = (byte) ((ipInt >>> 24) & 0xFF);
- ipAddr[1] = (byte) ((ipInt >>> 16) & 0xFF);
- ipAddr[2] = (byte) ((ipInt >>> 8) & 0xFF);
- ipAddr[3] = (byte) (ipInt & 0xFF);
- return ipAddr;
- }
-
- /**
- * 把int->ip地址
- * @param ipInt
- * @return String
- */
- public static String intToIp(int ipInt) {
- return new StringBuilder().append(((ipInt >> 24) & 0xff)).append('.')
- .append((ipInt >> 16) & 0xff).append('.').append(
- (ipInt >> 8) & 0xff).append('.').append((ipInt & 0xff))
- .toString();
- }
-
- /**
- * 把192.168.1.1/24 转化为int数组范围
- * @param ipAndMask
- * @return int[]
- */
- public static int[] getIPIntScope(String ipAndMask) {
-
- String[] ipArr = ipAndMask.split("/");
- if (ipArr.length != 2) {
- throw new IllegalArgumentException("invalid ipAndMask with: "
- + ipAndMask);
- }
- int netMask = Integer.valueOf(ipArr[1].trim());
- if (netMask < 0 || netMask > 31) {
- throw new IllegalArgumentException("invalid ipAndMask with: "
- + ipAndMask);
- }
- int ipInt = IPv4Util.ipToInt(ipArr[0]);
- int netIP = ipInt & (0xFFFFFFFF << (32 - netMask));
- int hostScope = (0xFFFFFFFF >>> netMask);
- return new int[] { netIP, netIP + hostScope };
-
- }
-
- /**
- * 把192.168.1.1/24 转化为IP数组范围
- * @param ipAndMask
- * @return String[]
- */
- public static String[] getIPAddrScope(String ipAndMask) {
- int[] ipIntArr = IPv4Util.getIPIntScope(ipAndMask);
- return new String[] { IPv4Util.intToIp(ipIntArr[0]),
- IPv4Util.intToIp(ipIntArr[0]) };
- }
-
- /**
- * 根据IP 子网掩码(192.168.1.1 255.255.255.0)转化为IP段
- * @param ipAddr ipAddr
- * @param mask mask
- * @return int[]
- */
- public static int[] getIPIntScope(String ipAddr, String mask) {
-
- int ipInt;
- int netMaskInt = 0, ipcount = 0;
- try {
- ipInt = IPv4Util.ipToInt(ipAddr);
- if (null == mask || "".equals(mask)) {
- return new int[] { ipInt, ipInt };
- }
- netMaskInt = IPv4Util.ipToInt(mask);
- ipcount = IPv4Util.ipToInt("255.255.255.255") - netMaskInt;
- int netIP = ipInt & netMaskInt;
- int hostScope = netIP + ipcount;
- return new int[] { netIP, hostScope };
- } catch (Exception e) {
- throw new IllegalArgumentException("invalid ip scope express ip:"
- + ipAddr + " mask:" + mask);
- }
-
- }
-
- /**
- * 根据IP 子网掩码(192.168.1.1 255.255.255.0)转化为IP段
- * @param ipAddr ipAddr
- * @param mask mask
- * @return String[]
- */
- public static String[] getIPStrScope(String ipAddr, String mask) {
- int[] ipIntArr = IPv4Util.getIPIntScope(ipAddr, mask);
- return new String[] { IPv4Util.intToIp(ipIntArr[0]),
- IPv4Util.intToIp(ipIntArr[0]) };
- }
-
- /**
- * @param args
- * @throws Exception
- */
- public static void main(String[] args) throws Exception {
- String ipAddr = "192.168.8.1";
-
- byte[] bytearr = IPv4Util.ipToBytesByInet(ipAddr);
-
- StringBuffer byteStr = new StringBuffer();
-
- for (byte b : bytearr) {
- if (byteStr.length() == 0) {
- byteStr.append(b);
- } else {
- byteStr.append("," + b);
- }
- }
- System.out.println("IP: " + ipAddr + " ByInet --> byte[]: [ " + byteStr
- + " ]");
-
- bytearr = IPv4Util.ipToBytesByReg(ipAddr);
- byteStr = new StringBuffer();
-
- for (byte b : bytearr) {
- if (byteStr.length() == 0) {
- byteStr.append(b);
- } else {
- byteStr.append("," + b);
- }
- }
- System.out.println("IP: " + ipAddr + " ByReg --> byte[]: [ " + byteStr
- + " ]");
-
- System.out.println("byte[]: " + byteStr + " --> IP: "
- + IPv4Util.bytesToIp(bytearr));
-
- int ipInt = IPv4Util.ipToInt(ipAddr);
-
- System.out.println("IP: " + ipAddr + " --> int: " + ipInt);
-
- System.out.println("int: " + ipInt + " --> IP: "
- + IPv4Util.intToIp(ipInt));
-
- String ipAndMask = "192.168.1.1/24";
-
- int[] ipscope = IPv4Util.getIPIntScope(ipAndMask);
- System.out.println(ipAndMask + " --> int地址段:[ " + ipscope[0] + ","
- + ipscope[1] + " ]");
-
- System.out.println(ipAndMask + " --> IP 地址段:[ "
- + IPv4Util.intToIp(ipscope[0]) + ","
- + IPv4Util.intToIp(ipscope[1]) + " ]");
-
- String ipAddr1 = "192.168.1.1", ipMask1 = "255.255.255.0";
-
- int[] ipscope1 = IPv4Util.getIPIntScope(ipAddr1, ipMask1);
- System.out.println(ipAddr1 + " , " + ipMask1 + " --> int地址段 :[ "
- + ipscope1[0] + "," + ipscope1[1] + " ]");
-
- System.out.println(ipAddr1 + " , " + ipMask1 + " --> IP地址段 :[ "
- + IPv4Util.intToIp(ipscope1[0]) + ","
- + IPv4Util.intToIp(ipscope1[1]) + " ]");
-
- }
- }