I store IPs as 16 byte blobs (IPv4 in IPv6 syntax). You may do it differently.
And, sorry, I don’t care about Windows.
This is contributed under the same license as SQLite.
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "sqlite3.h"
#include "ntop.h"
void
ntop(
sqlite3_context *context
,int argc
,sqlite3_value **argv
){
static unsigned char i4[] = {0x00,0x00,0x00,0x00
,0x00,0x00,0x00,0x00
,0x00,0x00,0xff,0xff};
const unsigned char *b;
char *r;
int i;
(void)argc;
i = sqlite3_value_bytes(argv[0]);
if ((i == 4 || i == 16)
&& (b = sqlite3_value_blob(argv[0]))
&& (r = sqlite3_malloc(40))) {
if (i == 4)
b = (const unsigned char *)inet_ntop(AF_INET, b, r, 40);
else if (!memcmp(b, i4, sizeof(i4)))
b = (const unsigned char *)inet_ntop(AF_INET, b + 12, r, 40);
else
b = (const unsigned char *)inet_ntop(AF_INET6, b, r, 40);
if (b) {
r[39] = '\0'; /* strlen safety */
sqlite3_result_text(context, r, strlen(r), sqlite3_free);
} else
sqlite3_free(r);
}
}
sqlite3_create_function(db, "ntop", 1, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, ntop, 0, 0);