Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert uint32_t to struct in_addr?

Tags:

c

#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; 
};
like image 607
Bruce Avatar asked Apr 01 '12 01:04

Bruce


1 Answers

You're casting an int to a pointer. Perhaps you want this:

*(struct in_addr *)&ip

But the result is implementation-defined (for a start, there're endianness considerations).

like image 71
Oliver Charlesworth Avatar answered Sep 27 '22 21:09

Oliver Charlesworth