IP转int 和int 转IP 的实现(Python & Java)

1、python IP转int 和int 转IP

1.1、IP地址意义

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地址

1.2、IP str转IP int 解决函数解决方案

代码:

#!/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

1.3、IP str转IP int 一行lambda 解决

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')

1.4、IP int转IP str 函数解决方案

代码:

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

1.5、IP int转IP str 一行lambda 解决

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.7、python list间隔输出,倒序输出、enumerate() 函数介绍

#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
'''

参考:https://blog.csdn.net/nio_lu/article/details/93738956

2、Java把IP地址转换成INT型存储(考察的位运算)

 java ip转Int 和 java Ip转Int

2.1、基本知识点 

IP ——> 整数:

  • 把IP地址转化为字节数组

  • 通过左移位(<<)、与(&)、或(|)这些操作转为int

整数 ——> IP:

  • 将整数值进行右移位操作(>>>),右移24位,再进行与操作符(&)0xFF,得到的数字即为第一段IP。

  • 将整数值进行右移位操作(>>>),右移16位,再进行与操作符(&)0xFF,得到的数字即为第二段IP。

  • 将整数值进行右移位操作(>>>),右移8位,再进行与操作符(&)0xFF,得到的数字即为第三段IP。

  • 将整数值进行与操作符(&)0xFF,得到的数字即为第四段IP。

2.2、java代码示例

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]) + " ]");
 
    }
}

参考:https://blog.csdn.net/paul342/article/details/48374237

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Socket编程是一种在计算机网络中实现进程通信的方法。在Java中,可以使用java.net包中的Socket类来创建一个客户端。编写Socket客户端程序的过程包括以下几个步骤: 1. 导入必要的类:导入java.net包中的Socket和IOException类。 2. 创建Socket对象:使用Socket构造函数创建一个Socket对象。构造函数需要传入服务器的IP地址和端口号。 3. 获取输入输出流:通过Socket对象的getInputStream()方法获取输入流和getOutputStream()方法获取输出流。 4. 发送和接收数据:使用输出流向服务器发送数据,并使用输入流接收服务器返回的数据。 5. 关闭Socket连接:使用Socket对象的close()方法关闭连接。 下面是一个简单的Java Socket客户端程序示例: ```java import java.io.*; import java.net.*; public class SocketClient { public static void main(String[] args) { try { // 创建Socket对象,指定服务器的IP地址和端口号 Socket socket = new Socket("服务器IP地址", 端口号); // 获取输出流 OutputStream outputStream = socket.getOutputStream(); // 向服务器发送数据 String message = "需要发送的数据"; outputStream.write(message.getBytes()); // 获取输入流 InputStream inputStream = socket.getInputStream(); // 接收服务器返回的数据 byte[] buffer = new byte[1024]; int length = inputStream.read(buffer); String response = new String(buffer, 0, length); System.out.println("服务器返回的数据:" + response); // 关闭连接 socket.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 在Python中,可以使用socket模块来创建一个服务端。编写Socket服务端程序的过程包括以下几个步骤: 1. 导入必要的模块:导入socket模块。 2. 创建Socket对象:使用socket.socket()函数创建一个socket对象。 3. 绑定地址和端口:使用socket对象的bind()方法绑定服务器的IP地址和端口号。 4. 开始监听:使用socket对象的listen()方法开始监听,等待客户端连接。 5. 建立连接:使用socket对象的accept()方法接收客户端的连接请求,并返回客户端的Socket对象和地址。 6. 接收和发送数据:通过客户端的Socket对象进行数据的接收和发送。 7. 关闭连接:使用socket对象的close()方法关闭连接。 下面是一个简单的Python Socket服务端程序示例: ```python import socket # 创建socket对象 s = socket.socket() # 绑定地址和端口 host = '0.0.0.0' port = 20000 s.bind((host, port)) # 开始监听 s.listen(6) # 建立连接 conn, addr = s.accept() # 接收数据 data = conn.recv(1024) print(data.decode()) # 发送数据 data_last = data.decode() conn.send(f"{data_last},也算我一个,青鸟是我的!".encode()) # 关闭连接 s.close() conn.close() ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值