在同一系统中的2个以太网端口之间传输和接收UDP帧

时间:2015-04-23 12:04:15

标签: c# sockets networking ethernet

我的系统中有两个以太网端口, 我已将IP地址分别配置为 - 10.169.20.1510.169.20.30。我试图通过IP地址为10.169.20.30的端口从一个应用程序传输UDP帧。在另一个应用程序中,我试图通过IP 10.169.20.15的其他以太网端口接收帧。

发送时我可以设置我的源IP地址(以便使用该IP的特定以太网端口进行传输)和我的目标IP地址。

但是对于接收我不知道如何设置IP 10.169.20.15作为接收端口的端口。

Tx代码

class Program
{
    static IPEndPoint Mypoint = new IPEndPoint(IPAddress.Parse("10.169.20.30"), 8050);// Source IP 
    static IPEndPoint UrPoint = new IPEndPoint(IPAddress.Parse("10.169.20.15"), 8051);// Destination IP
    static UdpClient TxClient;
    static void Main(string[] args)
    {
        int i = 0;
        byte [] data= new byte[1472];
        TxClient = new UdpClient(Mypoint);
        while (i < 500)
        {
            data[i]++;
            try
            {
                TxClient.Send(data, data.Length, UrPoint);
            }
            catch { }
            Console.WriteLine("Sent frame " + i + " times\n");
            i++;
        }
        Console.ReadKey();
    }
}

Rx代码

class Program
{
   static IPEndPoint RxEndpoint = new IPEndPoint(IPAddress.Any, 8051); // IP from where I can receive the frame

    static UdpState state1 = new UdpState();
    static UdpClient Rx;
    static int i = 0;
    static void Main(string[] args)
    {
        Rx = new UdpClient(RxEndpoint);
        state1.Rxclient = Rx;
        state1.Endpoint = RxEndpoint;
        Rx.BeginReceive(new AsyncCallback(RecieveCallback1), state1);
        while (true)
        { }
    }
    public static void RecieveCallback1(IAsyncResult ar)
    {

        UdpClient Rx1 = (UdpClient)((UdpState)(ar.AsyncState)).Rxclient;
        IPEndPoint End1 = (IPEndPoint)((UdpState)(ar.AsyncState)).Endpoint;
        Byte[] receiveBytes = Rx1.EndReceive(ar, ref End1);
        Console.WriteLine("Recieved " + (i++) + "Frame and its data is -> " + receiveBytes + "\n");
        Rx.BeginReceive(new AsyncCallback(RecieveCallback1), state1);
    }
}
class UdpState
{
  public  UdpClient Rxclient;
  public  IPEndPoint Endpoint;
}

2 个答案:

答案 0 :(得分:1)

如果两个程序在同一主机设备上运行,并且您希望在它们之间进行通信,则应使用loopback interface而不是发送一个物理接口并在另一个上接收。

环回接口效率更高,因为它全部在软件中并且更易于使用。配置发件人发送到127.0.0.1并将您的接收器绑定到127.0.0.1。您可以在示例中使用相同的端口。

答案 1 :(得分:1)

只有一个原因是您实际上想要使用外部网络在同一台机器中的两个进程之间交换数据,如果您想检测它们之间的链接(以及干预)交换机已启动。

为此,您应该使用IEEE 802.1d生成树协议。当且仅当两个端口汇聚到同一树中的成员资格时,它们之间才有链接。