Skip to content

Instantly share code, notes, and snippets.

@safferli
Last active December 23, 2021 20:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save safferli/70a858a460c0a084e35bcb71bc214273 to your computer and use it in GitHub Desktop.
Save safferli/70a858a460c0a084e35bcb71bc214273 to your computer and use it in GitHub Desktop.
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