I want to convert IP addresses to binary in order to store them in MySQL DB. Online search says this is the most efficient way to store addresses, because ipv4 fits in 4 bytes and ipv6 in 16 bytes (What is the ideal datatype to store IP address in a mysql table?).
Now, it seems the common method to do that is using inet_pton() function which says: "inet_pton - convert IPv4 and IPv6 addresses from text to binary form" (http://man7.org/linux/man-pages/man3/inet_pton.3.html)
So my question is where is that binary number stored?
I use "sockaddr_in" struct with inet_pton as most online guides suggest, this is 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]; // zero this if you want to
};
struct in_addr {
unsigned long s_addr; // load with inet_ntop()
};
My code is 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 this IP address in sa:
inet_pton(AF_INET, ip, &sa.sin_addr);
/* for verifying purposes, I'm trying to print the result
to make sure I get a binary number (obviously, "%d" should
not print a binary yet I do get an int result) */
printf("%d\n", sa.sin_addr.s_addr);
}
}
The output I'm getting (using 127.0.0.1 as input) is: 16777343 <- This does not seem like a binary number, nor should printf print a binary if it actually were that. If inet_pton() converts an IP to binary then where is that binary.
If it's possible, I would prefer for a solution to include printf that prints the binary to verify the result (but that's just personal preference).
Edit
My question is not about how to convert int to binary, it is about inet_pton function output. I wanted to include a mechanism to convert int to binary in the answer as a bonus, but that's definitely not the main theme of the question - hence it's not duplicate of: Print an int in binary representation using C as @Andre Kampling suggested in the comments