In case anyone is interested, here is the full code. It's capable of unpacking an IPAddress
object to an in_addr
struct and back again.
[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];
}
/// <summary>
/// Unpacks an in_addr struct to an IPAddress object
/// </summary>
/// <returns></returns>
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);
}
Like JaredPar, I still don't know what to do with Anonymous3, but it doesn't really matter because it can't be set anyway. Since they all have the same FieldOffset, setting one field clears all of the others. It appears to work, though, so I'm not too worried about it.