Analysis of WiFi Configuration Script in Embedded Linux

The embedded Linux system generally supports WiFi networking, which can be achieved through sh scripts or other programming languages.

This article introduces the execution principle of a script that configures WiFi using sh scripts.

1. Introduction to sh Script for WiFi Networking

Here, we take the WiFi startup script in the Feilin development board as an example.

Analysis of WiFi Configuration Script in Embedded Linux

In the serial port of the Feilin development board, execute the following command (calling the fltest_wifi.sh script and specifying some parameters) to connect to WiFi:
fltest_wifi.sh -i mlan0 -s "wifi_name" -p wifi_password
  • wifi_name is your WiFi name
  • wifi_password is the corresponding WiFi password

Then the ifconfig command can be used to check the board’s IP information:

[root@ok3568:/usr/sbin]# ifconfig
lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:239 errors:0 dropped:0 overruns:0 frame:0
          TX packets:239 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:346556 (338.4 KiB)  TX bytes:346556 (338.4 KiB)

mlan0     Link encap:Ethernet  HWaddr E8:FB:1C:66:AF:DF
          inet addr:192.168.5.111  Bcast:192.168.5.255  Mask:255.255.255.0
          inet6 addr: fe80::eafb:1cff:fe66:afdf/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1799 errors:0 dropped:0 overruns:0 frame:0
          TX packets:981 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:109635 (107.0 KiB)  TX bytes:331552 (323.7 KiB)

[root@ok3568:/usr/sbin]#

As we can see, the IP of the mlan0 network interface is 192.168.5.111

2. Analysis of fltest_wifi.sh Script File

Next, let’s analyze the content of the fltest_wifi.sh script.

2.1 Analysis of the Beginning Part

First, let’s look at this segment of the script:

cnt1=`ps aux | grep hostapd | grep -v grep  | wc -l`
if [ "$cnt1" != "0" ];then
        killall hostapd > /dev/null
fi

/etc/init.d/S80dnsmasq stop > /dev/null

Analysis:

First, a command is executed to confirm the number of running hostapd processes, which is stored in the variable cnt1

  • ps aux: View detailed information about all currently running processes in the system
  • | grep hostapd | grep -v grep: Match lines containing hostapd and not containing grep
  • | wc -l: Count the number of lines (word count)

Note: “ps aux” is actually a command form that combines several commands

  • “ps” is short for “process status”
  • “a” means show processes for all users, not just the current user
  • “u” means display process information in a user-oriented detailed format
  • “x” means show processes that do not have a controlling terminal

hostapd is a software used to create Wireless Access Points (WAP) in Linux

The function of hostapd is to create AP, as it is to connect to WiFi, not to create a hotspot, so if there is a hostapd process, it should be stopped.

Analysis of WiFi Configuration Script in Embedded Linux

If cnt1 is not 0, then kill all hostapd processes

  • killall: Used to terminate one or more running processes by process name
  • >: A common redirection operation in Linux
  • /dev/null: A special device file that can receive any written data but will discard it

Then, execute /etc/init.d/S80dnsmasq stop

2.1.1 Analysis of S80dnsmasq Script

S80dnsmasq is also a script with the content:

#!/bin/sh

[ -f /etc/dnsmasq.conf ] || exit 0

case "$1" in
        start)
                printf "Starting dnsmasq: "
                start-stop-daemon -S -x /usr/sbin/dnsmasq
                [ $? = 0 ] && echo "OK" || echo "FAIL"
                ;;
        stop)
                printf "Stopping dnsmasq: "
                start-stop-daemon -K -q -x /usr/sbin/dnsmasq
                [ $? = 0 ] && echo "OK" || echo "FAIL"
                ;;
        restart|reload)
                $0 stop
                $0 start
                ;;
        *)
                echo "Usage: $0 {start|stop|restart}"
                exit 1
esac

exit 0

First, let’s look at this line, which checks whether the specified file dnsmasq.conf exists and is a regular file; if not, it exits

[ -f /etc/dnsmasq.conf ] || exit 0

Analysis:

  • [ and ]: This is a shorthand syntax for the test command
  • -f: An option for the test command to check if the specified object is a regular file
  • ||: A logical OR operator in shell
  • exit 0: A shell command to exit the current script execution environment

Next, the case is used to determine the input arguments of the script and process them; if the argument is stop, it executes:

printf "Stopping dnsmasq: "
start-stop-daemon -K -q -x /usr/sbin/dnsmasq
[ $? = 0 ] && echo "OK" || echo "FAIL"

Analysis:

  • start-stop-daemon is a tool for managing daemons; the above command specifically operates on the dnsmasq daemon.
  • -K: This option is generally used to send a signal to the specified daemon to stop it.
  • -q: Means “quiet”, i.e., in quiet mode, the command execution will not produce too much additional output.
  • -x /usr/sbin/dnsmasq: Here, it specifies the executable file path to operate on.

dnsmasq is a lightweight DNS forwarder and DHCP server software in Linux.

2.1.2 dnsmasq.conf

Let’s take a look at the content of dnsmasq.conf:

interface=uap0
bind-interfaces
except-interface=lo
dhcp-range=192.168.2.100,192.168.2.254,12h
dhcp-option=3,192.168.2.1
dhcp-option=6,192.168.2.1

This is a configuration file for the dnsmasq software

  • interface=uap0: Specifies the network interface name to bind or perform relevant network operations.

  • bind-interfaces: Indicates that the software should bind to the specified network interface.

  • except-interface=lo: Indicates that the local loopback interface should be excluded from the binding operation.

  • dhcp-range=192.168.2.100,192.168.2.254,12h: Specifies the range of IP addresses to assign to clients and the lease duration.

  • dhcp-option=3,192.168.2.1: Sets the default gateway option.

  • dhcp-option=6,192.168.2.1: Sets the DNS server option.

2.2 Parameter Parsing Section

usage() and parse_args() are two functions to print help information and parse the script’s input parameters

function usage()
{
    echo "Usage: -i <wifi> -s <ssid> -p <password>"
    echo "eg: ./wifi.sh -i mlan0 -s bjforlinx -p 12345678 "
    echo "eg: ./wifi.sh -i mlan0 -s bjforlinx -p NONE "
    echo " -i : mlan0 or mlan1"
    echo " -s : wifi ssid"
    echo " -p : wifi password or NONE"
}

function parse_args()
{
    while true; do
        case "$1" in
            -i ) wifi=$2;echo wifi $wifi;shift 2 ;;
            -s ) ssid=$2;echo ssid $ssid;shift 2 ;;
            -p ) pasw=$2;echo pasw $pasw;shift 2 ;;
            -h ) usage; exit 1 ;;
            * ) break ;;
        esac
    done
}

if [ $# != 6 ]
then
    usage;
    exit 1;
fi

parse_args $@

The function part of the script is to check whether the input parameters of fltest_wifi.sh are 6:

  • If not, print help information and exit
  • If yes, parse the 6 input parameters of the script

Let’s review the 6 parameters:

fltest_wifi.sh -i mlan0 -s "wifi_name" -p wifi_password

2.3 Connecting to WiFi Section

Connecting to WiFi uses the wpa_supplicant tool, which stands for Wi-Fi Protected Access Supplicant.

Analysis of WiFi Configuration Script in Embedded Linux

2.3.1 Modifying the wpa_supplicant Configuration File

if [ -e /etc/wpa_supplicant.conf ]
then
    rm /etc/wpa_supplicant.conf
fi
    echo \#PSK/TKIP >> /etc/wpa_supplicant.conf
	echo ctrl_interface=/var/run/wpa_supplicant >>/etc/wpa_supplicant.conf
	echo ctrl_interface_group=0 >>/etc/wpa_supplicant.conf
	echo update_config=1 >>/etc/wpa_supplicant.conf
	echo network={ >>/etc/wpa_supplicant.conf
    echo ssid=\"$ssid\" >>/etc/wpa_supplicant.conf
	echo scan_ssid=1 >>/etc/wpa_supplicant.conf
    if [ $pasw == NONE ]
	then
		echo key_mgmt=NONE >>/etc/wpa_supplicant.conf
	else
		echo psk=\"$pasw\" >>/etc/wpa_supplicant.conf
		echo key_mgmt=WPA-EAP WPA-PSK IEEE8021X NONE >>/etc/wpa_supplicant.conf
		echo group=CCMP TKIP WEP104 WEP40 >>/etc/wpa_supplicant.conf
	fi
    echo } >>/etc/wpa_supplicant.conf

We can look at the final modified content of wpa_supplicant.conf

#PSK/TKIP
ctrl_interface=/var/run/wpa_supplicant
ctrl_interface_group=0
update_config=1
network={
ssid="MERCURY_3394"
scan_ssid=1
psk="2H2+O2=2H2O"
key_mgmt=WPA-EAP WPA-PSK IEEE8021X NONE
group=CCMP TKIP WEP104 WEP40
}

2.3.2 Some ifconfig Commands to Disable Network Interfaces

ifconfig -a|grep mlan0 |grep -v grep  > /dev/null
if [ $? -eq 0 ]
then
	ifconfig mlan0 down > /dev/null
fi

ifconfig -a|grep mlan1 |grep -v grep  > /dev/null
if [ $? -eq 0 ]
then
	ifconfig mlan1 down > /dev/null
fi

ifconfig -a|grep eth0 |grep -v grep  > /dev/null
if [ $? -eq 0 ]
then
	ifconfig eth0 down > /dev/null
fi

ifconfig -a|grep eth1 |grep -v grep  > /dev/null
if [ $? -eq 0 ]
then
	ifconfig eth1 down > /dev/null
fi

Analysis:

  • ifconfig -a: Used to view detailed configuration information of all network interfaces in the system
  • Then check for mlan0, mlan1, eth0, eth1; if these network interfaces exist, they will be disabled

2.3.3 Stopping wpa_supplicant

ps -fe|grep wpa_supplicant |grep -v grep > /dev/null
if [ $? -eq 0 ]
then
	kill -9 $(pidof wpa_supplicant)
fi

Analysis: ps -fe is used to view the status information of all processes started by all users in the system

  • -f means to display process information in full format
  • -e means to show processes for all users

If the wpa_supplicant process is running, it will be killed

2.3.4 Enabling Specified Network Interfaces

sleep 1
ifconfig $wifi up > /dev/null 
sleep 1
  • up is a parameter in the ifconfig command that sets the network interface to enabled state.
  • $wifi: is a variable assigned in parse_args(), which is the mlan0 network interface.

2.3.5 Configuring Network through wpa_supplicant

(wpa_supplicant -Dnl80211,wext -i$wifi -c/etc/wpa_supplicant.conf  >/dev/null) &
echo "waiting..."
sleep 3
wpa_cli -i$wifi status |grep COMPLETED |grep -v grep >/dev/null
if [ $? -eq 0 ]
then
	udhcpc -i $wifi
	echo "Finished!" 
else
	echo "try to connect again..."
sleep 3
wpa_cli -i$wifi status |grep COMPLETED |grep -v grep >/dev/null
	if [ $? -eq 0 ]
	then
		udhcpc -i $wifi
		echo "nameserver 114.114.114.114" > /etc/resolv.conf
		echo "Finished!"
	else
		echo "************************************************"
			echo "connect failed, please check the password and ssid"
			kill -9 $(pidof wpa_supplicant)
			exit 1
	fi
fi

First, let’s look at the first command, which starts the wpa_supplicant process in the background and performs wireless network configuration operations according to the specified parameters

(wpa_supplicant -Dnl80211,wext -i$wifi -c/etc/wpa_supplicant.conf  >/dev/null) &

Let’s analyze the parameters of wpa_supplicant:

  • -D: Used to specify the driver type.
  • nl80211 and wext: Two common wireless network card driver types.
  • -i: Used to specify the wireless network interface name to connect to.
  • -c: Used to specify the path of the configuration file.

After waiting for 3 seconds, let’s look at this command, which checks whether the authentication process of connecting to WiFi through the specified wireless network interface has been completed:

wpa_cli -i$wifi status |grep COMPLETED |grep -v grep >/dev/null

Analysis:

  • wpa_cli: A command-line tool used to interact with the wpa_supplicant process.
  • -i: Used to specify the wireless network interface name to connect to.
  • status: An operation of the wpa_cli command to query the connection status information.
  • Then check if the output contains the word COMPLETED

We can manually input the first part of the command:

[root@ok3568:/usr/sbin]# wpa_cli -imlan0 status
bssid=f4:ee:14:1b:33:94
freq=2412
ssid=MERCURY_3394
id=0
mode=station
pairwise_cipher=CCMP
group_cipher=CCMP
key_mgmt=WPA2-PSK
wpa_state=COMPLETED
ip_address=192.168.5.111
p2p_device_address=e8:fb:1c:66:af:df
address=e8:fb:1c:66:af:df
uuid=dbddbcf1-3fcd-54be-b9aa-57858a84189f
[root@ok3568:/usr/sbin]#

As we can see, the wpa_state=COMPLETED

According to the query result, if the connection is successful, it will attempt to obtain a dynamic IP address. If it fails, it will continue to try connecting:

if [ $? -eq 0 ]
then
	udhcpc -i $wifi
	echo "Finished!" 
else
	echo "try to connect again..."
  • udhcpc: A client program used to obtain dynamic IP addresses.

udhcpc is a commonly used DHCP client program in Linux for obtaining dynamic IP addresses and related network configuration parameters from a DHCP server.

  • Obtain dynamic IP
  • Obtain dynamic IP (subnet mask, dynamic gateway, DNS server address)

2.4 Overall Review

  • Stop hostapd (software to create WAP)
  • Stop dnsmasq (DNS forwarder and DHCP server software)
  • Read and parse parameters (network interface name, WiFi name, WiFi password)
  • Modify /etc/wpa_supplicant.conf file based on parameters
  • Disable mlan0, mlan1, eth0, eth1 network interfaces
  • Stop wpa_supplicant
  • Enable specified network interface (mlan0)
  • Configure the network through wpa_supplicant (with wpa_supplicant.conf file)
  • Use udhcpc to obtain a dynamic IP address

Additionally, here are some commonly confused terms:

AP: Access Point

WPA: Wi-Fi Protected Access

hostapd: A program in Linux for creating encrypted wireless access points

hostapd_cli: A text-based utility included in hostapd

wpa_supplicant: Used to scan and connect to APs, runs in the background

wpa_cli: Used to search, set, and connect to networks

udhcpd: A DHCP server that allocates IP addresses to devices

udhcpc: A DHCP client that obtains IP addresses

3. Conclusion

This article uses the Feilin embedded Linux development board as an example to introduce the execution principle of its built-in WiFi configuration script. It automatically configures the wpa_supplicant.conf file and calls wpa_supplicant for WiFi configuration.

The next article will continue to introduce how to implement WiFi configuration through C/C++ programming, stay tuned!

Analysis of WiFi Configuration Script in Embedded Linux

END

Author: xxpcb
Source: Programmer Loves Learning
Copyright belongs to the original author, please contact for deletion if there is any infringement.
Recommended Reading
How Fast Can GPIO Flip?
I Don’t Want to Do This Project Again!!!
I Didn’t Expect the Recently Popular DeepSeek Can Really Be Used to Analyze Circuits!
→ Follow to Not Get Lost ←

Leave a Comment