When using the inet_ntoa function, I do not understand the structural type conversion that is passed to the factor.

Asked 2 years ago, Updated 2 years ago, 28 views

You want to use a function whose circular form is char * inet_ntoa (structure in_add in); in function

int ipaddr = inet_addr("127.0.0.1");

And I want to convert the ip Internet address back to a dot-marking address and print it out

printf("%s \n", inet_ntoa(*(structure in_addr *)&ipaddr); this is how you use it.

I wonder why they pass the function transfer factor like that.

c

2022-09-22 21:53

3 Answers

I think the structure in_add is 4 bytes. I think it's an action to put the value in the 4-byte int into the structure using a pointer. Refer to the following example for the process of putting the value in int into the structure. Press Run under Code to try running the code immediately.

#include <stdio.h>

struct Dumnmy_in_add {
   char part1;
   char part2;
   char part3;
   char part4;
};


int main(){
  int a=0;
  struct Dumnmy_in_add*b;
  //1)
  Put the address value of a in pointer b to point to the memory area of b=&a;//a.

  struct Dumnmy_in_add c;
  Make c=*b;//c have a value in the memory area of b

  printf("%d.%d.%d.%d", c.part1,c.part2,c.part3,c.part4);
  return 0;
}


2022-09-22 21:53

Because the inet_ntoa function is defined as char *inet_ntoa(struct in_addrin), passing int to a factor causes a compilation error. For this reason, cast &ipaddr to structure in_addr*) and use * to read the values at that address.


2022-09-22 21:53

I don't know the in_addr type or the inet_ntoa function, but let's take a look.

Since (inet_addr) is (char *) reciprocal, we will return the address value of a string.

And you store that address in the ipaddr.

So let's look at this kid again.

&ipaddr brings the 'address value' of the int variable.

What you see here is not taking the address value in the int, but the address value in the int.

As the above person said, use (sturct in_addr*) to enter the address value of int.

Change the 'address value' stored in int to the 'sturct in_addr' type.(You can do Haet-gal-ri in this part. Take it easy. h)

And the address value converted to the in_addr type from (*(....)&...) to the far left *(pointer) and the approached value

I'm handing it over to a function.

I'm not sure if I answered your question properly.

Study hard~


2022-09-22 21:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.