4

The getnameinfo prototype asks for sockaddr but I have only seen examples using sockaddr_in. Can this example be re-written for sockaddr ? sin_family becomes sa_family but what about sin_port and sin_addr ? How are they included in sa_data ?

struct sockaddr{
    unsigned short  sa_family;
    char            sa_data[14];
};

struct sockaddr_in{
    short           sin_family;
    unsigned short  sin_port;
    struct in_addr  sin_addr;
    char            sin_zero[8];
};


struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
sin.sin_family      = AF_INET;
sin.sin_addr.s_addr = inet_addr(IPvar);
sin.sin_port        = 0; // If 0, port is chosen by system

getnameinfo( (struct sockaddr *)&sin, sizeof(sin), buffervar, sizeof(buffervar), NULL, 0, 0);
cassepipe
  • 371
  • 6
  • 16
Jane
  • 41
  • 2

1 Answers1

5

struct sockaddr is a "super-class" of the concrete protocol address structures like struct sockaddr_in, struct sockaddr_in6, and struct sockaddr_un, etc. The getnameinfo(3) dispatches to a specific execution path based of the address family (the sa_family member.)

As far as memory is concerned - the three members of struct sockaddr_in are overlaid with the struct sockaddr's sa_data member. Take a look at Chapter 3 of the UnP book.

Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171
  • 1
    And this is why you have to pass in the size of the address structure that you've given it. – Jonathan Leffler Apr 05 '10 at 00:07
  • @JonathanLeffler But then, why can't you just pass a `void*` since you have the size ? Why the need for a common type ? – cassepipe Oct 11 '22 at 14:54
  • 1
    @cassepipe — I can think of a couple of reasons to avoid `void *`. First, you lose whatever smidgen of type-safety is available — you could pass any type of pointer to the function and the compiler couldn't complain that the `int *` or `char *` or `struct passwd *` passed to the function is wrong. The second is probably history — and consistency with history. However, I wasn't party to the decision-making process and I don't know why the design was chosen. It wasn't decided casually, however. – Jonathan Leffler Oct 11 '22 at 16:18