在C#中将in_addr转换为IPAddress

C、C++中有时候会用 in_addr 结构体 做为参数保存IP地址,当用C、C++编写的动态库包含 in_addr 参数的接口,而我们需要在 C#中调用此动态库时就会遇到将 in_addr 转换为 IPAddress 的问题,以下C#代码可实现此转换:

[StructLayout(LayoutKind.Sequential)]
public struct in_addr {
    public Anonymous1 S_un;
 
    [StructLayoutAttribute(LayoutKind.Explicit)]
    public struct Anonymous1 {
        [FieldOffsetAttribute(0)]
        public Anonymous2 S_un_b;
 
        [FieldOffsetAttribute(0)]
        public Anonymous3 S_un_w;
 
        [FieldOffsetAttribute(0)]
        public uint S_addr;
    }
 
    [StructLayoutAttribute(LayoutKind.Sequential)]
    public struct Anonymous2 {
        public byte s_b1;
        public byte s_b2;
        public byte s_b3;
        public byte s_b4;
    }
 
    [StructLayoutAttribute(LayoutKind.Sequential)]
    public struct Anonymous3 {
        public ushort s_w1;
        public ushort s_w2;
    }
 
    public in_addr(IPAddress address) : this(address.GetAddressBytes()) { }
 
    public in_addr(byte[] address) {
        // Set this first, otherwise it wipes out the other fields
        S_un.S_un_w = new Anonymous3();
 
        S_un.S_addr = (uint)BitConverter.ToInt32(address, 0);
 
        S_un.S_un_b.s_b1 = address[0];
        S_un.S_un_b.s_b2 = address[1];
        S_un.S_un_b.s_b3 = address[2];
        S_un.S_un_b.s_b4 = address[3];
    }
 
    /// 
    /// Unpacks an in_addr struct to an IPAddress object
    /// 
    /// 
    public IPAddress ToIPAddress() {
        byte[] bytes = new[] {
            S_un.S_un_b.s_b1,
            S_un.S_un_b.s_b2,
            S_un.S_un_b.s_b3,
            S_un.S_un_b.s_b4
        };
    }
 
    return new IPAddress(bytes);
}

原文地址:http://stackoverflow.com/questions/1323845/using-in-addr-in-c-sharp

发布者

发表评论

电子邮件地址不会被公开。