iptools icon indicating copy to clipboard operation
iptools copied to clipboard

Map a host IP and a subnet length into a subnet range

Open synikitin opened this issue 6 years ago • 1 comments

Hello,

I ran into an issue of mapping host ips and subnet lengths collected from flow data into subnet ranges, and did not find a way to make it with the current version of iptools. Here is a working function I wrote to solve the problem:

library(magrittr)

host_ip <- c("1.2.3.4", "4.3.2.1")
subnet_len <- c(24L, 25L)

ip_to_subnet <- function(host_ip, subnet_len) {
  
  # binary representation of host ips
  ip <- iptools::ip_to_binary_string(host_ip) %>% 
    stringr::str_split("", simplify = TRUE) %>% 
    `mode<-`("double")
  
  # binary representation of subnet masks
  default_mask <- stringr::str_c(rep("0", 32L), collapse = "")
  mask <- stringr::`str_sub<-`(
    default_mask,
    start = 1, end = subnet_len,
    value = stringr::str_dup("1", subnet_len)
    ) %>% 
    stringr::str_split("", simplify = TRUE) %>% 
    `mode<-`("double")
  
  # numeric representation of subnet ips
  subnet_ip <- iptools::numeric_to_ip(
    (ip * mask) %*% 2 ^ (31:0)
  )
  
  # octet representation of subnet ranges
  subnet_range <- stringr::str_c(subnet_ip, subnet_len, sep = "/")
  subnet_range
}


ip_to_subnet(host_ip, subnet_len)

Maybe a variant of this can make into the package.

synikitin avatar Jun 05 '19 18:06 synikitin

Many thanks for using the package and submitting this!

I ended up using the underlying Boost AsioHeaders network_v4 class functions for this and added a convenience wrapper for it (https://github.com/hrbrmstr/iptools/blob/master/R/ip-to-subnet.R#L1-L41)

host_ip <- c("1.2.3.4", "4.3.2.1")
subnet_len <- c(24L, 25L)
ip_to_subnet(host_ip, subnet_len)
## [1] "1.2.3.0/24" "4.3.2.0/25"

ip_to_subnet(c("1.2.3.4/24", "4.3.2.1/25"))
## [1] "1.2.3.0/24" "4.3.2.0/25"

Let me know if it doesn't handle any inputs you toss at it (I've only done light testing).

It should be on the main branch now.

hrbrmstr avatar Jun 06 '19 12:06 hrbrmstr