不久前我创建了一个类来处理我的局域网网络程序。我最近将我的一台笔记本电脑升级到Windows 7并重新设计了Windows 7(或者至少我设置的方式)只支持IPv6,但我的桌面仍然在Windows xp时代,并且只使用IPv4。我创建的类使用UdpClient类,目前设置为仅使用IPv4 ..有没有办法修改我的代码以允许发送和接收IPv6和IPv4数据包? 废弃类代码很难,我的很多程序都依赖于这个类。我想保持班级接近其原始状态,所以我不需要修改我的旧程序,只需要更新旧班级。
感谢您的帮助, 最大
发送:
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 );
}
接收:
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
}
答案 0 :(得分:0)
我认为这可能会对您有所帮助:C# server that supports IPv6 and IPv4 on the same port
答案 1 :(得分:0)
UdpClient可以通过提供DualMode套接字准备在IPv4和IPv6上接收:
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)
发送更容易,我们可以使用指定的目标地址(IPv4或IPv6)创建UdpClient。如果需要,可以在构造函数中提供AddressFamily。