Question

I want to duplicate addrinfo structure (simply copying all bytes of it) but my changes result in memory corruption in host application when hooking.

My code is simple as:

 byte[] addressInfoBytes = new byte[32];
 Marshal.Copy(addressInfoAddress, addressInfoBytes, 0, addressInfoBytes.Length);
 newAddressInfoAddress = GCHandle.Alloc(addressInfoBytes, GCHandleType.Pinned).AddrOfPinnedObject();

I thought it happens because 32 is not correct size of this structure. I calculated this number based on this definition on MSDN:

typedef struct addrinfo {
  int             ai_flags;
  int             ai_family;
  int             ai_socktype;
  int             ai_protocol;
  size_t          ai_addrlen;
  char            *ai_canonname;
  struct sockaddr  *ai_addr;
  struct addrinfo  *ai_next;
} ADDRINFOA, *PADDRINFOA;

Do you have any Idea about correct size of this structure and what I do incorrect?

Thank you very much for your time.

Was it helpful?

Solution

I solved this problem long time ago, so I just thought posting it here may help some one else as well.

    using System.Net;
    using System.Net.Sockets;

    [StructLayout(LayoutKind.Sequential)]
    internal struct AddressInfo
    {
        internal AddressInfoHints Flags;

        internal AddressFamily Family;

        internal SocketType SocketType;

        internal ProtocolFamily Protocol;

        internal int AddressLen;

        internal IntPtr CanonName; // sbyte Array

        internal IntPtr Address; // byte Array

        internal IntPtr Next; // Next Element In AddressInfo Array

        [Flags]
        internal enum AddressInfoHints
        {
            None = 0,
            Passive = 0x01,
            Canonname = 0x02,
            Numerichost = 0x04,
            All = 0x0100,
            Addrconfig = 0x0400,
            V4Mapped = 0x0800,
            NonAuthoritative = 0x04000,
            Secure = 0x08000,
            ReturnPreferredNames = 0x010000,
            Fqdn = 0x00020000,
            Fileserver = 0x00040000,
        }
    }

    AddressInfo addressInfo = (AddressInfo)Marshal.PtrToStructure(handle, typeof(AddressInfo));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top