Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Convert IP strings to integers and reverse using cpp/boost, and Rcpp
library(Rcpp)
library(inline)
Rcpp::sourceCpp("iputils.cpp")
# test convert an IPv4 string to integer
rinet_pton("10.0.0.0")
#[1] 167772160
rinet_pton(c("10.0.0.0", "192.168.0.1"))
# [1] 167772160 -1062731775
# test conversion back
rinet_ntop(167772160)
#[1] "10.0.0.0"
#include <Rcpp.h>
#include <boost/asio/ip/address_v4.hpp>
using namespace Rcpp;
// [[Rcpp::export]]
IntegerVector rinet_pton (CharacterVector ip) {
int n = ip.size();
IntegerVector out(n);
for(int i = 0; i < n; ++i) {
out[i] = boost::asio::ip::address_v4::from_string(ip[i]).to_ulong();
}
return out;
}
// [[Rcpp::export]]
CharacterVector rinet_ntop (IntegerVector addr) {
int n = addr.size();
CharacterVector out(n);
for(int i = 0; i < n; ++i) {
out[i] = boost::asio::ip::address_v4(addr[i]).to_string();
}
return out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment