c - inet_pton() function where is the binary? -
i want convert ip addresses binary in order store them in mysql db. online search says efficient way store addresses, because ipv4 fits in 4 bytes , ipv6 in 16 bytes (what ideal datatype store ip address in mysql table?).
now, seems common method using inet_pton() function says: "inet_pton - convert ipv4 , ipv6 addresses text binary form" (http://man7.org/linux/man-pages/man3/inet_pton.3.html)
so question binary number stored?
i use "sockaddr_in" struct inet_pton online guides suggest, how struct looks like:
struct sockaddr_in { short sin_family; // e.g. af_inet unsigned short sin_port; // e.g. htons(3490) struct in_addr sin_addr; // see struct in_addr, below char sin_zero[8]; // 0 if want }; struct in_addr { unsigned long s_addr; // load inet_ntop() };
my code basically:
#include <arpa/inet.h> int main(int argc, const char *argv[]) { if (argc >= 2) { char *ip = malloc(strlen(argv[1]) + 1); memcpy(ip, argv[1], strlen(argv[1]) + 1); struct sockaddr_in sa; char str[inet_addrstrlen]; // store ip address in sa: inet_pton(af_inet, ip, &sa.sin_addr); /* verifying purposes, i'm trying print result make sure binary number (obviously, "%d" should not print binary yet int result) */ printf("%d\n", sa.sin_addr.s_addr); } }
the output i'm getting (using 127.0.0.1 input) is: 16777343 <- not seem binary number, nor should printf print binary if that. if inet_pton() converts ip binary binary.
if it's possible, prefer solution include printf prints binary verify result (but that's personal preference).
edit
my question not how convert int binary, inet_pton function output. wanted include mechanism convert int binary in answer bonus, that's not main theme of question - hence it's not duplicate of: print int in binary representation using c @andre kampling suggested in comments
the output i'm getting (using 127.0.0.1 input) is: 16777343 <- not seem binary number
as commented, stored "binary" in computer. %d
conversion specifier of printf()
interprets bit pattern number.
if it's possible, prefer solution include printf prints binary verify result (but that's personal preference).
there's no conversion specifier "binary number" in printf()
, have write own implementation. e.g. int
, this:
#define imax_bits(m) ((m) /((m)%0x3fffffffl+1) /0x3fffffffl %0x3fffffffl *30 \ + (m)%0x3fffffffl /((m)%31+1)/31%31*5 + 4-12/((m)%31+3)) // use unsigned because don't want treat sign bit specially void print_binary(unsigned int i) { unsigned mask = 1 << (imax_bits((unsigned)-1) - 1); while (mask) { putchar(i & mask ? '1' : '0'); mask >>= 1; } }
the "strange" macro portably determining number of bits in unsigned int
, see this answer more info.
Comments
Post a Comment