使用udp C#发送和接收数据

时间:2019-05-01 08:20:09

标签: c# sockets model-view-controller udp ipv6

我执行以下两个过程来从一个ipv6地址发送数据到另一个ipv6地址。

  1. 我使用udp标头创建套接字和ipv6数据包,然后将其发送到我的目标地址。它成功发送,但是当我使用套接字的接收功能时,它将进入等待状态

在下面的这段代码中,我使用目标地址创建了连接,但是当我收到发送的相同数据时,它就会进入等待状态

在我的计算机iv4和6中都启用了该功能,但在目标位置仅启用了ipv6,并且该ipv6地址是本地服务器

        IPAddress sourceAddress = IPAddress.Parse(GetIPAddress(version).Values.FirstOrDefault()),

        destAddress = IPAddress.Parse("[2001:db8:abcd::7]");
        IPAddress bindAddress;
        if (version == 4)
        {
            bindAddress = IPAddress.Any;
        }
        else
        {
            bindAddress = IPAddress.IPv6Any;
        }

        ushort sourcePort = 5150,

    //    destPort = 1234;
    destPort = 84;

        int messageSize = 16,

        sendCount = 5;







        // Parse the command line


        // Make sure parameters are consistent

        if ((sourceAddress.AddressFamily != destAddress.AddressFamily) || (sourceAddress.AddressFamily != bindAddress.AddressFamily))
        {

            Console.WriteLine("Source and destination address families don't match!");

            //usage();

            return;

        }



        // Print the command line parameters

        Console.WriteLine("Source address : {0}   \tPort: {1}", sourceAddress.ToString(), sourcePort.ToString());

        Console.WriteLine("Dest   address : {0}   \tPort: {1}", destAddress.ToString(), destPort.ToString());

        Console.WriteLine("Local interface: {0}", bindAddress.ToString());

        Console.WriteLine("Message size   : {0}", messageSize);

        Console.WriteLine("Send count     : {0}", sendCount);



        // Start building the headers

        Console.WriteLine("Building the packet header...");

        byte[] builtPacket, payLoad = new byte[messageSize];

        UdpHeader udpPacket = new UdpHeader();

        ArrayList headerList = new ArrayList();

        Socket rawSocket = null;

        SocketOptionLevel socketLevel = SocketOptionLevel.IP;



        // Initialize the payload

        Console.WriteLine("Initialize the payload...");

        for (int i = 0; i < payLoad.Length; i++)

            payLoad[i] = (byte)'#';



        // Fill out the UDP header first

        Console.WriteLine("Filling out the UDP header...");

        udpPacket.SourcePort = sourcePort;

        udpPacket.DestinationPort = destPort;

        udpPacket.Length = (ushort)(UdpHeader.UdpHeaderLength + messageSize);

        udpPacket.Checksum = 0;



        if (sourceAddress.AddressFamily == AddressFamily.InterNetwork)
        {

            Ipv4Header ipv4Packet = new Ipv4Header();



            // Build the IPv4 header

            Console.WriteLine("Building the IPv4 header...");

            ipv4Packet.Version = 4;

            ipv4Packet.Protocol = (byte)ProtocolType.Udp;

            ipv4Packet.Ttl = 2;

            ipv4Packet.Offset = 0;

            ipv4Packet.Length = (byte)Ipv4Header.Ipv4HeaderLength;

            ipv4Packet.TotalLength = (ushort)System.Convert.ToUInt16(Ipv4Header.Ipv4HeaderLength + UdpHeader.UdpHeaderLength + messageSize);

            ipv4Packet.SourceAddress = sourceAddress;

            ipv4Packet.DestinationAddress = destAddress;



            // Set the IPv4 header in the UDP header since it is required to calculate the

            //    pseudo header checksum

            Console.WriteLine("Setting the IPv4 header for pseudo header checksum...");

            udpPacket.ipv4PacketHeader = ipv4Packet;



            // Add IPv4 header to list of headers -- headers should be added in th order

            //    they appear in the packet (i.e. IP first then UDP)

            Console.WriteLine("Adding the IPv4 header to the list of header, encapsulating packet...");

            headerList.Add(ipv4Packet);

            socketLevel = SocketOptionLevel.IP;

        }

        else if (sourceAddress.AddressFamily == AddressFamily.InterNetworkV6)
        {

            ProtocolHeaderDef.Ipv6Header ipv6Packet = new ProtocolHeaderDef.Ipv6Header();



            // Build the IPv6 header

            Console.WriteLine("Building the IPv6 header...");

            ipv6Packet.Version = 6;

            ipv6Packet.TrafficClass = 1;

            ipv6Packet.Flow = 2;

            ipv6Packet.HopLimit = 2;

            ipv6Packet.NextHeader = (byte)ProtocolType.Udp;

            ipv6Packet.PayloadLength = (ushort)(UdpHeader.UdpHeaderLength + payLoad.Length);

            ipv6Packet.SourceAddress = sourceAddress;

            ipv6Packet.DestinationAddress = destAddress;



            // Set the IPv6 header in the UDP header since it is required to calculate the

            //    pseudo header checksum

            Console.WriteLine("Setting the IPv6 header for pseudo header checksum...");

            udpPacket.ipv6PacketHeader = ipv6Packet;



            // Add the IPv6 header to the list of headers - headers should be added in the order

            //    they appear in the packet (i.e. IP first then UDP)

            Console.WriteLine("Adding the IPv6 header to the list of header, encapsulating packet...");

            headerList.Add(ipv6Packet);

            socketLevel = SocketOptionLevel.IPv6;

        }



        // Add the UDP header to list of headers after the IP header has been added

        Console.WriteLine("Adding the UDP header to the list of header, after IP header...");

        headerList.Add(udpPacket);



        // Convert the header classes into the binary on-the-wire representation

        Console.WriteLine("Converting the header classes into the binary...");

        builtPacket = udpPacket.BuildPacket(headerList, payLoad);



        // Create the raw socket for this packet

        Console.WriteLine("Creating the raw socket using Socket()...");

        rawSocket = new Socket(sourceAddress.AddressFamily, SocketType.Raw, ProtocolType.Udp);



        // Bind the socket to the interface specified

        Console.WriteLine("Binding the socket to the specified interface using Bind()...");

        rawSocket.Bind(new IPEndPoint(bindAddress, 0));



        // Set the HeaderIncluded option since we include the IP header

        Console.WriteLine("Setting the HeaderIncluded option for IP header...");

        rawSocket.SetSocketOption(socketLevel, SocketOptionName.HeaderIncluded, 1);

        try
        {

            // Send the packet!

            Console.WriteLine("Sending the packet...");

            for (int i = 0; i < sendCount; i++)
            {
                int rc = rawSocket.SendTo(builtPacket, new IPEndPoint(destAddress, destPort));
                Console.WriteLine("send {0} bytes to {1}", rc, destAddress.ToString());
            }

            //IPEndPoint object will allow us to read datagrams sent from any source.
            EndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.IPv6Any, 0);             
            byte[] rec=new byte[128];
            var receiveBytes = rawSocket.ReceiveFrom(rec,SocketFlags.None, ref RemoteIpEndPoint);
            //string returnData = Encoding.ASCII.GetString(receiveBytes);
        }

        catch (SocketException err)
        {

            Console.WriteLine("Socket error occurred: {0}", err.Message);



        }

        finally
        {

            // Close the socket

            Console.WriteLine("Closing the socket...");

            rawSocket.Close();

        }




2. i use the udp client  and same as earlier send successfully with destination address but in receive it goes to waiting

在下面的这段代码中,我使用目标地址创建了连接,但是当我收到发送的相同数据时,它将在ipv6地址中进入等待状态

        IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
        IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("2001:db8:abcd:12:15df:d075:5e4f:ac82"),11000);

        Socket s = new Socket(endPoint.Address.AddressFamily,
            SocketType.Dgram,
            ProtocolType.Udp);

        // Creates an IPEndPoint to capture the identity of the sending host.
        IPEndPoint sender = new IPEndPoint(IPAddress.IPv6Any, 0);
        EndPoint senderRemote = (EndPoint)sender;

        // Binding is required with ReceiveFrom calls.
        s.Bind(endPoint);

        byte[] msg = new Byte[256];
        Console.WriteLine("Waiting to receive datagrams from client...");
        // This call blocks. 
        s.ReceiveFrom(msg, msg.Length, SocketFlags.None, ref senderRemote);
        s.Close();

0 个答案:

没有答案