C# socket ipv6
时间: 2023-12-02 13:42:42 浏览: 61
以下是使用C#编写的IPv6套接字示例代码:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SocketListener
{
public static void Main()
{
// 定义IPv6套接字
Socket listener = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
// 定义IPv6地址
IPAddress ipv6Address = IPAddress.Parse("::1");
// 定义网络端口
int port = 11000;
// 定义网络终结点
IPEndPoint localEndPoint = new IPEndPoint(ipv6Address, port);
try
{
// 绑定网络终结点
listener.Bind(localEndPoint);
// 开始监听
listener.Listen(10);
Console.WriteLine("Waiting for a connection...");
// 接受连接请求
Socket handler = listener.Accept();
string data = null;
// 接收数据
byte[] bytes = new byte[1024];
int bytesRec = handler.Receive(bytes); data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
Console.WriteLine("Text received : {0}", data);
// 发送数据
byte[] msg = Encoding.ASCII.GetBytes("Hello World");
handler.Send(msg);
// 关闭套接字
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
}
```
该示例代码创建了一个IPv6套接字并绑定到本地IPv6地址和端口11000。然后,它开始监听连接请求并接受连接。一旦连接建立,它将接收来自客户端的数据并发送“Hello World”作为响应。最后,它关闭套接字并退出。