从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

相关文章

PostgreSQL的扩展dict_int应用案例解析

《PostgreSQL的扩展dict_int应用案例解析》dict_int扩展为PostgreSQL提供了专业的整数文本处理能力,特别适合需要精确处理数字内容的搜索场景,本文给大家介绍PostgreS... 目录PostgreSQL的扩展dict_int一、扩展概述二、核心功能三、安装与启用四、字典配置方法

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

Spring WebFlux 与 WebClient 使用指南及最佳实践

《SpringWebFlux与WebClient使用指南及最佳实践》WebClient是SpringWebFlux模块提供的非阻塞、响应式HTTP客户端,基于ProjectReactor实现,... 目录Spring WebFlux 与 WebClient 使用指南1. WebClient 概述2. 核心依

Mysql实现范围分区表(新增、删除、重组、查看)

《Mysql实现范围分区表(新增、删除、重组、查看)》MySQL分区表的四种类型(范围、哈希、列表、键值),主要介绍了范围分区的创建、查询、添加、删除及重组织操作,具有一定的参考价值,感兴趣的可以了解... 目录一、mysql分区表分类二、范围分区(Range Partitioning1、新建分区表:2、分

MySQL 定时新增分区的实现示例

《MySQL定时新增分区的实现示例》本文主要介绍了通过存储过程和定时任务实现MySQL分区的自动创建,解决大数据量下手动维护的繁琐问题,具有一定的参考价值,感兴趣的可以了解一下... mysql创建好分区之后,有时候会需要自动创建分区。比如,一些表数据量非常大,有些数据是热点数据,按照日期分区MululbU

Spring Boot @RestControllerAdvice全局异常处理最佳实践

《SpringBoot@RestControllerAdvice全局异常处理最佳实践》本文详解SpringBoot中通过@RestControllerAdvice实现全局异常处理,强调代码复用、统... 目录前言一、为什么要使用全局异常处理?二、核心注解解析1. @RestControllerAdvice2

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

MySQL中查找重复值的实现

《MySQL中查找重复值的实现》查找重复值是一项常见需求,比如在数据清理、数据分析、数据质量检查等场景下,我们常常需要找出表中某列或多列的重复值,具有一定的参考价值,感兴趣的可以了解一下... 目录技术背景实现步骤方法一:使用GROUP BY和HAVING子句方法二:仅返回重复值方法三:返回完整记录方法四:

IDEA中新建/切换Git分支的实现步骤

《IDEA中新建/切换Git分支的实现步骤》本文主要介绍了IDEA中新建/切换Git分支的实现步骤,通过菜单创建新分支并选择是否切换,创建后在Git详情或右键Checkout中切换分支,感兴趣的可以了... 前提:项目已被Git托管1、点击上方栏Git->NewBrancjsh...2、输入新的分支的

Spring事务传播机制最佳实践

《Spring事务传播机制最佳实践》Spring的事务传播机制为我们提供了优雅的解决方案,本文将带您深入理解这一机制,掌握不同场景下的最佳实践,感兴趣的朋友一起看看吧... 目录1. 什么是事务传播行为2. Spring支持的七种事务传播行为2.1 REQUIRED(默认)2.2 SUPPORTS2