在同一个系统中的两个以太网端口之间传输和接收UDP帧
问题描述:
我在我的系统中有两个以太网端口, 和我已经分别配置了它们的IP地址,分别为 - 10.169.20.15
和10.169.20.30
。我试图通过IP地址为10.169.20.30
的端口从一个应用程序传输UDP帧。与另一个应用程序,我试图通过IP 10.169.20.15
通过其他以太网端口接收帧。在同一个系统中的两个以太网端口之间传输和接收UDP帧
在传输过程中,我可以设置我的源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;
}
答
如果两个程序在同一主机设备上运行,并且希望他们之间的沟通,你应该使用loopback interface而不是发送出一个物理接口和另一个接收。
环回接口更高效,因为它全部位于软件内部并且更易于使用。配置你的发送者发送到127.0.0.1,并将你的接收者绑定到127.0.0.1。你可以在你的例子中使用相同的端口。
答
只有一个原因是您实际上希望使用外部网络在同一台计算机上的两个进程之间交换数据,也就是说,如果要检测它们(和中间交换机之间)的链接是否已启动。
为此,您应该使用IEEE 802.1d生成树协议。当且仅当两个端口收敛到同一棵树中的成员资格时,它们之间才有链接。
新的UdpClient(IPEndPoint localEP)用于指定**本地**端点。 * IPAddress.Any *让系统选择使用哪个IP地址。 –
确定而不是IPAddress.Any,我使用IPAddress.Parse(“10.169.20.15”),但仍然没有成功。通过wireshark,我能够发现数据已经传输到ip 10.169.20.15,但我的应用程序无法收到它。 – Bas
@Bas当你说“我的系统中有两个以太网端口”时,你的意思是两个物理主机连接在一个以太网网络中,或者你的意思是你有一个主机上有两个以太网端口,即两个网络在以太网网络中连接在一起的接口 –