1

In the file below I only get output for the first of the two prints. The output that I get is:

0 2 127.0.0.1
0 2 

Why does using sockaddr->sa_data (it is a char array) not print anything? While I know it is not a very convenient struct but it should still hold information right? How does the info magically show up after casting it?

Code Used:

#include <stdio.h>
#include <string.h>
#include <netdb.h>
#include <arpa/inet.h>

int main(int argc, char **argv) {

    //DNS
    struct addrinfo hints;
    struct addrinfo *result, *temp;

    memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_CANONNAME;

    int s = getaddrinfo("localhost", NULL, &hints, &result);
    for (temp = result; temp != NULL; temp = temp->ai_next) {
        printf("%d %d %s\n", s, temp->ai_addr->sa_family, inet_ntoa(((struct sockaddr_in*)(temp->ai_addr))->sin_addr));
        printf("%d %d %s\n", s, temp->ai_addr->sa_family, temp->ai_addr->sa_data);

    }

}
dash-o
  • 13,723
  • 1
  • 10
  • 37
Legolas
  • 105
  • 8
  • 1
    Because `sin_addr` isn't at the same offset. There is something else there that null-terminates the display. Look at the definitions. – user207421 Nov 20 '19 at 11:37
  • Does this answer your question? [Why do we cast sockaddr\_in to sockaddr when calling bind()?](https://stackoverflow.com/questions/21099041/why-do-we-cast-sockaddr-in-to-sockaddr-when-calling-bind) – Rishikesh Raje Nov 20 '19 at 11:46
  • 1
    The IP address is printed in the first case, because `inet_ntoa()` converts it to a printable string. In the sockaddr-struct, the IP is stored in "binary" form (4 bytes) – Karim Nov 20 '19 at 13:03
  • @user207421 what definitions are you referring to? – Legolas Nov 20 '19 at 14:32
  • The definitions of those structs, of course. – user207421 Nov 21 '19 at 00:17
  • @RishikeshRaje No it doesn't. That's the opposite cast. – user207421 Nov 21 '19 at 00:18

0 Answers0