I have populated my structure struct addrinfo **res
with data:
err = getaddrinfo(argv[1], NULL, &hints, &res);
if I want to print the IP address, I could use
addr.s_addr = ((struct sockaddr_in *)(res->ai_addr))->sin_addr.s_addr;
printf("ip address : %s\n", inet_ntoa(addr));
and that would print for example 10.111.1.11
. But I need the IP in hex format, i.e. 0A6F010B
.
I came up with following, which will indeed print the IP in hex format:
for (i=0; i<32; i=i+8)
printf("%02X",(addr.s_addr>>i) % 256) ;
But it seems to me that my approach is needlessly complicated. I need two steps (two conversions). I would like to simplify my code, if possible, and print the hex IP directly from res->ai_addr->sa_data
(without having to store the data in addr.s_addr
first).
I know that the data is there in res->ai_addr->sa_data
. I can print it with:
for (i=0; i<14; i++)
printf("%d", res->ai_addr->sa_data[i]);
printf("\n");
and I get following output (which corresponds to 10.111.1.11
):
001011111100000000
But the format is not as straightforward as in the previous example. For example for 172.25.0.31
I get this output:
00-842503100000000
Thus my question:
How can I convert this gibberish into hex IP adress?