诗歌rails之获取本地ip地址

都是基于linux平台的

典型的不好的办法是
Ruby代码
  1. `ifconfig`.slice(/[\d|.]+  Bcast/).sub(/  Bcast/,'')  



人家比较好的办法是
Ruby代码
  1. ###############  
  2. # local_ip  
  3. # This is to get around using ifconfig shell calls to get an ip address  
  4. # Described here  
  5. #http://coderrr.wordpress.com/2008/05/28/get-your-local-ip-address/  
  6. ###############  
  7. require 'socket'  
  8. def get_local_ip    
  9.   orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true    
  10. # turn off reverse DNS resolution temporarily    
  11.    
  12.   UDPSocket.open do |s|    
  13.     s.connect '64.233.187.99', 1  #google的ip  
  14.     s.addr.last    
  15.   end    
  16. ensure    
  17.   Socket.do_not_reverse_lookup = orig    
  18. end    
posted @ 2009-08-24 17:29  麦飞  阅读(662)  评论(0编辑  收藏  举报