`
oldrev
  • 浏览: 230204 次
  • 性别: Icon_minigender_1
  • 来自: 昆明
社区版块
存档分类
最新评论

一个 Ubuntu获取铁通独立 IP 的脚本

阅读更多
我的铁通 ADSL 最近几天经常被铁通分配 10.*.*.* 的内网 IP,让我的 MLDonkey 基本上用不了。今天有空顺手写了个脚本自动测试 IP,如果是内网的就断线重拨,直到获得外网 IP 为止 

=begin
    一个 Ubuntu Linux 下自动拨号获取铁通独立 IP 的脚本
    作者:oldrev <oldrev@gmail.com>
    授权: Public Domain
=end

require 'socket'  

# 获取本机 IP 代码来自:
# http://www.iteye.com/topic/160284

# bits/ioctls.h  
SIOCGIFADDR    = 0x8915          # get PA address            

def get_ip_address(iface)  
    begin  
        sock = UDPSocket.new  
        buf = [iface,""].pack('a16h16')  
        sock.ioctl(SIOCGIFADDR, buf);  
        sock.close  
        buf[20..24] 
    rescue  
        nil  
    end  
end  

def getip
    get_ip_address('ppp0') #通常 ADSL 连接是 ppp0
end

def format_ip ip   
    if ip != nil then ip.unpack("CCCC").join(".") end
end

def recall
    puts "正在断开...."
    system 'poff dsl-provider'
    sleep 1
    puts "正在拨号...."
    system 'pon dsl-provider'
end

def needs_recall(ip)
    ip == nil || ip[0] <= 10 #内网 ip 通常是 10.*.*.*
end

if $0 == __FILE__ then
    ip = getip
    puts "当前 IP 地址是: #{format_ip(ip)}"

    if not needs_recall(ip) then
        puts "不需要重新拨号"
        exit()
    end

    while needs_recall(ip)
        recall
        sleep 4
        ip = getip
        puts "新 IP: #{format_ip(ip)}"
    end

end  



Happy Hacking!
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics