Я не знаю, предоставляют ли ту же функциональность методы * Asyn c, но вот реализация, которая дает вам IP-адрес получения и номер сетевого интерфейса, который получил пакет UDP.
Используя базовые методы ReceiveMessageFrom Socket
s (Begin / End), мы можем получить больше информации о полученном пакете. Документация кода для его двух значимых параметров:
// endPoint:
// The source System.Net.EndPoint.
//
// ipPacketInformation:
// The System.Net.IPAddress and interface of the received packet.
Надеюсь, это поможет.
static UdpClient client;
static byte[] byts = new byte[8192];
static void ReceiveUDP(IAsyncResult asyncResult)
{
EndPoint ipEndpoint = new IPEndPoint(IPAddress.Any, 9876);
IPPacketInformation packetInformation;
SocketFlags socketFlags = SocketFlags.None;
int numberOfBytesReceived = client.Client.EndReceiveMessageFrom(asyncResult, ref socketFlags, ref ipEndpoint, out packetInformation);
Console.WriteLine
(
"Received {0} bytes\r\nfrom {1}\r\nReceiving IP Address: {2}\r\nNetwork Interface #{3}\r\n************************************",
numberOfBytesReceived,
ipEndpoint,
packetInformation.Address,
packetInformation.Interface
);
EndPoint anyEndpoint = new IPEndPoint(IPAddress.Any, 9876);
try
{
client.Client.BeginReceiveMessageFrom(byts, 0, 8192, SocketFlags.None, ref anyEndpoint, ReceiveUDP, null);
}
catch (Exception beginReceiveError)
{
// Console.WriteLine("{0}", beginReceiveError);
}
}
static void Main(string[] args)
{
client = new UdpClient(new IPEndPoint(IPAddress.Any, 9876));
EndPoint anyEndpoint = new IPEndPoint(IPAddress.Any, 9876);
client.Client.BeginReceiveMessageFrom(byts, 0, 8192, SocketFlags.None, ref anyEndpoint, ReceiveUDP, null);
UdpClient server = new UdpClient();
server.Connect("172.20.10.4", 9876);
server.Send(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 8);
UdpClient server2 = new UdpClient();
server2.Connect("127.0.0.1", 9876);
server2.Send(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 9);
UdpClient server3 = new UdpClient();
server3.Connect("OOZGUL-NB02", 9876);
server3.Send(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 9);
client.Close();
server.Close();
server2.Close();
Console.ReadLine();
}
Вывод:
Received 8 bytes
from 172.20.10.4:59196
Receiving IP Address: 172.20.10.4
Network Interface #3
************************************
Received 9 bytes
from 127.0.0.1:59197
Receiving IP Address: 127.0.0.1
Network Interface #1
************************************
Received 9 bytes
from 172.20.10.4:59198
Receiving IP Address: 172.20.10.4
Network Interface #3
************************************