I'm trying to convert this C code to C#, is there a C# equivalent to the C union typedef?
struct sockaddr_in {
short sin_family;
u_short sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};
typedef struct in_addr {
union {
struct {
u_char s_b1,s_b2,s_b3,s_b4;
} S_un_b;
struct {
u_short s_w1,s_w2;
} S_un_w;
u_long S_addr;
} S_un;
} IN_ADDR, *PIN_ADDR, FAR *LPIN_ADDR;
Thanks.
You may check out the following page. This being said, in .NET you have classes that allows you to work directly with sockets and TCP/IP such as Socket, TcpListener, TcpClient and you don't need to translate C code blindly.
Whilst the others definitely have a point - this is likely something you really don't need to do - there is a way to simulate unions in C# using StructLayoutAttribute (example of simulating a union here).
But don't do it. The purpose of this C union seems to be to permit bit twiddling parts of a 4 byte long. Using a union in this way depends on byte order knowledge of the target architecture, something that C# cannot guarantee.
In C# - or any other language where portability is a concern - if you want to get or set the high byte/low byte/etc you need to use explicit bit shifting as explained here.
But then don't do that either. Do like others have said and don't port this code. Someone's already done it for you, most likely Microsoft in the built in libraries ;).