简体   繁体   English

如何将uint32_t转换为struct in_addr?

[英]How to convert uint32_t to struct in_addr?

#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main()
{
uint32_t ip = 0;
printf("%s\n",inet_ntoa(*(struct in_addr *)ip));
return 0;
}

I don't want to do this by declaring any temporary variable. 我不想通过声明任何临时变量来做到这一点。 This program gives segmentation fault. 该程序给出了分段错误。

struct in_addr {
    uint32_t s_addr; 
};

You're casting an int to a pointer. 你正在将int转换为指针。 Perhaps you want this: 也许你想要这个:

*(struct in_addr *)&ip

But the result is implementation-defined (for a start, there're endianness considerations). 但结果是实现定义的(一开始就有字节序注意事项)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM