Sending and receiving UDP packets between two programs on the same computer

后端 未结 8 1758
慢半拍i
慢半拍i 2020-12-02 12:37

Is it possible to get two separate programs to communicate on the same computer (one-way only) over UDP through localhost/127... by sharing the same port #?

We\'re

相关标签:
8条回答
  • 2020-12-02 12:49

    Even changing your code so that I can pass in an IP address I gets the same error message it appears that you can't bind to the same port and only one port can be used here is the sample code I used your example and Altered it to capture my ip from my local machine.. IPAddress ipAddress = Dns.Resolve(Dns.GetHostName()).AddressList[0]; IPEndPoint ipLocalEndPoint = new IPEndPoint(ipAddress, 11000);

            //IPEndPoint localpt = new IPEndPoint(ipLocalEndPoint);
    
            UdpClient udpServer = new UdpClient(ipLocalEndPoint);
            udpServer.Client.SetSocketOption(
                SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            udpServer.Connect(ipLocalEndPoint);
            UdpClient udpServer2 = new UdpClient();
            udpServer2.Client.SetSocketOption(
                SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
    
            udpServer2.Client.Bind(ipLocalEndPoint); // <<---------- Exception here
    

    this will produce the exception on the Bind () method.. sorry.

    0 讨论(0)
  • 2020-12-02 12:57

    I did not expect this to be possible, but.. well.. sipwiz was right.

    It can be done very easily. (Please vote sipwiz's answer up!)

    IPEndPoint localpt = new IPEndPoint(IPAddress.Any, 6000);
    
    //Failed try
        try
        {
            var u = new UdpClient(5000);
            u.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
    
            UdpClient u2 = new UdpClient(5000);//KABOOM
            u2.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        }
        catch (Exception)
        {
            Console.WriteLine("ERROR! You must call Bind only after setting SocketOptionName.ReuseAddress. \n And you must not pass any parameter to UdpClient's constructor or it will call Bind.");
        }
    
    //This is how you do it (kudos to sipwiz)
        UdpClient udpServer = new UdpClient(localpt); //This is what the proprietary(see question) sender would do (nothing special) 
    
        //!!! The following 3 lines is what the poster needs...(and the definition of localpt (of course))
        UdpClient udpServer2 = new UdpClient();
        udpServer2.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        udpServer2.Client.Bind(localpt);
    
    0 讨论(0)
  • 2020-12-02 12:57

    bind the two programs,ie, the sender and receiver to the same port on the localhost.dats the simple answer.

    0 讨论(0)
  • 2020-12-02 13:03

    My advice: don't pass the port number into the UdpClient constructor. From the documentation, (somewhat sparse, I know...) it looks like if you do, the UdpClient will try to bind to that port (which, as sysrqb mentioned, is not allowed). (If you don't, I believe the UdpClient will listen on a random port for any replies. You could also pick a port you know to be unused.)

    When you call Connect() you need to pass in the port number the server is listening on.

    0 讨论(0)
  • 2020-12-02 13:09

    You might be able to put multiple IP addresses on your network card, or loopback, and bind the server and client to different IP addresses?

    Or else the Virtual machine approach will definitely work.

    0 讨论(0)
  • 2020-12-02 13:10

    Here is the full code from the answers by Tarnay Kálmán and sipwiz:

    The server code:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace UdpBroadcastTest
    {
        class Program
        {
            static void Main(string[] args)
            {
    
                Console.WriteLine("Sender");
                // This constructor arbitrarily assigns the local port number.
    
                UdpClient udpClient = new UdpClient();
                udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                udpClient.Connect("localhost", 11000);
                try
                {
                    string message = String.Empty;
                    do
                    {
                        message = Console.ReadLine();
                        // Sends a message to the host to which you have connected.
                        Byte[] sendBytes = Encoding.ASCII.GetBytes(message);
    
                        udpClient.Send(sendBytes, sendBytes.Length);
                    } while (message != String.Empty);
    
                    udpClient.Close();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
    
                Console.WriteLine("Press Any Key to Continue");
                Console.ReadKey();
            }
        }
    }
    

    The client code:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace UdpReciever
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("Receiver");
                // This constructor arbitrarily assigns the local port number.
                UdpClient udpClient = new UdpClient();
                udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                udpClient.Client.Bind(new IPEndPoint(IPAddress.Any, 11000));
                try
                {
                    //IPEndPoint object will allow us to read datagrams sent from any source.
                    IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
    
                    string message = String.Empty;
                    do
                    {
    
                        // Blocks until a message returns on this socket from a remote host.
                        Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
                        message = Encoding.ASCII.GetString(receiveBytes);
    
                        // Uses the IPEndPoint object to determine which of these two hosts responded.
                        Console.WriteLine("This is the message you received: " +
                                                     message);
                        //Console.WriteLine("This message was sent from " +
                        //                            RemoteIpEndPoint.Address.ToString() +
                        //                            " on their port number " +
                        //                            RemoteIpEndPoint.Port.ToString());
                    }
                    while (message != "exit");
                    udpClient.Close();
                    //udpClientB.Close();
    
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
    
                Console.WriteLine("Press Any Key to Continue");
                Console.ReadKey();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题