嵌入式Linux通过DHCP自动获取IP地址的方法
1.
在编译嵌入式Linux内核时添加以下选项:
Networking --->
[*] Networkingsupport
Networkingoptions --->
<* > Packet socket //添加.配置CONFIG_PACKET
[ * ] IP: DHCPsupport //添加
[ * ] Network packet filtering (replaces ipchains) ---> //添加,后面子选项可不选,配置CONFIG_NETFILTER
说明:若没选<* > Packetsocket, [ * ] Network packet filtering (replaces ipchains) --->选项,在执行udhcpc命令时出现如下错误:
~ # udhcpc
udhcpc (v0.9.9-pre)started
udhcpc[208]: udhcpc (v0.9.9-pre)started
FATAL: couldn't listen on socket, Addressfamily not supported by protocol
udhcpc[208]: FATAL: couldn't listen onsocket, Address family not supported by protocol
2.
在编译Busybox中添加以下选项:
Networking Utilities --->
udhcp Server/Client --->
[] udhcp Server (udhcpd) //在此不作服务端,故不选。生成udhcpd命令
[*] udhcp Client (udhcpc) //生成udhcpc命令
[ ] Lease display utility(dumpleases)
[ ] Log udhcp messages to syslog (instead ofstdout)
[ ] Compile udhcp with noisy debugging messages
3.
建相关配置文件
从busybox的examples/udhcp/下copy simple.script文件到开发板/usr/share/udhcpc/下,并重命名为default.script,udhcp_0.9.8cvs20050303.orig.tar.gz中也有这样的文件。
[root@localhost root]# viusr/share/udhcpc/default.script
#!/bin/sh
# udhcpc script edited by Tim Riker
[ -z "$1" ] && echo"Error: should be called from udhcpc" && exit 1
RESOLV_CONF="/etc/resolv.conf"
[ -n "$broadcast" ] &&BROADCAST="broadcast $broadcast"
[ -n "$subnet" ] &&NETMASK="netmask $subnet"
case "$1" in
deconfig)
/sbin/ifconfig $interface 0.0.0.0
;;
renew|bound)
/sbin/ifconfig $interface $ip $BROADCAST $NETMASK
if [ -n "$router" ] ; then
echo "deleting routers"
while route deldefault gw 0.0.0.0 dev $interface ; do
:
done
for i in $router ; do
route add default gw $i dev $interface
done
fi
echo -n > $RESOLV_CONF
[ -n "$domain" ] && echo search $domain >> $RESOLV_CONF
for i in $dns ; do
echo adding dns $i
echo nameserver $i >> $RESOLV_CONF
done
;;
esac
exit 0
4.
重启开发板,执行udhcpc就可自动获取IP地址了,以下是执行udhcpc的输出信息:
~ # udhcpc
udhcpc (v0.9.9-pre)started
udhcpc[228]: udhcpc (v0.9.9-pre)started
Sending discover...
udhcpc[228]: Sending discover...
Sending select for 192.168.1.109...
udhcpc[228]: Sending select for192.168.1.109...
Lease of 192.168.1.109 obtained, lease time86400
udhcpc[228]: Lease of 192.168.1.109obtained, lease time 86400
deleting routers
route: SIOC[ADD|DEL]RT: No such process
adding dns 192.168.0.1
5.
如果是双网卡必须用参数指明
例:udhcpc -i eth1
附:如何在LinuxPE中用脚本获取DHCP Server的IP地址
Inside the LinuxPE environment, afterenable udhcp service:
/sbin/udhcpc start
that
Server_IP=`cat /tmp/resolv.conf | cut -d "
用busybox生成的udhcpc命令,关键要把busybox的目录下examples/udhcp/simple.script 脚本文件做为default.script拷贝,使用下面的命令 cp /examples/udhcpc/simple.script /usr/share/udhcpc/default.script
同时要在编译busybox时选中使用usr的选项,否则需要把simple.script拷贝到 /share/man/udhcp/default.script
内核选项里也要把DHCP的选项加上。