Linux 實現DHCP自動獲取IP地址
1. 在核心中新增以下選項:
Networking --->
Networking options --->
Packet socket //新增.配置CONFIG_PACKET
[ * ] IP: DHCP support //新增
[ * ] Network packet filtering (replaces ipchains) ---> //新增,後面子選項可不選,配置CONFIG_NETFILTER
說明:若沒選 Packet socket, [ * ] Network packet filtering (replaces ipchains) --->選項,在執行udhcpc命令時出現如下錯誤:
Make menuconfigARCH=arm
make ARCH=arm CROSS_COMPILE=arm-none-linux-gnueabi-
或者 執行 ./build.sh
build.sh內容如下:
#make ARCH=arm CROSS_COMPILE=arm-none-linux-gnueabi- sama5d3_defconfig
make ARCH=arm CROSS_COMPILE=arm-none-linux-gnueabi- zImage
make ARCH=arm CROSS_COMPILE=arm-none-linux-gnueabi- dtbs
cp arch/arm/boot/dts/mc-a5d36-gka.dtb ./
cp arch/arm/boot/zImage ./
cp arch/arm/boot/dts/mc-a5d36-gka.dtb /tftpboot/
cp zImage /tftpboot/
Networking Utilities --->
udhcp Server/Client --->
[] udhcp Server (udhcpd) //在此不作服務端,故不選。生成udhcpd命令
udhcp Client (udhcpc) //生成udhcpc命令 3. 建立配置檔案:
從busybox的examples/udhcp/下copy simple.script檔案到開發板/usr/share/udhcpc/下,並重命名為default.script
或者:vi usr/share/udhcpc/default.script 複製下面shell指令碼即可。
如果busybox沒有dhcpc命令則要做如下步驟:
a. 我在CSDN上下載的udhcp_0.9.8cvs20050303.orig.tar.gz檔案,
解壓後修改Makefile檔案
註釋12行的COMBINED_BINARY=1,否則不生成udhcpc命令。
在19行新增CROSS_COMPILE=arm-linux-
b. 修改後執行 #Make 命令,會看到生成的udhcpd,udhcpc可執行檔案
c. 將arm-linux交叉編譯得到udhcpd,udhcpc命令copy到根檔案系統中的usr/sbin
#udhcpc 所需shell指令碼
vi usr/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 del default 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
儲存退出後
chmod +x usr/share/udhcpc/default.script
執行命令
udhcpc -i eth0
啟動資訊如下:
udhcpc (v1.22.1) started
IPv6: ADDRCONF(NETDEV_UP): eth0: link is not ready
Ignore event for foreign ifindex 4
Sending discover...
macb f0028000.ethernet eth0: link up (100/Full)
IPv6: ADDRCONF(NETDEV_CHANGE): eth0: link becomes ready
Ignore event for foreign ifindex 4
Sending discover...
Sending select for 192.168.0.110...
Lease of 192.168.0.110 obtained, lease time 86400
deleting routers
route: SIOCDELRT: No such process
adding dns 192.168.0.1