[R] IP-Address
David Huffer
David.Huffer at csosa.gov
Fri Jun 19 18:40:58 CEST 2009
On Wednesday, June 17, 2009 3:33 PM, edwin<edwin7 at web.de> wrote:
> Sorry, David has just told my that it was a mistake in my
> example (Thanks David). I had a wrong idea. The right idea is:
> make a ip range, when the number increament without an gap (and
> with maximum number: 255, see example down).
> In case my initial example would be:
> 162.131.58.1
> 162.131.58.2
> 162.131.58.3
> 162.131.58.4
> 162.131.58.5
> 162.131.58.6
> The Range is: 162.131.58.1 - 162.131.58.6
> 162.132.58.20
> 162.132.58.20 (no range)
> 162.252.20.21
> 162.252.20.21 (no range)
> 162.254.20.22
> 162.254.20.22 (no range)
> 163.253.7.23
> 163.253.7.23 (no range)
> 163.253.20.25
> 163.253.20.25 (no range)
> 161.138.45.226
> 161.138.45.226 (no range)
> Another example: [...]
Edwin, here's a function that does what you want. it probably
doesn't return the ranges the way you'll need them, but you can
play around with that part:
iprange <- function ( x ) {
ip.set <- x
ip <- do.call (
rbind
, lapply (
ip.set
, function ( x ) {
as.numeric (
unlist (
strsplit (
as.character ( x )
, split = "."
, fixed = TRUE
)
)
)
}
)
)
ip <- cbind (
ip
, ip [ , 1 ] * 256^3
+ ip [ , 2 ] * 256^2
+ ip [ , 3 ] * 256
+ ip [ , 4 ]
)
ip.set <- ip.set [ order ( ip [ , 5] ) ]
ip <- ip [ order ( ip [ , 5] ) , ]
index.start <- which ( c ( -Inf , diff ( ip [ , 5] ) ) != 1 )
index.end <- c ( index.start [-1] - 1 , tail ( index.start , 1 ) )
iprange <- cbind (
ip.set [ index.start ]
, ifelse ( ip.set [ index.start ] == ip.set [ index.end ] , NA , ip.set [ index.end ] )
)
cat ("ip addresses:\n")
cat (
ip.set
, sep = "\n"
)
cat ("\nip ranges:\n")
cat (
paste (
ip.set [ index.start ]
, ifelse (
ip.set [ index.start ] == ip.set [ index.end ]
, "(no range)"
, paste (
"to"
, ip.set [ index.end ]
)
)
)
, sep = "\n"
)
invisible ( iprange )
}
test <- iprange (
c (
"162.131.58.1" , "163.253.7.23"
, "162.131.58.2" , "163.253.20.25"
, "162.131.58.3" , "161.138.45.226"
, "162.131.58.4" , "169.131.58.1"
, "162.131.58.5" , "169.131.58.2"
, "162.131.58.6" , "169.132.58.3"
, "162.132.58.20" , "250.131.58.4"
, "162.252.20.21" , "250.131.58.5"
, "162.254.20.22" , "250.131.58.7"
)
)
test
HTH
--
David
-----------------------------------------------------
David Huffer, Ph.D. Senior Statistician
CSOSA/Washington, DC david.huffer at csosa.gov
More information about the R-help
mailing list