问题描述:
busybox udhcpc获取IP,但没有自动将获取到的ip设置到网卡上,并且没有自动设置网关,路由表等。必须手动设置才能连接外网。
解决方案:
udhcpc可以通过-s参数指定运行脚本,当获取到ip地址后,会自动运行这个脚本,从而自动将获取到的ip地址设置到网卡,并自动设置网关等。脚本的名字没有限制,busybox官网给的脚本如下:
default.script
#!/bin/sh
# udhcpc script edited by Tim Riker <Tim@Rikers.org>
RESOLV_CONF="/etc/resolv.conf"
[ -n "$1" ] || { echo "Error: should be called from udhcpc"; exit 1; }
NETMASK=""
[ -n "$subnet" ] && NETMASK="netmask $subnet"
BROADCAST="broadcast +"
[ -n "$broadcast" ] && BROADCAST="broadcast $broadcast"
case "$1" in
deconfig)
echo "Setting IP address 0.0.0.0 on $interface"
busybox ifconfig $interface 0.0.0.0
;;
renew|bound)
echo "Setting IP address $ip on $interface"
busybox ifconfig $interface $ip $NETMASK $BROADCAST
if [ -n "$router" ] ; then
echo "Deleting routers"
while busybox route del default gw 0.0.0.0 dev $interface ; do
:
done
metric=0
for i in $router ; do
echo "Adding router $i"
busybox route add default gw $i dev $interface metric $metric
: $(( metric += 1 ))
done
fi
echo "Recreating $RESOLV_CONF"
# If the file is a symlink somewhere (like /etc/resolv.conf
# pointing to /run/resolv.conf), make sure things work.
realconf=$(readlink -f "$RESOLV_CONF" 2>/dev/null || echo "$RESOLV_CONF")
tmpfile="$realconf-$$"
> "$tmpfile"
[ -n "$domain" ] && echo "search $domain" >> "$tmpfile"
for i in $dns ; do
echo " Adding DNS server $i"
echo "nameserver $i" >> "$tmpfile"
done
busybox mv "$tmpfile" "$realconf"
;;
esac
exit 0
最终效果:
root@XXXX:/# busybox udhcpc -i ethsta0 -s /system/bin/default.script
udhcpc: started, v1.26.2
start script
udhcpc: sending discover
udhcpc: sending select for 192.168.247.217
udhcpc: lease of 192.168.247.217 obtained, lease time 3600
start script
start script
deleting routers
route: ioctl 890c: No such process
interface:ethsta0
domain:domain
dns:192.168.247.42
Error connecting (No such file or directory)
Error connecting (No such file or directory)
root@XXXX:/ # ping 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=113 time=116 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=113 time=116 ms
64 bytes from 8.8.8.8: icmp_seq=3 ttl=113 time=139 ms
^C
--- 8.8.8.8 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 1999ms
rtt min/avg/max/mdev = 116.089/124.221/139.793/11.021 ms
root@XXXX:/ #
踩过的坑:
busybox udhcpc -s指定的这个脚本在指定解释器的时候,一定要确认解释器的路径是否正确。
我从网络复制过来的脚本,因为我的解释器路径为“#!system//bin/sh”,而网络默认的解释器路径为“#!/bin/sh”。导致-s指定的脚本一直不运行。
ref:
【Linux应用】udhcpc命令获取到ip后,但是没有生效(没有设置进去)_看图的博客-CSDN博客_udhcpc 获取不到ip
WAN Ethernet : DHCP/Static/PPPoE - LiveWithACat - 博客园
udhcpc 移植和使用_sean_8180的博客-CSDN博客_udhcpc 移植
linux udhcpc 后无法自动设置网卡ip - 陈富林 - 博客园
嵌入式Linux:解决busybox udhcpc获取IP但没有设置系统DNS的问题_R-QWERT的博客-CSDN博客