我正在设置UDP侦听器,该侦听器仅从某个IP,某个端口和某个NIC接收。为了检查侦听器的功能,我希望将我拥有的另一个NIC的UDP数据包发送到接收方中指定的UDP数据包。不幸的是,接收方仅在从与接收方相同的NIC发送信息时才接收信息。
从我读到的内容来看,如果我想绑定希望发送的NIC,则应该使用udpclient构造函数,connect方法或套接字绑定方法。我已经尝试了所有这些方法,并将在代码中包含示例。除非我将UDPclient设置为相同的值,或者将套接字绑定为相同的值,否则永远不会收到该程序包。如果这就是它的原意,那么我该如何绑定一个不同的NIC进行发送。
这是收件人代码
public void StartListening()
{
if (init == true)
{
running = true;
//Props.NICIP = NIC of reciever, listenport is recievers port
listenEndpoint = new IPEndPoint(Props.NICIP, Props.ListenPort);
//creates UDP client with set out NIC ip and a decided port
udp = new UdpClient(listenEndpoint);
init = false;
}
if (running == true)
{
this.udp.BeginReceive(Receive, new object());
}
}
private void Receive(IAsyncResult ar)
{
//reference ip from sender
IPEndPoint ip1 = null;
byte[] bytes1 = null;
if (running == true)
{
//array of bytes recieved for subission
bytes1 = udp.EndReceive(ar, ref ip1);
//check to see that ip of recieved packet, is from specified
//NIC of sender
if (ip1.Address.Address == Props.IPValue.Address)
{
BSubmit = new Byte[220];
BinSubmit = bytes1;
}
}
StartListening();
}
这是发件人代码
public class Sender
{
//this sets up NIC of Sender
IPEndPoint ip2 = new IPEndPoint(new IPAddress(new byte[]
{ 10, 0, 101, 67 }), 200);
Socket sock = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
static int z = 0;
public void Send()
{
//insures dont try use same port twice
if (z == 0)
{
// binds NIC of reciever to socket
sock.Bind(ip2);
z++;
}
//states the NIC and port of the Receiver
IPEndPoint endPoint = new IPEndPoint(Props.NICIP,
Props.ListenPort);
byte[] bytes = new byte[500];
bytes[8] = 5;
bytes[9] = 6;
//intention is to send from socket bound to sender NIC,
// to reciever IP and port determined by endPoint
sock.SendTo(bytes, endPoint);
////////////this is the udpclient version of the code/////////
//
// //binds NIC of sender to UDP client
// IPEndPoint ip2 = new IPEndPoint(new IPAddress(new byte[]
// { 10, 0, 101, 67 }),200);
//
//
// //states NIC and port of reciever
// IPEndPoint ip = new IPEndPoint(Props.NICIP,
// Props.ListenPort);
//
// UdpClient client = new UdpClient(ip2);
//////////////////////////////////////////////////////
//////////////UDP CLIENT VERSION//////////////////
//
// //intention is to send to ip, which defines recievers NIC
// //and port, from client, which is bound to Sender NIC
// client.Send(bytes, bytes.Length, ip);
// client.Close();
/////////////////////////////////////////////////
}
}
}
预期的结果是,接收者应接收由发送者的ipEndPoint确定的发送给它的消息。然后要么根据数据包是否来自预期的NIC允许访问,然后通过此检查过滤 “((ip1.Address.Address == Props.IPValue.Address)”。
发生什么事,除非我将套接字的绑定或发送方的UDPClient的构造器/连接设置为接收方NIC的IP,否则不会收到任何程序包。端口值可以不同,并且仍然可以接收消息,但是IP必须保持不变。
我不知道我是否对将NIC绑定到发送者或接收者有基本的误解,或者是否完全缺少其他东西。任何帮助将不胜感激。