从0到1用java再造tcpip协议栈:代码实现ping应用功能1

2024-04-30 22:08

本文主要是介绍从0到1用java再造tcpip协议栈:代码实现ping应用功能1,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

上一节我们讲解了基于ICMP echo协议的ping原理,并提出下图的代码实现架构:

1.png

我们将遵照上面架构实现代码,首先为protocol后面的所有协议对象增加一个接口:

package protocol;import java.util.HashMap;public interface IProtocol {public byte[] createHeader(HashMap<String, byte[]> headerInfo);
}package protocol;public class ProtocolManager {private static ProtocolManager instance = null;private ProtocolManager() {}public static ProtocolManager getInstance() {if (instance == null) {instance = new ProtocolManager();}return instance;}public IProtocol getProtocol(String name) {switch (name.toLowerCase()) {case "icmp":return new ICMPProtocolLayer();case "ip":return new IPProtocolLayer();}return null;}
}

所有协议对象必须继承上面接口,处于Application处的应用对象直接调用协议对象该接口来封装发送数据包所需要的包头。接下来我们使用一个类专门用于构造协议头:

package protocol;import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Random;import utils.Utility;public class ICMPEchoHeader implements IProtocol{private static int ICMP_EOCH_HEADER_LENGTH = 16;private static short ICMP_ECHO_TYPE = 8;private static short ICMP_ECHO_REPLY_TYPE = 0;@Overridepublic byte[] createHeader(HashMap<String, Object> headerInfo) {String headerName = (String)headerInfo.get("header");if (headerName != "echo" && headerName != "echo_reply") {return null;}byte[] buffer = new byte[ICMP_EOCH_HEADER_LENGTH];ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);short type = ICMP_ECHO_TYPE;if (headerName == "echo_reply") {type = ICMP_ECHO_REPLY_TYPE;}byteBuffer.putShort(type);short code = 0;byteBuffer.putShort(code);short checkSum = 0;byteBuffer.putShort(checkSum);short identifier = 0;if (headerInfo.get("identifier") == null) {Random ran = new Random();identifier = (short) ran.nextInt();headerInfo.put("identifier", identifier);}identifier = (short) headerInfo.get("identifier");byteBuffer.putShort(identifier);short sequenceNumber = 0;if (headerInfo.get("sequence_number") != null) {sequenceNumber = (short) headerInfo.get("sequence_number");sequenceNumber += 1;}headerInfo.put("sequence_number", sequenceNumber);byteBuffer.putShort(sequenceNumber);checkSum = (short) Utility.checksum(byteBuffer.array(), byteBuffer.array().length);byteBuffer.putShort(4, checkSum);		return byteBuffer.array();}}

在ICMPProtocolLayer类中,我们依旧使用责任链模式调用相应对象来构造不同的包头:

public class ICMPProtocolLayer implements PacketReceiver, IProtocol{
....private ArrayList<IProtocol> protocol_header_list = new ArrayList<IProtocol>();public ICMPProtocolLayer() {//添加错误消息处理对象error_handler_list.add(new ICMPUnReachableMsgHandler());//增加icmp echo 协议包头创建对象protocol_header_list.add(new ICMPEchoHeader());}
....public byte[] createHeader(HashMap<String, Object> headerInfo) {for (int i = 0; i < protocol_header_list.size(); i++) {byte[] buff = protocol_header_list.get(i).createHeader(headerInfo);if (buff != null) {return buff;}}return null;}
}

由于发送ICMP echo数据包依然需要IP包头,因此我们先构建一个产生IP包头的类:

package protocol;import java.nio.ByteBuffer;
import java.util.HashMap;import utils.Utility;public class IPProtocolLayer implements IProtocol{private static byte IP_VERSION = 4;private static int CHECKSUM_OFFSET = 10;@Overridepublic byte[] createHeader(HashMap<String, Object> headerInfo) {byte version = IP_VERSION;byte internetHeaderLength = 5;if (headerInfo.get("internet_header_length") != null) {internetHeaderLength = (byte)headerInfo.get("internet_header_length");}byte[] buffer = new byte[internetHeaderLength];ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);byteBuffer.put((byte) (internetHeaderLength << 4 | version));byte dscp = 0;if (headerInfo.get("dscp") != null) {dscp = (byte)headerInfo.get("dscp");}byte ecn = 0;if (headerInfo.get("ecn") != null) {ecn = (byte)headerInfo.get("ecn");}byteBuffer.put((byte)(dscp | ecn << 6));if (headerInfo.get("total_length") == null) {return null;}short totalLength = (short)headerInfo.get("total_length");byteBuffer.putShort(totalLength);int identification = 0;if (headerInfo.get("identification") != null) {identification = (int)headerInfo.get("identification");}byteBuffer.putInt(identification);short flagAndOffset = 0;if (headerInfo.get("flag") != null) {flagAndOffset = (short)headerInfo.get("flag");}if (headerInfo.get("fragment_offset") != null) {flagAndOffset |= ((short)headerInfo.get("fragment_offset")) << 3;}byteBuffer.putShort(flagAndOffset);short timeToLive = 64;if (headerInfo.get("time_to_live") != null) {timeToLive = (short)headerInfo.get("time_to_live");}byteBuffer.putShort(timeToLive);short protocol = 0;if (headerInfo.get("protocol") == null) {return null;}protocol = (short)headerInfo.get("protocol");byteBuffer.putShort(protocol);short checkSum = 0;byteBuffer.putShort(checkSum);int srcIP = 0;if (headerInfo.get("source_ip") == null) {return null;}srcIP = (int)headerInfo.get("source_ip");byteBuffer.putInt(srcIP);int destIP = 0;if (headerInfo.get("destination_ip") == null) {return null;}byteBuffer.putInt(destIP);if (headerInfo.get("options") != null) {byte[] options = (byte[])headerInfo.get("options");byteBuffer.put(options);}checkSum = (short) Utility.checksum(byteBuffer.array(), byteBuffer.array().length);byteBuffer.putShort(CHECKSUM_OFFSET, checkSum);return byteBuffer.array();}}

接着我们构造应用程序管理对象,它将用于管理各个应用程序:

package Application;public interface IApplication {public  int getPort();public boolean isClosed(); public  void handleData(byte[] data);
}package Application;public interface IApplicationManager {public  IApplication getApplicationByPort(int port);
}package Application;import java.util.ArrayList;public class ApplicationManager implements IApplicationManager{private ArrayList<IApplication> application_list = new ArrayList<IApplication>();@Overridepublic IApplication getApplicationByPort(int port) {for (int i = 0; i < application_list.size(); i++) {IApplication app = application_list.get(i);if (app.getPort() == port) {return app;}}return null;}}

在下一小节,我们会继续完善代码。

更详细的讲解和代码调试演示过程,请点击链接

更多技术信息,包括操作系统,编译器,面试算法,机器学习,人工智能,请关照我的公众号:
这里写图片描述

这篇关于从0到1用java再造tcpip协议栈:代码实现ping应用功能1的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/950044

相关文章

Java中流式并行操作parallelStream的原理和使用方法

《Java中流式并行操作parallelStream的原理和使用方法》本文详细介绍了Java中的并行流(parallelStream)的原理、正确使用方法以及在实际业务中的应用案例,并指出在使用并行流... 目录Java中流式并行操作parallelStream0. 问题的产生1. 什么是parallelS

C++中unordered_set哈希集合的实现

《C++中unordered_set哈希集合的实现》std::unordered_set是C++标准库中的无序关联容器,基于哈希表实现,具有元素唯一性和无序性特点,本文就来详细的介绍一下unorder... 目录一、概述二、头文件与命名空间三、常用方法与示例1. 构造与析构2. 迭代器与遍历3. 容量相关4

Java中Redisson 的原理深度解析

《Java中Redisson的原理深度解析》Redisson是一个高性能的Redis客户端,它通过将Redis数据结构映射为Java对象和分布式对象,实现了在Java应用中方便地使用Redis,本文... 目录前言一、核心设计理念二、核心架构与通信层1. 基于 Netty 的异步非阻塞通信2. 编解码器三、

C++中悬垂引用(Dangling Reference) 的实现

《C++中悬垂引用(DanglingReference)的实现》C++中的悬垂引用指引用绑定的对象被销毁后引用仍存在的情况,会导致访问无效内存,下面就来详细的介绍一下产生的原因以及如何避免,感兴趣... 目录悬垂引用的产生原因1. 引用绑定到局部变量,变量超出作用域后销毁2. 引用绑定到动态分配的对象,对象

SpringBoot基于注解实现数据库字段回填的完整方案

《SpringBoot基于注解实现数据库字段回填的完整方案》这篇文章主要为大家详细介绍了SpringBoot如何基于注解实现数据库字段回填的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以了解... 目录数据库表pom.XMLRelationFieldRelationFieldMapping基础的一些代

一篇文章彻底搞懂macOS如何决定java环境

《一篇文章彻底搞懂macOS如何决定java环境》MacOS作为一个功能强大的操作系统,为开发者提供了丰富的开发工具和框架,下面:本文主要介绍macOS如何决定java环境的相关资料,文中通过代码... 目录方法一:使用 which命令方法二:使用 Java_home工具(Apple 官方推荐)那问题来了,

Java HashMap的底层实现原理深度解析

《JavaHashMap的底层实现原理深度解析》HashMap基于数组+链表+红黑树结构,通过哈希算法和扩容机制优化性能,负载因子与树化阈值平衡效率,是Java开发必备的高效数据结构,本文给大家介绍... 目录一、概述:HashMap的宏观结构二、核心数据结构解析1. 数组(桶数组)2. 链表节点(Node

Java AOP面向切面编程的概念和实现方式

《JavaAOP面向切面编程的概念和实现方式》AOP是面向切面编程,通过动态代理将横切关注点(如日志、事务)与核心业务逻辑分离,提升代码复用性和可维护性,本文给大家介绍JavaAOP面向切面编程的概... 目录一、AOP 是什么?二、AOP 的核心概念与实现方式核心概念实现方式三、Spring AOP 的关

详解SpringBoot+Ehcache使用示例

《详解SpringBoot+Ehcache使用示例》本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录摘要概念内存与磁盘持久化存储:配置灵活性:编码示例引入依赖:配置ehcache.XML文件:配置

Java 虚拟线程的创建与使用深度解析

《Java虚拟线程的创建与使用深度解析》虚拟线程是Java19中以预览特性形式引入,Java21起正式发布的轻量级线程,本文给大家介绍Java虚拟线程的创建与使用,感兴趣的朋友一起看看吧... 目录一、虚拟线程简介1.1 什么是虚拟线程?1.2 为什么需要虚拟线程?二、虚拟线程与平台线程对比代码对比示例:三