从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获取当前时间String类型和Date类型方式

《Java获取当前时间String类型和Date类型方式》:本文主要介绍Java获取当前时间String类型和Date类型方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录Java获取当前时间String和Date类型String类型和Date类型输出结果总结Java获取

Spring Boot Actuator应用监控与管理的详细步骤

《SpringBootActuator应用监控与管理的详细步骤》SpringBootActuator是SpringBoot的监控工具,提供健康检查、性能指标、日志管理等核心功能,支持自定义和扩展端... 目录一、 Spring Boot Actuator 概述二、 集成 Spring Boot Actuat

OpenCV在Java中的完整集成指南分享

《OpenCV在Java中的完整集成指南分享》本文详解了在Java中集成OpenCV的方法,涵盖jar包导入、dll配置、JNI路径设置及跨平台兼容性处理,提供了图像处理、特征检测、实时视频分析等应用... 目录1. OpenCV简介与应用领域1.1 OpenCV的诞生与发展1.2 OpenCV的应用领域2

Python实现批量提取BLF文件时间戳

《Python实现批量提取BLF文件时间戳》BLF(BinaryLoggingFormat)作为Vector公司推出的CAN总线数据记录格式,被广泛用于存储车辆通信数据,本文将使用Python轻松提取... 目录一、为什么需要批量处理 BLF 文件二、核心代码解析:从文件遍历到数据导出1. 环境准备与依赖库

在Java中使用OpenCV实践

《在Java中使用OpenCV实践》用户分享了在Java项目中集成OpenCV4.10.0的实践经验,涵盖库简介、Windows安装、依赖配置及灰度图测试,强调其在图像处理领域的多功能性,并计划后续探... 目录前言一 、OpenCV1.简介2.下载与安装3.目录说明二、在Java项目中使用三 、测试1.测

linux下shell脚本启动jar包实现过程

《linux下shell脚本启动jar包实现过程》确保APP_NAME和LOG_FILE位于目录内,首次启动前需手动创建log文件夹,否则报错,此为个人经验,供参考,欢迎支持脚本之家... 目录linux下shell脚本启动jar包样例1样例2总结linux下shell脚本启动jar包样例1#!/bin

go动态限制并发数量的实现示例

《go动态限制并发数量的实现示例》本文主要介绍了Go并发控制方法,通过带缓冲通道和第三方库实现并发数量限制,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 目录带有缓冲大小的通道使用第三方库其他控制并发的方法因为go从语言层面支持并发,所以面试百分百会问到

PyTorch中的词嵌入层(nn.Embedding)详解与实战应用示例

《PyTorch中的词嵌入层(nn.Embedding)详解与实战应用示例》词嵌入解决NLP维度灾难,捕捉语义关系,PyTorch的nn.Embedding模块提供灵活实现,支持参数配置、预训练及变长... 目录一、词嵌入(Word Embedding)简介为什么需要词嵌入?二、PyTorch中的nn.Em

Go语言并发之通知退出机制的实现

《Go语言并发之通知退出机制的实现》本文主要介绍了Go语言并发之通知退出机制的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录1、通知退出机制1.1 进程/main函数退出1.2 通过channel退出1.3 通过cont

Spring Bean初始化及@PostConstruc执行顺序示例详解

《SpringBean初始化及@PostConstruc执行顺序示例详解》本文给大家介绍SpringBean初始化及@PostConstruc执行顺序,本文通过实例代码给大家介绍的非常详细,对大家的... 目录1. Bean初始化执行顺序2. 成员变量初始化顺序2.1 普通Java类(非Spring环境)(