[R] INET_NTOA equivalent?

Martin Maechler maechler at stat.math.ethz.ch
Thu Apr 24 11:33:40 CEST 2014


>>>>> "EL" == Eberhard Lisse <nospam at lisse.NA>
>>>>>     on Thu, 24 Apr 2014 01:21:37 +0100 writes:

    EL> In MySQL
    EL> SELECT INET_ATON('127.0.0.1')

    EL> returns the integer 2130706433

    EL> Is there a function in R to reverse that, ie so that something like

    EL> ip <- inet_ntoa(2130706433)

    EL> would put  '127.0.0.1' into ip?

almost:

  install.packages("sfsmisc")
  require("sfsmisc")

  # NTOA :

  > digitsBase(2130706433, base = 256)
  Class 'basedInt'(base = 256) [1:1]
       [,1]
  [1,]  127
  [2,]    0
  [3,]    0
  [4,]    1

  # ATON :

  > as.intBase(digitsBase(2130706433, base = 256), base = 256)
	   1 
  2130706433 
  > 

So, an easy solution seems


> ip.ntoa <- function(n) paste(sfsmisc::digitsBase(n, base = 256), collapse=".")
> ip.ntoa(2130706433)
[1] "127.0.0.1"
> 

but that does not vectorize (work for  length(n) > 1 )
correctly.

The correct solution then is

ip.ntoa <- function(n) 
    apply(sfsmisc::digitsBase(n, base = 256), 2, paste, collapse=".")

and that does work nicely:

> ip.ntoa(1000000000+ (0:10))

 [1] "59.154.202.0"  "59.154.202.1"  "59.154.202.2"  "59.154.202.3"  "59.154.202.4" 
 [6] "59.154.202.5"  "59.154.202.6"  "59.154.202.7"  "59.154.202.8"  "59.154.202.9" 
[11] "59.154.202.10"

right ?

--
Martin Maechler, ETH Zurich




More information about the R-help mailing list