您好,欢迎访问三七文档
privatevoidbtnSend_Click(objectsender,EventArgse){device.Open();//打开网卡//获取本机的ip和接收方的IPIPAddresssourceAddress=IPAddress.Parse(((WinPcapDevice)device).Interface.Addresses[0].Addr.ToString());IPAddressdestinationAddress=IPAddress.Parse(this.ipServerAddress.Text);PhysicalAddresssourceHwAddress=device.MacAddress;//获取本机网卡的MAC地址PhysicalAddressdestinationHwAddress=NetworkUtils.GetMacAddress(((WinPcapDevice)device).Interface.GatewayAddress);//获取网关的MAC地址(访问外网),如果是访问内网直接用接收方的MAC地址EthernetPacketpacket=EthernetPacket.RandomPacket();packet.SourceHwAddress=sourceHwAddress;packet.DestinationHwAddress=destinationHwAddress;//构造以太网数据包,并将MAC绑定到数据包中UdpPacketudpPacket=newUdpPacket(Properties.Settings.Default.Port,Properties.Settings.Default.ServerPort);//构造UDP数据包,初始化源端口与目的端口udpPacket.PayloadData=System.Text.Encoding.Unicode.GetBytes(this.txtMessage.Text);//要发送的数据udpPacket.UpdateCalculatedValues();//更新数据包的长度IpPacketipPacket=IpPacket.RandomPacket(IpVersion.IPv4);ipPacket.TimeToLive=20;ipPacket.Protocol=IPProtocolType.UDP;ipPacket.Version=IpVersion.IPv4;ipPacket.DestinationAddress=destinationAddress;ipPacket.SourceAddress=sourceAddress;//构造的IP数据包ipPacket.PayloadPacket=udpPacket;//按层封装数据包packet.PayloadPacket=ipPacket;//ipPacket.ParentPacket=packet;//udpPacket.ParentPacket=ipPacket;udpPacket.UpdateUDPChecksum();//计算校验和device.SendPacket(packet);//发送数据包}
本文标题:构造UDP数据包
链接地址:https://www.777doc.com/doc-3275148 .html