C# - 转换的IntPtr指向sockaddr结构体为ip地址 [英] C# - Converting IntPtr pointing to sockaddr structure to IPAddress

查看:603
本文介绍了C# - 转换的IntPtr指向sockaddr结构体为ip地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从P /调用本地函数,我得到一个 的IntPtr 它指向的 的sockaddr 结构。我怎样才能将其转换为一个 ip地址

From a P/Invoked native function, I get an IntPtr which points to a sockaddr structure. How can I convert it to an IPAddress?

谢谢!

推荐答案

既然你不能直接元帅 A 的sockaddr 输入到 ip地址的类型,你就必须做出一个管理结构出来的率先将其封进:

Since you can't directly Marshal a sockaddr type into an IPAddress type, you'd have to make a managed struct out of it first to marshal it into:

[StructLayout(LayoutKind.Sequential)]
internal struct sockaddr_in
{
    internal EnumLib.ADDRESS_FAMILIES sin_family;
    internal ushort sin_port;
    internal in_addr sin_addr;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] internal byte[] sin_zero;

    internal static sockaddr_in FromString(string host, int port)
    {
    var sockaddr = new sockaddr_in();
    var lpAddressLength = Marshal.SizeOf(sockaddr);
    WSAStringToAddress(host + ":" + port, EnumLib.ADDRESS_FAMILIES.AF_INET, IntPtr.Zero,
                      ref sockaddr, ref lpAddressLength);
    return sockaddr;
    }
}



然后,您可以使用元帅.PtrToStructure 来获得 SOCKADDR_IN 从类型你的的IntPtr 像这样:

You could then use Marshal.PtrToStructure to obtain a sockaddr_in type from your IntPtr like so:

(SOCKADDR_IN)Marshal.PtrToStructure(地址的typeof(SOCKADDR_IN));

之后,它应该是相当简单的,创建从你刚刚检索到的数据的新的 ip地址对象。

After that it should be fairly simple to create a new IPAddress object from the data you've just retrieved.

您可以找到包含在 EnumLib 在上面的例子这里的 ADDRESS_FAMILIES 枚举:的 http://pastie.org/8103489

You can find the ADDRESS_FAMILIES enum that is contained in EnumLib in the above example here: http://pastie.org/8103489

有更多原本在pinvoke.net的结构上的成员,只需这里看看如果你有兴趣在其中不过,我想你不会需要他们都在这种特殊情况。

There are originally more members of the struct over at pinvoke.net, just take a look here if you are interested in them but I reckon you won't need them at all in this specific situation.

这篇关于C# - 转换的IntPtr指向sockaddr结构体为ip地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆