这个题目的解答的核心是知道这两个数据结构可以互换
下面的输出是
printf("uint16_t: %ld\n", sizeof(uint16_t));
printf("in_addr: %ld\n", sizeof(struct in_addr));
#include "csapp.h"
int main (int argc, char **argv) {
struct addrinfo *p, *listp, hints;
char buf[MAXLINE];
int rc, flags;
if (argc != 2) {
fprintf(stderr, "usage: %s \n" , argv[0]);
exit(0);
}
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
if ((rc = getaddrinfo(argv[1], NULL, &hints, &listp))!= 0) {
fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(rc));
exit(1);
}
flags = NI_NUMERICHOST;
for (p = listp; p; p = p->ai_next) {
Getnameinfo(p->ai_addr, p->ai_addrlen, buf, MAXLINE, NULL, 0, flags);
printf("%s\n", buf);
}
Freeaddrinfo(listp);
exit(0);
}
#include "csapp.h"
#include
int main (int argc, char **argv) {
struct addrinfo *p, *listp, hints;
char buf[MAXLINE];
int rc, flags;
if (argc != 2) {
fprintf(stderr, "usage: %s \n" , argv[0]);
exit(0);
}
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
if ((rc = getaddrinfo(argv[1], NULL, &hints, &listp))!= 0) {
fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(rc));
exit(1);
}
flags = NI_NUMERICHOST;
for (p = listp; p; p = p->ai_next) {
struct sockaddr_in* sin = (struct sockaddr_in*)p->ai_addr;
struct in_addr src = sin->sin_addr;
char dst[20];
inet_ntop(AF_INET, (void*)&src, dst, INET_ADDRSTRLEN);
printf("%s\n", dst);
}
Freeaddrinfo(listp);
exit(0);
}
不知道为什么和前面那个顺序是反的
答案
解这个问题的时候搜了一下百度,当时是想弄清楚sockaddr是怎么回事,结果
当我知道要转换后,这个问题怎么解基本思路有了,只是不知道会不会有什么意外,比如大小端什么的