Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why struct in_addr is needed

Tags:

c

sockets

I already searched. Maybe bad... I didn't understand why the 'in_addr' structure exists.

typedef uint32_t in_addr_t;

struct in_addr
{
    in_addr_t s_addr;
};

The question is whether this structure is important or not. If it doesn't matter then I can write like this:

*(uint32_t*)(&s->sin_addr) = to_be32(ip->addr);

If it matters then I should write like this:

s->sin_addr.s_addr = to_be32(ip->addr);
like image 724
Penguin Avatar asked Aug 28 '26 11:08

Penguin


1 Answers

Yes, it matters, because it hides implementation details. Just because it contains a single in_addr_t in your case, does not mean that will be so on all systems. Moreover, in_addr_t need not even be compatible with uint32_t, as you have assumed.

The Socket API need not even be specific to TCP/IP - all these types are abstracted to allow your code to be portable across both network protocols and operating systems.

So, while it may work, there is no real advantage, and in any case I would argue that s->sin_addr.s_addr = to_be32(ip->addr); is simpler and easier to understand, and more importantly does not require you to know the underlying implementation. So, *(uint32_t*)(&s->sin_addr) = to_be32(ip->addr); may "work", but it is not correct, safe, or even serves any useful purpose. It is even a longer expression!

like image 54
Clifford Avatar answered Aug 31 '26 01:08

Clifford