Created
October 26, 2014 01:47
-
-
Save hrbrmstr/f51cf8422738c01726db to your computer and use it in GitHub Desktop.
DNS lookups in R via sourceCpp and using only standard libraries (non-vectorized)
This file contains 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 <arpa/inet.h> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <netdb.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
using namespace Rcpp ; | |
// [[Rcpp::export]] | |
CharacterVector getNameInfo(std::string fqdn) { | |
struct addrinfo hints, *res, *res0; | |
int error; | |
char host[NI_MAXHOST]; | |
memset(&hints, 0, sizeof hints); | |
hints.ai_family = PF_UNSPEC; | |
hints.ai_socktype = SOCK_DGRAM; | |
error = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0); | |
if (error) { return(NA_STRING); } | |
int i = 0 ; | |
for (res = res0; res; res = res->ai_next) { | |
error = getnameinfo(res->ai_addr, res->ai_addrlen, | |
host, sizeof host, NULL, 0, NI_NUMERICHOST); | |
if (!error) { i++ ; } | |
} | |
CharacterVector results(i) ; | |
i = 0; | |
for (res = res0; res; res = res->ai_next) { | |
error = getnameinfo(res->ai_addr, res->ai_addrlen, | |
host, sizeof host, NULL, 0, NI_NUMERICHOST); | |
if (!error) { results[i++] = host ; } | |
} | |
freeaddrinfo(res0); | |
return(results) ; | |
} | |
// [[Rcpp::export]] | |
CharacterVector getAddrInfo(std::string ip) { | |
struct sockaddr_in sa; | |
sa.sin_family = AF_INET; | |
inet_pton(AF_INET, ip.c_str(), &sa.sin_addr); | |
char node[NI_MAXHOST]; | |
int res = getnameinfo((struct sockaddr*)&sa, | |
sizeof(sa), node, sizeof(node), NULL, 0, 0); | |
if (res) { return(NA_STRING); } | |
return(node); | |
} |
This file contains 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) | |
sourceCpp("dns.cpp") | |
getAddrInfo("74.125.226.66") | |
getNameInfo("google.com") |
This file contains 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
getAddrInfo("74.125.226.66") | |
## [1] "lga15s44-in-f2.1e100.net" | |
getNameInfo("google.com") | |
## [1] "74.125.226.39" "74.125.226.36" | |
## [3] "74.125.226.37" "74.125.226.34" | |
## [5] "74.125.226.38" "74.125.226.41" | |
## [7] "74.125.226.46" "74.125.226.35" | |
## [9] "74.125.226.33" "74.125.226.32" | |
## [11] "74.125.226.40" "2607:f8b0:4006:808::1006" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment