Doubt about pointer to structure in TCP / IP connections

2

I have the following code:

// IPv6:

struct sockaddr_in6 ip6addr;
int s;
ip6addr.sin6_family = AF_INET6;
ip6addr.sin6_port = htons(4950);
inet_pton(AF_INET6, "2001:db8:8714:3a90::12", &ip6addr.sin6_addr);
s = socket(PF_INET6, SOCK_STREAM, 0);
bind(s, (struct sockaddr*)&ip6addr, sizeof ip6addr);

I would like to know what this pointer is pointing to. I guess it's all the elements of the structure, but I'm not sure about it.

(struct sockaddr*)&ip6addr, sizeof ip6addr);
    
asked by thc 18.05.2018 в 00:51
source

1 answer

3

In C the concept of inheritance does not exist, so if you need a function to do polymorphism , that is, to be able to treat objects of different structures in a more or less homogeneous way you have to perform some tricks.

Notice that the function bind should receive a pointer to a structure of type sockaddr ... while you are using a structure of type sockaddr_in6 . Why does this work? The reason is that both structures have a common part, as can be seen below:

struct sockaddr {
  sa_family_t sa_family;
  char        sa_data[14];
};

struct sockaddr_in6 {
  sa_family_t     sin6_family;   /* AF_INET6 */
  in_port_t       sin6_port;     /* port number */
  uint32_t        sin6_flowinfo; /* IPv6 flow information */
  struct in6_addr sin6_addr;     /* IPv6 address */
  uint32_t        sin6_scope_id; /* Scope ID (new in 2.4) */
};

Notice that the first member of both structures is common. sa_family will be what the socket API uses to identify the structure that is really below.

So to do the conversion in reverse you could do something like:

struct sockaddr* sockaddr = GetConfigSocket();
switch( sockaddr->sa_family )
{
  case AF_INET6:
    struct sockaddr_in6* ip6addr = (struct sockaddr_in6*)sockaddr;
    // ...

  case /* ... */
}

Well, saying that we can answer your question:

  

I would like to know what this pointer is pointing to, I suppose it is all the elements of the structure but I am not sure about it.

In this part of the code:

(struct sockaddr*)&ip6addr

You are getting a pointer of type struct sockaddr pointing to your structure, which is type sockaddr_in6 and this is done, as we have seen, to be able to provide a single entry point to configure the different sockets.

Since what you provide to the function is a pointer, what you are really sharing is the region of memory where your variable is then, yes, you are really sharing the entire structure.

    
answered by 18.05.2018 в 07:53