csapp ch11.1 练习题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32768743/article/details/87517738

在这里插入图片描述
当我把代码写完的时候,发现不对啊
我的代码

#include "csapp.h"
#include <arpa/inet.h>
void pton(const char * src) {
    struct in_addr dst;
    inet_pton(AF_INET, src, (void*)&dst);
    printf("%s -> 0x%x\n", src, dst.s_addr);
}
void ntop(const uint32_t hex) {
    struct in_addr src;
    src.s_addr = hex;
    char dst[20];
    inet_ntop(AF_INET, (void*)&src, dst, 16);
    printf("0x%x -> %s\n", src.s_addr, dst);
}
int main (int argc, char **argv) {
    ntop(0x0);
    ntop(0xfffffff);
    ntop(0x7f000001);
    pton("205.188.160.121");
    pton("64.12.149.13");
    pton("205.188.146.23");
}

运行结果
在这里插入图片描述
答案
在这里插入图片描述
怎么不少地方是反的,比如127.0.0.1那个,太明显了
还有大小端问题
当然有个地方少写了一个f
我把百度百科的一个例子拿过来跑,
在这里插入图片描述
这个反的不知道怎么解决
最后看书上
在这里插入图片描述
有这样的函数进行转换
最后解决问题的代码

#include "csapp.h"
#include <arpa/inet.h>
void pton(const char * src) {
    struct in_addr dst;
    inet_pton(AF_INET, src, (void*)&dst);
    printf("%s -> 0x%x\n", src, ntohl(dst.s_addr));
}
void ntop(const uint32_t hex) {
    struct in_addr src;
    src.s_addr = htonl(hex);
    char dst[20];
    inet_ntop(AF_INET, (void*)&src, dst, INET_ADDRSTRLEN);
    printf("0x%x -> %s\n", src.s_addr, dst);
}
int main (int argc, char **argv) {
    ntop(0x0);
    ntop(0xffffffff);
    ntop(0x7f000001);
    pton("205.188.160.121");
    pton("64.12.149.13");
    pton("205.188.146.23");
}

csapp真是处处有惊喜

猜你喜欢

转载自blog.csdn.net/qq_32768743/article/details/87517738