2014-12-01 4 views
1

두 개의 테이블이 있습니다. 표 A는 'ip_address'필드와 다른 필드와 함께 'ip_start'및 'ip_end'(ip 범위)를 포함하는 다른 테이블 B를 포함합니다. 테이블 B에서 ip_address의 세부 사항을 추출하고 싶습니다. 예를 들어IP 주소에서 IP 주소 세부 정보 찾기 R

. 표 A는

ip_address : '178.91.21.2" 

표 B를 가지고있다

1. ip_start : "178.91.19.0" and ip_end : "178.91.19.255" 
2. ip_start : "178.91.21.0" and ip_end : "178.91.21.255" 

이제 내 쿼리는 누군가가 제안 할 수 R.에 내가 이것을 달성 할

나에게 표 B에 기록 2와 관련된 세부 사항을 반환해야 어떻게 할 수 있니?

+0

나는 C++있어 - 순수 R 버전에 비해 정수로 훨씬 빠르게 IPv4의 변환과 백업 [iptools] (https://gitlab.dds.ec/public/projects/bob.rudis/iptools) 패키지 . 그러나 IP 변환이 필요하고 다른 비트가 필요하지 않은 경우 독립 실행 형 버전 [http://datadrivensecurity.info/blog/posts/2014/May/vectorizing-ipv4-address-conversions-part-2/]이 있습니다. – hrbrmstr

답변

4

한 가지 방법이 있습니다. 지정하는 ipv4 주소는 기본적으로 8 바이트 16 진수의 십진수 표현이므로 아래와 같이 변환하여 십진 정수로 표시 할 수 있습니다.

a.b.c.d = a × 2563 + b × 2562 + c × 256 + d

그래서 우리는 테스트 벡터 (이 예에서는 ip), 그리고 (이 예에서는 ip.range) 범위의 데이터 프레임하고있는 간단한 연산을 사용하여 IP 이동하는 범위 식별 모두에 대해이 작업을 수행합니다.

# example dataset 
ip  <- c("178.91.21.2","178.91.19.30","178.91.20.100") 
ip.range <- data.frame(start=c("178.91.19.0", "178.91.20.0", "178.91.21.0"), 
         end= c("178.91.19.255","178.91.20.255","178.91.21.255"), 
         stringsAsFactors=FALSE) 
# function to convert ip address to decimal integer 
ip2integer <- function(ip) sapply(strsplit(ip,".",fixed=TRUE),function(x)sum(as.integer(x)*256^(3:0))) 
# convert ip and ranges to integer 
ip.int <- ip2integer(ip) 
range.int <- data.frame(sapply(ip.range,ip2integer)) 
# find indices, combine into result 
indx <- sapply(ip.int,function(x)with(range.int,which(x>=start & x <=end))) 
result <- cbind(ip,ip.range[indx,]) 
result 
#    ip  start   end 
# 3 178.91.21.2 178.91.21.0 178.91.21.255 
# 1 178.91.19.30 178.91.19.0 178.91.19.255 
# 2 178.91.20.100 178.91.20.0 178.91.20.255 
+0

덕분에 많은 jlhoward :) – rupali

+1

원래의 대답은 오류가있었습니다 : 정확한 기수는 255가 아니라 256입니다. 위의 코드가 변경되었습니다. – jlhoward