Use UdpClient with IPv4 and IPv6?

Posted by mazzzzz on Stack Overflow See other posts from Stack Overflow or by mazzzzz
Published on 2010-03-17T00:50:39Z Indexed on 2010/03/17 0:51 UTC
Read the original article Hit count: 510

Filed under:
|
|
|
|

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 );
        ReceivedPacket = new Packet ( receiveBytes );
        client.Close();
        //Do what ever with the packets now
    }

© Stack Overflow or respective owner

Related posts about c#

Related posts about networking