📄 winsock2wrapper.cs
字号:
namespace NCindy.Util
{
using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
public static class WinSock2Wrapper
{
public const int INT32_LENGTH = 4;
private static readonly byte[] KeepAliveOff = BitConverter.GetBytes((uint) 0);
private static readonly byte[] KeepAliveOn = BitConverter.GetBytes((uint) 1);
public const int SO_CONNECT_TIME = 0x700c;
private static readonly int UintSize = Marshal.SizeOf(typeof(uint));
public static int GetConnectTime(Socket sock)
{
int optval;
if (sock == null)
{
throw new ArgumentNullException();
}
int optlen = 4;
if (getsockopt(sock.Handle, 0xffff, 0x700c, out optval, ref optlen) != 0)
{
throw new SocketException(WSAGetLastError());
}
return optval;
}
[DllImport("ws2_32.dll", CharSet=CharSet.Auto, SetLastError=true)]
private static extern int getsockopt(IntPtr socketHandle, int level, int optname, out int optval, ref int optlen);
public static IPEndPoint QueryRoutingInterface(Socket sock, IPEndPoint remoteEP)
{
LangHelper.CheckNullArgument("sock", sock);
LangHelper.CheckNullArgument("remoteEP", remoteEP);
SocketAddress socketAddress = remoteEP.Serialize();
byte[] buffer = new byte[socketAddress.Size];
for (int i = 0; i < socketAddress.Size; i++)
{
buffer[i] = socketAddress[i];
}
byte[] buffer2 = new byte[buffer.Length];
sock.IOControl(0xc8000014, buffer, buffer2);
for (int j = 0; j < socketAddress.Size; j++)
{
socketAddress[j] = buffer2[j];
}
IPEndPoint point = (IPEndPoint) remoteEP.Create(socketAddress);
point.Port = ((IPEndPoint) sock.LocalEndPoint).Port;
return point;
}
public static void SetKeepAlive(Socket s, bool on, uint time, uint interval)
{
byte[] dst = new byte[UintSize * 3];
Buffer.BlockCopy(on ? ((Array) KeepAliveOn) : ((Array) KeepAliveOff), 0, dst, 0, UintSize);
Buffer.BlockCopy(BitConverter.GetBytes(time), 0, dst, UintSize, UintSize);
Buffer.BlockCopy(BitConverter.GetBytes(interval), 0, dst, UintSize * 2, UintSize);
s.IOControl(0x98000004, dst, null);
}
[DllImport("ws2_32.dll", CharSet=CharSet.Auto, SetLastError=true)]
private static extern int WSAGetLastError();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -