1

Consider the following code snippet:

uint8_t addr[4];
inet_pton(AF_INET, args.gtp_bind_addr.c_str(), addr);

The function inet_pton() takes an IP-address in dotted decimal form (args.gtp_bind_addr.c_str()), converts it into an in_addr struct and copies this struct to addr.

Now, assume I am given a sockaddr_in struct, let's call it help. And I want to write the addr_in entry of help into my addr array. Would this be possible simply by the following command: addr[0] = help->sin_addr ?

This seems a little wrong as I am now assigning the sin_addr just to addr[0], but I want it to fill the entire addr array.

Luk
  • 1,009
  • 2
  • 15
  • 33
  • Does this answer your question? [How to convert string to IP address and vice versa](https://stackoverflow.com/questions/5328070/how-to-convert-string-to-ip-address-and-vice-versa) – Andrew Henle Dec 09 '19 at 15:00
  • assigning a `uint32_t` to a `uint8_t` will simply cause the `uint32_t` to be truncated. – AndyG Dec 09 '19 at 15:01

2 Answers2

1

help.sin_addr is a struct in_addr, a class type that wraps a single 32-bit integer.

A struct in_addr is assignable (from another struct in_addr). It's not a uint8_t, though (how could it be), so your proposed assignment is never going to work. If you'd tried writing such a program, you would have been told this by your compiler.

So, no, it doesn't make much sense. The problem is that you chose to use an array with inet_pton, when there was no need to. All you needed to do was provide another struct in_addr to fill:

struct in_addr addr;
inet_pton(AF_INET, args.gtp_bind_addr.c_str(), static_cast<void*>(&addr));

Now the assignment you want to perform is both valid and completely intuitive.

But, wait! Why bother with the middle-man, then? Just read directly into your target:

inet_pton(AF_INET, args.gtp_bind_addr.c_str(), static_cast<void*>(&help->sin_addr));

Job done.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • I think OP means to assign an `in_addr` to an array of `uint8_t` like this: `uint8_t addr[] = { 192, 168, 1, 1 };`. In that case another answer already points that the way to go with it is using `memcpy`. – Jorge Bellon Dec 09 '19 at 16:23
1

It happens that struct in_addr has exactly 4 bytes, the same size of your uint8_t array. You can copy the contents of the in_addr (which just contains a uint32_t) using memcpy:

memcpy((void *)addr, (void*)&help.sin_addr.s_addr, sizeof help.sin_addr.s_addr);
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
lvella
  • 12,754
  • 11
  • 54
  • 106