【问题标题】:Set static ip if not obtained from DHCP (script)如果未从 DHCP 获得,则设置静态 ip(脚本)
【发布时间】:2012-09-25 11:36:40
【问题描述】:

我在带有 linux 的嵌入式设备上工作。我想先使用 DHCP 客户端,但如果 DHCP 服务器没有响应,我想设置静态默认 IP。我想它应该不复杂,但我没有找到严格的答案。

我正在考虑 2 个解决方案(不幸的是,我可以在几天内对其进行测试):

  1. 我使用 ifconfig 设置静态 IP,然后调用 udhcpc。如果 udhcpc 得不到新的 IP,旧的会留下来。

  2. 我也可以先调用udhcpc,稍等一下,查看是否获取到IP。但这对我来说并不好。我不想在启动中添加任何等待程序。

BR 巴特克

我使用 udhcpc - 类似:

udhcpc -n -f -i eth0 
if ifconfig | grep -A1 eth0 | grep inet 
    then 

【问题讨论】:

    标签: linux ip dhcp ifconfig


    【解决方案1】:

    dhclient 应该通过租约声明支持回退 查看dhclient.conf 手册页。

    将这样的内容添加到您的dhclient.conf

    timeout 10;
    lease {
    interface "eth0";
    fixed-address 10.0.0.10;
    option subnet-mask 255.255.255.0;
    renew 2 2022/1/1 00:00:01;
    rebind 2 2022/1/1 00:00:01;
    expire 2 2022/1/1 0:00:01;
    }
    

    或者您可以为接口分配第二个 IP,例如 /etc/network/interfaces

    auto lo
    iface lo inet loopback
    iface eth0 inet dhcp
    
    auto eth0:1
    iface eth0:1 inet static
    address 10.10.10.2
    netmask 255.255.255.0
    

    【讨论】:

    • 我使用 udhcpc 并做了类似的东西: udhcpc -n -f -i eth0 if ifconfig | grep -A1 eth0 | grep inet 然后
    • 为什么不也auto eth0
    • @ygoe 为什么不auto <if> 会导致界面在引导过程中自动启动,而不是通过ifup 之类的手动方式启动。详情请查阅手册。
    【解决方案2】:

    虽然是一个老问题,但这里可能值得注意的是,Gentoo Linux 已经拥有这个功能很长时间了(我从 2004 年就开始使用它了)。 Gentoo 的网络配置文件 (/etc/conf.d/net) 允许在 DHCP 失败的情况下为任何接口轻松指定备用 IP 地址,例如:

    modules="dhclient"
    config_eth0="dhcp"
    config_eth1="dhcp"
    dhclient_eth1="nogateway"
    fallback_eth0="apipa"
    fallback_eth1="192.168.10.10/24"
    fallback_routes_eth1="default via 192.168.10.1"
    

    Maurizio 提供的使用 eth0:0 之类的别名的解决方案在许多(可能是大多数)情况下都很好,但不是全部。我遇到了一个软件,它不认为 eth0:0 是 eth0 的合适替代品,因为由于 DHCP 没有回答而未定义它,即使它是同一个端口。所以静态回退地址略优于别名解决方案。

    【讨论】:

      猜你喜欢
      • 2016-01-05
      • 2015-10-14
      • 2014-02-19
      • 1970-01-01
      • 1970-01-01
      • 2015-11-21
      • 1970-01-01
      • 2022-11-27
      • 2021-08-24
      相关资源
      最近更新 更多