2013-01-16 84 views

回答

23

可以發出一個system()命令操作系統:

  • 在Windows中可以使用ipconfig
  • 在Linux中,使用ifconfig

例如,在Windows嘗試調用system()與參數intern=TRUE的結果返回給R:

x <- system("ipconfig", intern=TRUE) 

這將返回:

x 
[1] ""                 
[2] "Windows IP Configuration"           
[3] ""                 
[4] ""                 
[5] "Wireless LAN adapter Wireless Network Connection:"     
[6] ""                 
[7] " Connection-specific DNS Suffix . : tbglondon.local"    
[8] " Link-local IPv6 Address . . . . . : fe80::c0cb:e470:91c7:abb9%14" 
[9] " IPv4 Address. . . . . . . . . . . : 10.201.120.184"    
[10] " Subnet Mask . . . . . . . . . . . : 255.255.255.0"    
[11] " Default Gateway . . . . . . . . . : 10.201.120.253"    
[12] ""                 
[13] "Ethernet adapter Local Area Connection:"        
[14] ""                 
[15] " Connection-specific DNS Suffix . : tbglondon.local"    
[16] " Link-local IPv6 Address . . . . . : fe80::9d9b:c44c:fd4d:1c77%11" 
[17] " IPv4 Address. . . . . . . . . . . : 10.201.120.157"    
[18] " Subnet Mask . . . . . . . . . . . : 255.255.255.0"    
[19] " Default Gateway . . . . . . . . . : 10.201.120.253"    
[20] ""                 
[21] "Tunnel adapter Local Area Connection* 13:"       
[22] ""                 
[23] " Media State . . . . . . . . . . . : Media disconnected"   
[24] " Connection-specific DNS Suffix . : "        
[25] ""                 
[26] "Tunnel adapter isatap.tbglondon.local:"        
[27] ""                 
[28] " Media State . . . . . . . . . . . : Media disconnected"   
[29] " Connection-specific DNS Suffix . : tbglondon.local"    
[30] ""                 
[31] "Tunnel adapter Teredo Tunneling Pseudo-Interface:"     
[32] ""                 
[33] " Media State . . . . . . . . . . . : Media disconnected"   
[34] " Connection-specific DNS Suffix . : "        

現在你可以使用grepIPv4找到行:

x[grep("IPv4", x)] 
[1] " IPv4 Address. . . . . . . . . . . : 10.201.120.184" 
[2] " IPv4 Address. . . . . . . . . . . : 10.201.120.157" 

而且只提取IP地址:

z <- x[grep("IPv4", x)] 
gsub(".*? ([[:digit:]])", "\\1", z) 
"10.201.120.184" "10.201.120.157" 
+4

和UNIX下'ifconfing'像系統... – agstudy

+0

@agstudy謝謝。回答編輯 – Andrie

+0

非常感謝你! – rdatasculptor

-1

這檢索正是你想要的:

system('ipconfig getifaddr en0') 

192.168.1.73 
+0

您的命令在R或CMD窗口(在我的Window 7工作站上)中不起作用。你能重新測試一下嗎?可能只是針對你的機器?它只是返回一個廣泛的'ipconfig'命令幫助手冊。 –

3

我最近創建使用ipify.org做這個確切的事情最小包裝。

用法很簡單,你可以安裝使用devtools和github上。

library(devtools) install_github("gregce/ipify")

一旦安裝,其一樣容易加載庫和一個函數調用...

library(ipify) get_ip()

0

雖然@andrie非常深入淺出解釋它,我相信它幫助我們瞭解它的功能很多。

所以從那裏只有共享一個襯墊代碼,而無需安裝任何其他程序包。

gsub(".*? ([[:digit:]])", "\\1", system("ipconfig", intern=T)[grep("IPv4", system("ipconfig", intern = T))]) 

希望這會有所幫助!