public class UdpData { public byte [ ] SourcePort = new byte [ 2 ] ; public byte [ ] DestinationPort = new byte [ 2 ] ; public byte [ ] Length = new byte [ 2 ] ; public byte [ ] Checksum = new byte [ 2 ] ; public byte [ ] Data = new byte [ 1472 ] ; }
第0-15位 第16-31位 源端口 目标端口 包长度 校验和 data data
2.IPV4包的格式
public class IpV4 { public BitArray Version= new ( 4 ) ; public BitArray HeaderLength = new BitArray ( 4 ) ; public byte TypeOfService; public byte [ ] TotalLength = new byte [ 2 ] ; public byte [ ] FragmentId = new byte [ 2 ] ; public BitArray R = new BitArray ( 1 ) ; public BitArray DF = new BitArray ( 1 ) ; public BitArray MF = new BitArray ( 1 ) ; public BitArray FragmentOffset = new BitArray ( 13 ) ; public byte TimeToLive; public byte Protocol; public BitArray HeaderChecksum = new BitArray ( 16 ) ; public byte [ ] SourceIPAddress= new byte [ 4 ] ; public byte [ ] DestinationIPAddress = new byte [ 4 ] ; public byte [ ] Options = new byte [ 0 ] ; public UdpData Data; }
0-3位 4-7位 8-15位 16-31位 Version HeaderLength TypeOfService Length
0-15位 16位 17位 18位 19-31位 FragmentID R DF MF FragmentOffset
0-7位 8-15位 16-31位 TimeToLive Protocol HeaderChecksum
0-31位 SourceIPAddress DestinationIPAddress Options(变长,假定为4字节) UdpData Package(n*4字节)
3.以太网包格式
public class EtherNetFrame { public byte [ ] EthernetFramePreamble = [ 0xAA , 0xAA , 0xAA , 0xAA , 0xAA , 0xAA , 0xAA , 0xAB ] ; public byte [ ] SourceMac = new byte [ 6 ] ; public byte [ ] DestinationMac = new byte [ 6 ] ; public byte [ ] TypeOrLength = new byte [ 2 ] ; public Byte DSAP; public Byte SSAP; public Byte Control; public byte [ ] OrgCode = new byte [ 3 ] ; public byte [ ] TypeOfProtocol = new byte [ 2 ] ; public IpV4 udp Mtu; public byte [ ] FrameChecksum = new byte [ 4 ] ; public byte [ ] EthernetFrameEndCode = [ 0xAA , 0xAA , 0xAA , 0xAA , 0xAA , 0xAA , 0xAA , 0xAA , 0xAA , 0xAA , 0xAA , 0xAA ] ; }
0-7 8-15 16-23 24-31位 0xAA 0xAA 0xAA 0xAA 0xAA 0xAA 0xAA 0xAB SourceMac SourceMac SourceMac SourceMac SourceMac SourceMac DestinationMac DestinationMac DestinationMac DestinationMac DestinationMac DestinationMac TypeOrLength TypeOrLength DSAP SSAP Control OrgCode OrgCode Orgcode TypeOfProtocol TypeOfProtocol IPV4 IPV4 IPV4 IPV4 IPV4 IPV4 … … … … FrameChecksum FrameChecksum FrameChecksum FrameChecksum 0xAA 0xAA 0xAA 0xAA 0xAA 0xAA 0xAA 0xAA
需要注意的是 (1)以太网传输时,低字节在前,高字节在后 (2)不同版本格式不同。 (3)真正编程时,我们关心的是本地IP,Port,远端IP 和Port,基本是从Socket开始的,校验、组包等底层工作,由网络 驱动程序来完成,程序员不用关心。 如何编程,待续。。。。