26 of 46
Shorten switching to systemd-networkd
  • 38k
  • 13
  • 62
  • 168

We are talking about an access point together with a wlan0 client connection to another wifi network (wlan repeater) or an internet router.

If you want an access point together with an ethernet port eth0 as uplink to a switch or an internet router then look at Setting up a Raspberry Pi as an access point - the easy way.

The Raspberry Pi is able to work as a wireless hotspot and simultanous connect to another hotspot as client. But the wifi device on the RasPi has a general limitation. The client connection cannot be bridged because lack of WDS (wireless distribution system) that is needed for bridging on wireless. For further information look at Raspberry Pi WiFi to Ethernet Bridge for a server?. So we can only use routing for the wifi client connection to the internet router. But the wifi hotspot and the wired ethernet port can be bridged so all devices on wifi and the wired port can have the same broadcast domain on its common subnet.

For reference I use a RPi3B+ with Raspbian Stretch Lite 2019-04-08 and upgraded by sudo bash -c 'apt update && apt full-upgrade && reboot' on 2019-05-19. I also assume that you already have a connection to the internet. All commands can simply copied and pasted to the command line of the RasPi. The blocks with EOF you can select from cat incl. the last EOF and paste it to the RasPis command line. With Enter it will be coppied to a file without the delimiter EOF.

We will first setup a wifi repeater so if anyone only need this he can stop setup at this point and use it. For those who need a bridged ethernet port with the wifi access point can continue with setting it up.

I use systemd-networkd for reasons. For the impatient first only the Setup.

♦ Setup wifi repeater

Example for this setup:
                 wifi                        wifi            wan
mobile-phone <~.~.~.~.~> (ap0)RPi(wlan0) <.~.~.~.~.> router <───> INTERNET
            ╲             ╱          ╲
           (dhcp     (dhcp
         from RPi)               from router)

Step 1: setup systemd-networkd

For detailed information look at (1). Here only in short. Execute these commands:

# Install hostapd
rpi ~$ sudo -Es
rpi ~# apt install hostapd
rpi ~# systemctl unmask hostapd
rpi ~# systemctl enable hostapd

# disable debian networking and dhcpcd
rpi ~# systemctl mask networking.service dhcpcd.service
rpi ~# sudo mv /etc/network/interfaces /etc/network/interfaces~
rpi ~# sed -i '1i resolvconf=NO' /etc/resolvconf.conf

# enable systemd-networkd
rpi ~# systemctl enable systemd-networkd.service systemd-resolved.service
rpi ~# ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf

Step 2: install hostapd for the access point

Create this file with your settings for ssid=, country_code= and wpa_passphrase=. As channel= select the same channel wpa_supplicant with wlan0 will connect to your internet router.

rpi ~# cat > /etc/hostapd/hostapd.conf <<EOF

rpi ~# chmod 600 /etc/hostapd/hostapd.conf

Set DAEMON_CONF="/etc/hostapd/hostapd.conf" in /etc/default/hostapd

rpi ~# sed -i 's/^#DAEMON_CONF=.*$/DAEMON_CONF="\/etc\/hostapd\/hostapd.conf"/' /etc/default/hostapd

Edit the hostapd.service:

rpi ~# systemctl --full edit hostapd.service

and comment the line After=network.target with # so it looks like:


Save it and quit the editor. Next add interface ap0 to the hostapd.service with:

rpi ~# systemctl edit hostapd.service

In the empty editor insert these statements, save it and quit the editor:


ExecStartPre=/sbin/iw dev wlan0 interface add ap0 type __ap
ExecStopPost=-/sbin/iw dev ap0 del

Step 3: setup wpa_supplicant for client connection

Create this file with your settings for country=, ssid= and psk= and enable it:

rpi ~# cat >/etc/wpa_supplicant/wpa_supplicant-wlan0.conf <<EOF
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev

    key_mgmt=WPA-PSK   # see ref (4)

rpi ~# chmod 600 /etc/wpa_supplicant/wpa_supplicant-wlan0.conf
rpi ~# systemctl disable wpa_supplicant.service
rpi ~# systemctl enable wpa_supplicant@wlan0.service

Extend wpa_supplicant with:

rpi ~# systemctl edit wpa_supplicant@wlan0.service

In the empty editor insert these statements. Have attention to the minus sign after equal =- on some statements. Save it and quit the editor:


ExecStartPost=/sbin/iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE
ExecStopPost=-/sbin/iptables -t nat -D POSTROUTING -o wlan0 -j MASQUERADE

Step 4: setup static interfaces

Create these files:

rpi ~# cat > /etc/systemd/network/08-wlan0.network <<EOF
# If you need a static ip address toggle commenting next three lines (example)
# Optional: if you want to connect to your own DNS server, set it here (example)

For those who want a bridge, do not need the next file and must continue with Setup bridge.

rpi ~# cat > /etc/systemd/network/12-ap0.network <<EOF
# If you want to connect to your own DNS server, set its ip address here

Setup a wifi repeater without bridge is finished. You must

♦ Setup bridge

**Setup wifi repeater** as described above.

Example for this setup:

        from RPi)        bridge
           ╱    wifi    ┌──────┐
mobile-phone <~.~.~.~.> │(ap0) │              wifi            wan
                        │   br0│RPi(wlan0) <.~.~.~.~> router <───> INTERNET
      laptop <────────> |(eth0)│╲       ╲
           ╲    wired   └──────┘╱      (dhcp
         (dhcp    from router)
       from RPi)

Step 5: configure hostapd for a bridge

Add a line `bridge=br0` to */etc/hostapd/hostapd.conf* with:
rpi ~# echo 'bridge=br0' >> /etc/hostapd/hostapd.conf

Step 6: setup wpa_supplicant for a bridge

Extend wpa_supplicant with:

rpi ~# systemctl edit wpa_supplicant@wlan0.service

In the editor add 3 lines so it looks like following. Have attention to the minus sign after equal =- on some statements. Save it and quit the editor:


ExecStartPost=/sbin/iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE
ExecStopPost=-/sbin/iptables -t nat -D POSTROUTING -o wlan0 -j MASQUERADE
ExecStopPost=-/bin/ip link set ap0 up

Please note that ExecStopPost=-/bin/ip link set ap0 up is not a typo. On stopping wpa_supplicant, interface ap must be set up again as described in section Details - wpa_supplicant for bridge (Step 6).

Step 7: bring up access point with virtual wifi interface

Create a unit with:
rpi ~# systemctl --force --full edit ap-bring-up.service

In the empty editor insert these statements, save it and quit the editor:

Description=Bring up wifi interface ap0

ExecStart=/lib/systemd/systemd-networkd-wait-online --interface=wlan0 --timeout=60 --quiet
ExecStartPost=/bin/ip link set ap0 up

Step 8: setup static interfaces

For a bridge ap0 is dynamically created. So create these files:

rpi ~# cat > /etc/systemd/network/02-br0.netdev <<EOF

rpi ~# cat > /etc/systemd/network/04-eth0.network <<EOF

rpi ~# cat > /etc/systemd/network/16-br0_up.network <<EOF
# Optional: if you want your own DNS server, set it here (example)

That's it.

♦ Details


One problem is that we want to use the same device for a wifi client and for an access point. This must be supported by the wifi hardware. We can check this with
rpi ~$ sudo iw list | grep -A4 "valid interface combinations:"
        valid interface combinations:
             * #{ managed } <= 1, #{ P2P-device } <= 1, #{ P2P-client, P2P-GO } <= 1,
               total <= 3, #channels <= 2
             * #{ managed } <= 1, #{ AP } <= 1, #{ P2P-client } <= 1, #{ P2P-device } <= 1,
               total <= 4, #channels <= 1

The important part is #{ managed } <= 1, #{ AP } <= 1, but you can also see that this is only possible on one channel.

I've found that we have to setup this in sequence, otherwise it won't work. If other applications bind to the wifi port it cannot be set.

  1. create a virtual interface ap0 for the access point
  2. start access point daemon hostapd using interface ap0
  3. start wpa_supplicant for wifi client using interface wlan0

This order restricts the whole setup. It isn't possible to start hostapd when wpa_supplicant is running. You must first stop wpa_supplicant and then start hostapd and wpa_supplicant in this order. This is due to the WiFi driver brcmfmac.

Another quirks is that wpa_supplicant disables the interface ap0 when it is managed, no matter if it start or stop. So even after a start from wpa_supplicant we have to enable ap0 again.

Here are mainly five components involved: virtual interface ap0, hostapd, wpa_supplicant, setup bridge and bring up access point.

hostapd (Step 2)

This is the normal setup you will find all over the web. Please set the channel to the same value than **wlan0** is connected to the wifi from your router. It is the restriction from the hardware and may avoid confusion with channel setting. *hostapd* will always set the channel to the same value than from the client connection, no matter what you set here.

Please use a passphrase that is long enough, I would say at least with 8 characters. It was told that 4 characters are to small and hostapd will refuse to accept connections. You will not find the access point RPiNet in your mobile phone (thanks to @Leo).

For dependencies we extend the unit from hostapd with a drop in file (overlay) (2). It always starts wpa_supplicant (Wants it) and creates interface ap0 before starting hostapd. This is respected to the starting order. Because ap0 is bound to wlan0 it gets the same mac address. You may consider to give it a unique mac address but that's not a good idea. On the network is only seen the mac address from wlan0. If you give ap0 its own mac address then it is not seen on the network for arp requests and the ip address for connections to ap0 is not found and get stuck. You have to set ap0 to promiscuous mode to get it to work then.

After setting up the dependencies then the hostapd.service by default will start After=network.target. The wpa_supplicant@wlan0.service must start After=hostapd.service and starts by default Before=network.target. Do you see the conflict with network.target? Systemd complains it with the error message "Found ordering cycle on wpa_supplicant@wlan0.service/start" and prevents hostapd.service to start. That's the reason why we have do comment After=network.target in the unit file of the hostapd.service.

After stopped hostapd then ap0 is also deleted so it can be created again on next start of hostapd.

wpa_supplicant (Step 3)

Setting up *wpa_supplicant* for **wlan0** we do as usual. It's extended unit is to strictly bind *wpa_supplicant* to *hostapd* so it will start and stop with it in the right order. We do it because running *wpa_supplicant* without *hostapd* is very complicated and may result in a total crash of the *brcmfmac* wifi driver, I have seen that on my tests.

There is no need that clients connected to the internet router must also connect to clients on the access point. So we can use NAT that simplifies setup a lot. Then we don't have to configure static routes and it is not needed to configure wlan0 with static values (ip address, gateway, DNS server etc.).

Setup static interfaces (Step 4)

Here we define interface **wlan0** and the virtual interface **ap0** we need for a wifi repeater. For **wlan0** we get an ip address by DHCP from the internet router. Optional you can set a static ip address, but then you also have to define all other settings like gateway and DNS server because you don't get them anymore from the DHCP server. IP forward is also enabled here that we use for routing between **wlan0** and **ap0**.

Interface ap0 needs a static ip address because it is the access point and the source of the DHCP server for the wifi network. This DHCP server will give default DNS server to the clients so usually you don't have to worry about this. Only if you need your own DNS server given to the clients you can define it here.

hostapd for bridge (Step 5)

We have setup *hostapd* in Step 2. Now we only need to append `bridge=br0` to its configuration so that it will dynamically manage adding **ap0** to the bridge.

wpa_supplicant for bridge (Step 6)

When wpa_supplicant is started it also brings up interface **wlan0**. Every time it is managed, no matter if started or stopped, it will stop **ap0** because it is not a real interface and depends direct on **wlan0**. That is also the reason why it can only brought up when **wlan0** has Gained carrier. But we cannot just wait some seconds and then bring up **ap0**. *wpa_supplicant.service* must have started completely so we only can use an extra service *ap-bring-up.service* for doing this. The dependencies ensure this.

After stopped wpa_supplicant (bring wlan0 down) ap0 must brought up again so it can continue running for the access point.

bring up access point (Step 7)

It is not possible to just set up **ap0** when needed. It can only start when **wlan0** "Gained carrier" and link becomes ready [**(3)**](https://github.com/systemd/systemd/issues/936). This will happen some or more seconds after *wpa_supplicant* has started. So we need *ap-bring-up.service* that *wpa_supplicant* Wants and that will check if **wlan0** has "Gained carrier" and is online. There is a helper *systemd-networkd-wait-online* that can do this synchronous. We use it with a timeout of 60 seconds. If your network connection takes longer than 60 seconds to get up, then you should increase the timeout accordingly. With `journalctl -b -e` you can check if `Starting Bring up wifi interface ap0...` and `Started Bring up wifi interface ap0.` covers `wlan0: Gained carrier`. This is very important because otherwise the bridge will not work correctly with undefined behavior. And of course this unit should only start when *hostapd* is running (Requisite).

define static interfaces for bridge (Step 8)

This files define the bridge. **ap0** will dynamically added by *hostapd*. **eth0** and **ap0** are slaves of the bridge and don't need an ip address. The bridge **br0** itself also does not need an ip address but here it has a static ip address because we need it for the DHCP server bound to **br0** so the DHCP server is available on the subnet on the bridge ( interfaces eth0, ap0). The clients there will get default DNS server ip addresses from the DHCP server. If you want to use your own DNS server you can set it here. The `DNS=` option accept more than one ip address.


You are now able to start, stop and restart *hostapd* and *wpa_supplicant*.

You should see the access point, here RPiNet, in your mobile phone and should get an ip address to connect to the access point. You should also get an ip address from the same subnet if you connect a laptop with an cable to the ethernet port and you can ping the mobile phone.

With this setup you have the following dependencies with starting and stopping:

 hostapd   │ wpa_supplicant      wpa_supplicant │  hostapd
 starting  │    starts              starting    │  starts
 stopping  │    stops               stopping    │   ----
restarting │   restarts            restarting   │  starts

This is because of the strict order of starting (see section General). You cannot run wpa_supplicant without hostapd but you can run hostapd without wpa_supplicant by starting hostapd and then stop wpa_supplicant.

If communication stops for some reason (e.g. delay to small or something else) it is mostly enough to kick ap0 with /bin/ip link set ap0 up.

♦ Troubleshooting

Using *systemd-networkd* with a virtual interface **ap0** seems to be buggy. Its built-in DHCPServer does not propagate DNS server ip addresses as option to the devices. For further information look at [How to setup hostapd to send DNS server address during DHCP session start on RPizeroW wifi repeater](https://raspberrypi.stackexchange.com/a/90822/79866). On an access point using the **wlan0** interface you will configure it for example:
rpi ~# cat > /etc/systemd/network/08-wlan0.network <<EOF

This will give an ip address to the connected device and the ip addresses and for the domain name server it should use. If you try just the same with ap0 (Name=ap0) the devices will get an ip address but no DNS server options. They are stuck with its default settings. In many cases this is enough and DNS name resolution works as expected. But if you need your own DNS server you have to work around this bug. Don't use the built-in DHCPServer instead use dnsmasq. First set DHCPServer=no or omit its entries. Then install and setup dnsmasq as follows:

rpi ~$ sudo -Es
rpi ~# apt install dnsmasq
rpi ~# systemctl stop dnsmasq.service
rpi ~# cat > /etc/dnsmasq.conf <<EOF

Important is to enable IGNORE_RESOLVCONF=yes in /etc/default/dnsmasq. We use systemd-resolved:

rpi ~# sed -i 's/^#IGNORE_RESOLVCONF=yes/IGNORE_RESOLVCONF=yes/' /etc/default/dnsmasq
rpi ~# systemctl start dnsmasq.service
rpi ~# exit
rpi ~$

With this setup dnsmasq will ask the nameserver set in /etc/resolv.conf for dns names requested from the stations and will give the responses to them. It works as a caching dns server.

**refefences:** [1] [Howto migrate from networking to systemd-networkd with dynamic failover](https://raspberrypi.stackexchange.com/a/78788/79866) [2] man systemd.unit [3] [systemd-networkd wireless bridging - need to wait for carrier](https://github.com/systemd/systemd/issues/936) [4] [Setup WiFi on Pi 3 B+](https://raspberrypi.stackexchange.com/a/97939/79866)
  • 38k
  • 13
  • 62
  • 168