Use UdpClient with IPv4 and IPv6?
-
20-09-2019 - |
Question
A little while ago I created a class to deal with my LAN networking programs. I recently upgraded one of my laptops to windows 7 and relized that windows 7 (or at least the way I have it set up) only supports IPv6, but my desktop is still back in the Windows xp days, and only uses IPv4. The class I created uses the UdpClient class, and is currently setup to only work with IPv4.. Is there a way to modify my code to allow sending and receiving of IPv6 and IPv4 packets?? It would be hard to scrap the classes code, a lot of my programs rely on this class. I would like to keep the class as close to its original state, so I don't need to modify my older programs, only switch out the old class for the updated one.
Thanks for any and all help, Max
Send:
using System.Net.Sockets;UdpClient tub = new UdpClient ();
tub.Connect ( new IPEndPoint ( ToIP, ToPort ) );
UdpState s = new UdpState ();
s.client = tub;
s.endpoint = new IPEndPoint ( ToIP, ToPort );
tub.BeginSend ( data, data.Length, new AsyncCallback ( SendCallBack ),s);
private void SendCallBack ( IAsyncResult result )
{
UdpClient client = (UdpClient)( (UdpState)( result.AsyncState ) ).client;
IPEndPoint endpoint = (IPEndPoint)( (UdpState)( result.AsyncState ) ).endpoint;
client.EndSend ( result );
}
Receive:
UdpClient tub = new UdpClient (ReceivePort);
UdpState s = new UdpState ();
s.client = tub;
s.endpoint = new IPEndPoint ( ReceiveIP, ReceivePort );
s.callback = cb;
tub.BeginReceive ( new AsyncCallback ( receivedPacket ), s );
public void receivedPacket (IAsyncResult result)
{
UdpClient client = (UdpClient)( (UdpState)( result.AsyncState ) ).client;
IPEndPoint endpoint = (IPEndPoint)( (UdpState)( result.AsyncState ) ).endpoint;
Byte[] receiveBytes = client.EndReceive ( result, ref endpoint );
Packet ThePacket = new Packet ( receiveBytes );
client.Close();
//Do what ever with the 'ThePacket' now
}
Solution
I think this might help you: C# server that supports IPv6 and IPv4 on the same port
OTHER TIPS
UdpClient can be prepared to receive on both IPv4 and IPv6 by providing a DualMode socket:
socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);
socket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234));
var udpClient = new UdpClient();
udpClient.Client = socket;
... (use udpClient)
Sending is easier, we can create UdpClient with the specified target address (IPv4 or IPv6). AddressFamily can be provided in the constructor, if needed.