Reputation: 9926
On my machine i have 2 network card. I need to send 2 udp messages but each of them will be send by different network card.
How can i do it ?
Upvotes: 0
Views: 39
Reputation: 106816
You need some way to identify the network interfaces. One way is to use their names:
var networkInterfaceNames = new HashSet<string>() {
"Local Area Connection",
"Loopback Pseudo-Interface 1"
};
Then you need to get the local IP addresses of these interfaces. I assume that you want to use IPv4 and that your interfaces have been assigned IPv4 addresses (AddressFamily.InterNetwork
):
var localIpAddresses = NetworkInterface
.GetAllNetworkInterfaces()
.Where(ni => networkInterfaceNames.Contains(ni.Name))
.Select(
ni => ni
.GetIPProperties()
.UnicastAddresses
.First(ua => ua.Address.AddressFamily == AddressFamily.InterNetwork)
);
Then you need to send UDP packets using these local end points. One way to do that is to use UdpClient
:
foreach (var localIpAddress in localIpAddresses) {
const Int32 LocalPort = 1234;
var localEndPoint = new IPEndPoint(localIpAddress.Address, LocalPort);
using (var udpClient = new UdpClient(localEndPoint)) {
const Int32 RemotePort = 4321;
var remoteEndPoint = new IPEndPoint(IPAddress.Parse("10.20.30.40"), RemotePort);
Byte[] payload = ...
udpClient.Send(payload, payload.Length, remoteEndPoint);
}
}
Upvotes: 3