Last active
December 23, 2021 20:20
-
-
Save safferli/70a858a460c0a084e35bcb71bc214273 to your computer and use it in GitHub Desktop.
Convert IP strings to integers and reverse using cpp/boost, and Rcpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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