Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
synikitin opened this issue Jun 5, 2019 · 1 comment
Open

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

synikitin opened this issue Jun 5, 2019 · 1 comment

Comments

@synikitin
Copy link

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.

hrbrmstr added a commit that referenced this issue Jun 6, 2019
@hrbrmstr
Copy link
Owner

hrbrmstr commented Jun 6, 2019

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants