gpt4 book ai didi

C# - 将指向 sockaddr 结构的 IntPtr 转换为 IPAddress

转载 作者:行者123 更新时间:2023-11-30 14:12:28 25 4
gpt4 key购买 nike

从 P/Invoked native 函数,我得到一个 IntPtr指向 sockaddr结构。如何将其转换为 IPAddress

谢谢!

最佳答案

根据@aevitas 的回答,我想到了以下解决方案:

public enum SockAddrFamily
{
Inet = 2,
Inet6 = 23
}

[StructLayout(LayoutKind.Sequential)]
public struct SockAddr
{
public ushort Family;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 14)]
public byte[] Data;
};

[StructLayout(LayoutKind.Sequential)]
public struct SockAddrIn
{
public ushort Family;
public ushort Port;
public uint Addr;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
public byte[] Zero;
}

[StructLayout(LayoutKind.Sequential)]
public struct SockAddrIn6
{
public ushort Family;
public ushort Port;
public uint FlowInfo;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public byte[] Addr;
public uint ScopeId;
};

public IPAddress ConvertSockAddrPtrToIPAddress(IntPtr sockAddrPtr)
{
SockAddr sockAddr = (SockAddr)Marshal.PtrToStructure(sockAddrPtr, typeof(SockAddr));
switch ((SockAddrFamily)sockAddr.Family)
{
case SockAddrFamily.Inet:
{
SockAddrIn sockAddrIn = (SockAddrIn)Marshal.PtrToStructure(sockAddrPtr, typeof(SockAddrIn));
return new IPAddress(sockAddrIn.Addr);
}
case SockAddrFamily.Inet6:
{
SockAddrIn6 sockAddrIn6 = (SockAddrIn6)Marshal.PtrToStructure(sockAddrPtr, typeof(SockAddrIn6));
return new IPAddress(sockAddrIn6.Addr);
}
default:
throw new Exception(string.Format("Non-IP address family: {0}", sockAddr.Family));
}
}

我成功地使用 IPv4 和 IPv6 地址对其进行了测试。

关于C# - 将指向 sockaddr 结构的 IntPtr 转换为 IPAddress,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17426939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com