views:

1225

answers:

5

What is the best way to get a byte array from a struct to send over TCP sockets? I'm using .Net (VB or C#).

A: 

You need to be more specific and tell us your language.

For many languages, there are ready-made frameworks, or even parts of the language's standard environment, for doing these kinds of things.

unwind
+1  A: 

If you are willing to take care of the endian (to communicate in an heterogeneous network), the only way to do this is field by field.

Maurice Perry
A: 

I'm assuming the C language since you say "struct"

you can use a function called

ssize_t write(int fd, const void *buf, size_t count);

where FD is the filedescriptor of socket the buffer is the address of the structure, and count is the size in bytes

you would use it as:

write(socket,&struct_var, sizeof(struct_var));

Jaap Geurts
Does this account for alignment, packing and endianness?
sharptooth
no it does not.For endianness you would have to use a function like htonl, htons, ntohl, ntohs which convert values between host and network byte order.For packing you can use your compiler to force a certain packing structure or alignment.
Jaap Geurts
+3  A: 

You should look into Serialization. There are number of options available to you, from Protocol Buffers (implementations by the 1st and 2nd ranked SO users) to Xml to the BinaryFormatter.

Joel Coehoorn
+5  A: 

If you're using C#, you can also marshal it to a native buffer yourself, to have better control over serialization.

You would need to add the appropriate attribute to your struct,

  [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack=1)]

Then you can serialize it using:

    /// <summary>
    /// Serializes the specified object into a byte array.
    /// </summary>
    /// <param name="nativeObject">The object to serialize.</param>
    /// <returns></returns>
    public static byte[] Serialize(object obj)
    {
        Type objectType = obj.GetType();
        int objectSize = Marshal.SizeOf(obj);
        IntPtr buffer = Marshal.AllocHGlobal(objectSize);
        Marshal.StructureToPtr(obj, buffer, false);
        byte[] array = new byte[objectSize];
        Marshal.Copy(buffer, array , 0, objectSize);
        Marshal.FreeHGlobal(buffer);
        return array;
    }
Groo