UDP协议包校验和小工具设计与实现
实现的功能:
C sharp实现界面的设计,UDP校验和的计算,UDP数据包的生成与发送,数据的保存。总体的代码在主页,有兴趣的可以一起学习交流。
存在问题:
界面的设计比较的简单,图标没进行更换,数据的保存是覆盖性的,追加性数据保存会更好些。UDP数据的接收端并不是自己写的,而是通过网络小助手进行的数据接收。
校验和
校验和的计算方法大同小异,基本的方法都是对应字段二进制反码累加和进行相加。当然了在计算校验和时,二进制相加会出现溢出所以要做溢出处理。
UDP的校验和主要由:UDP首部,伪首部,数据三个部分组成,UDP检验和的计算需要通过将三部分的相应字段转换成二进制反码相加求和。
(1)伪首部:源IP地址,目的IP地址,协议填充字段,协议,UDP数据部分。
(2)首部: 源端口,目的端口,UDP数据部分,检验和。
(3)数据:UDP最小的长度为8bit
源代码:
using System;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.IO;
namespace UDP_Protocol_design
{
public partial class Form1 : Form
{
string[] udphead = new string[14];
string allSum;
public Form1() //窗体的组件随界面的大小缩放
{
InitializeComponent();
}
private float X, Y; //获得控件的长度、宽度、位置、字体大小的数据
private void SetTag(Control cons) //Control类,定义控件的基类
{
foreach (Control con in cons.Controls) //获取或设置包含有关控件的数据的对象
{
con.Tag = con.Width + ":" + con.Height + ":" + con.Left + ":" + con.Top + ":" + con.Font.Size;
if (con.Controls.Count > 0)
SetTag(con); //递归算法
}
} //实现控件以及字体的缩放
private void SetControls(float newx, float newy, Control cons)
{
foreach (Control con in cons.Controls)
{
string[] mytag = con.Tag.ToString().Split(new char[] {
':' });
float a = Convert.ToSingle(mytag[0]) * newx;
con.Width = (int)a;
a = Convert.ToSingle(mytag[1]) * newy;
con.Height = (int)(a);
a = Convert.ToSingle(mytag[2]) * newx;
con.Left = (int)(a);
a = Convert.ToSingle(mytag[3]) * newy;
con.Top = (int)(a);
Single currentSize = Convert.ToSingle(mytag[4]) * newy;
con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit);
if (con.Controls.Count > 0)
{
SetControls(newx, newy, con); //递归
}
}
}
private void MyForm_Resize(object sender, EventArgs e)
{
float newx = (this.Width) / X; //当前宽度与变化前宽度之比
float newy = this.Height / Y; //当前高度与变化前宽度之
SetControls(newx, newy, this);
this.Text = ("UDP协议包自动生工具设计"); //显示窗体的标签
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.Resize += new EventHandler(MyForm_Resize);
X = this.Width;
Y = this.Height;
SetTag(this);