raspberrypirouter

Raspberry Pi and Routing: Turning a Pi into A Router

The Raspberry Pi can be used as a router–great if you need a pocket-sized device to share an Internet connection.  It can also be used in conjunction with a cantenna.

Requirements For This Walkthrough

Materials

  1. Local network
  2. Mac or PC
  3. Raspberry Pi  running Raspbian “wheezy”
  4. Wireless USB Adapter
  5. HDMI Cable (*optional)
  6. Keyboard (*optional)
  7. Mouse (*optional)
  8. Monitor with HDMI input (*optional)

*If the Raspberry Pi is set up as a headless machine, you will not need a monitor, keyboard, or mouse–just another computer, which would be used to access it remotely over the network via SSH.

Downloads

  1. Older hostapd (only needed if the driver via apt  does not work)
  2. Copies of config files on Github (optional or for reference)

Knowledge, Skills, and Abilities

  1. Ability to navigate throughout a computer OS
  2. Knowledge of basic computer terminology
  3. Ability and confidence to enter commands in the Terminal, adjusting them to suit your environment, if necessary
  4. Familiarity with core networking concepts

Resources

  1. http://magpi.techjeeper.com/The-MagPi-issue-11-en.pdf
  2. http://www.pi-point.co.uk/documentation/
  3. http://blog.sip2serve.com/post/48420162196/howto-setup-rtl8188cus-on-rpi-as-an-access-point
  4. https://docs.google.com/file/d/0B3nsVzbJuBHVOWRJRDJacVd0S2s/preview?pli=1
  5. http://sirlagz.net/2012/08/11/how-to-use-the-raspberry-pi-as-a-wireless-access-pointrouter-part-3/
  6. http://www.raspberrypi.org/phpBB3/viewtopic.php?t=39096&p=393810
  7. http://unix.stackexchange.com/questions/119209/hostapd-will-not-start-via-service-but-will-start-directly
  8. http://www.daveconroy.com/turn-your-raspberry-pi-into-a-wifi-hotspot-with-edimax-nano-usb-ew-7811un-rtl8188cus-chipset/

Conceptual Overview

  1. Install Required Components via  apt-get
  2. Verify Wi-Fi Adapter dongle functionality
  3. Configure  /etc/network/interfaces 
  4. Create /etc/hostapd/hostapd.conf  with desired AP settings
  5. Point hostapd  to the configuration file in step 4 by modifying  /etc/default/hostapd
  6. Replace /sbin/hostapd  with the older version (if necessary)
  7. Configure DHCP to allow clients to connect
  8. Enable IPv4 forwarding to reach the Internet

pi-router

Prepare the RPi

Make certain that the RPi is up-to-date and all the newest packages are available for download/installation.

Install Required Components

The following components will be required for setting this up as an access point:

  • rfkill: a wireless utility
  • zd1211-firmware: common firmware that works with many Wi-Fi dongles
  • hostapd: the hostap wireless access point daemon
  • hostap-utils: supplemental hostap tools
  • iw: wireless configuration utility
  • dnsmasq: DHCP and DNS utility
  • bridge-utils:  used for connecting multiple Ethernet devices together

Install these components using the command:

Configure the Wireless Dongle

Verify The Dongle is Recognized by the RPi

Check that the RPi recognizes the Wi-Fi dongle.

You should see a listing mentioning the adapter you have plugged in.

Verify that the Wi-Fi dongle supports AP mode

If the output of the following command does not show anything about AP mode, then the dongle will not work for this project. But if it does, continue following the step-by-step directions.

Unfortunately, my dongle did not work and produced the error  nl80211 not found , which is OK.  Run this command:

if the output is similar to:

then it will probably still work.  This will be fixed in a later step.

Configure the Wireless Interface

Make a backup of /etc/network/interfaces  and then open it in a text editor:

Modify the file as below (highlighted lines are the additions):

Restart the wlan0  interface:

Configure hostapd Settings

Next, make a backup of the  /etc/hostapd/hostap.conf  file and open it in a text editor to make some changes (ignore the first command if the file does not exist yet).

If using a different adapter than the one I used, just modify the file by adjusting any unique items (i.e. country_code , ssid , etc).  If the iw list  command mentioned previously reported the error nl80211 not found , then modify the file as follows:

If the iw list  command reported the error, you should also to make a backup of the  /etc/default/hostapd  file (if it exists),

and then modify the highlighted line below (be sure to uncomment the line):

If you are using the same dongle I did, you will need to take another additiona step and replace   /usr/sbin/hostapd  with a newer version, which you can get here (but we will use a command to download it next).  Following our best practice, make a backup first and then edit it:

Delete the original file, which will be replaced by the one downloaded via the command below:

Set the proper permissions on the new file and make sure it is executable:

Restart the hostapd  service to activate the settings.

If the hostapd restart did not work.  Try running this to view the output and see if you can find where the problem is in the config file and fix it:

The wireless network should show up if you were to scan for it from another device.  However, a few other settings need to be configured before anyone can connect to it.  In particular, dnsmasq .

raspberrypi-router

Configure dnsmasq Settings

Following best practices, make a backup of the config file before editing it and then open the file in a text editor.

Uncomment the following lines and adjust them to your environment:

After saving the file, you can easily verify all the settings were correct with the following command (it just parses out the comments and blank lines):

Restart the dnsmasq  service to apply the settings:

Attempt to connect to the network using another device.  You should be able to connect, but you won’t be able to get out the the Internet yet.

Enable Forwarding to Reach the Internet

Enable IPv4 forwarding

Enable NAT

Other Dongles and Other Uses

The main reason I chose the Wi-Fi dongle that I did was so that I could connect my cantenna to it and blast the signal a long distance.  It would have certainly been easier to use an adapter that worked right out of the box, but now I have a lot more flexibility with antenna types.

Appendix

Here are all the commands from the walkthrough needed to set up the router (excluding the information needing to be added to the files):

 Troubleshooting

I recently followed my own walkthrough and ran into an issue on the last command for iptables .  It returned the error:

I was using the image of raspian from back in January 2014.  After running

I was able to execute the command and get out to the Internet via the Raspberry Pi Router!

  • tuxun

    the last line is double :) I’m trying it!

  • Pingback: Tab Dump | mattezell.info()

  • blue architect

    Any thoughts on turning a Raspberry Pi into an aircard router for one device (IP Cam) via Lan? I’d like to plug a USB Aircard into the Pi and connect the cam via ethernet.

    • http://www.jacobsalmela.com Jacob Salmela

      If you are just looking to get an IP webcam, take a look at my other post on turning the Pi into a live-steam Webcam over the Internet. If you have already set up the Pi as a router, you could just plug in the USB Webcam, bypassing the aircard all together.

      If you are trying to use the celluar data service for the Webam, you would probably need the driver for the aircard first. Since an aircard is basically another network interface, you might be able to modify the steps in this walkthrough for that interface instead of the ethernet/wi-fi interfaces.

      • https://www.facebook.com/Blue.Architect Christian Silva

        Thanks for the info J. I am following your design since I just have to swap the interfaces and make a couple of changes. I’m new to linux so it is taking me a bit longer to learn my way around. Once I get the wwan0-eth0 bridge working I’ll post the results.

  • https://www.facebook.com/prokectx ProJectX
    • tuxun

      Do you know I got mail for this useless ad?

  • David

    How would one go about running this on start up? I can get it to work no problem after booting, Thank you!

    • http://www.jacobsalmela.com Jacob Salmela

      I tried this setup again and the router started automatically when I booted the Pi…

      • Ambitious

        Dear Jacob;
        good job for this post, i want to ask you a question, i need to make a small project like router,i.e i need to forward any data comes from local network to outside the local network through a GPRS / USB modem,
        and also i need to access a device connected to the local network remotly through the same GPRS or USB modem.
        I successfully did it using a TP-Link router and usb modem and using the port forward, but now i want to use my own Embedded system to add some control to my system,
        Could i know if the rabry Pi or any platform is suitable for this project or not. also i need to buy thousands of this system so i need to compile all command to the kernel instead of write all these command for each device.

        hope that i explained my problem successfully and i appreciate your support.

        Best regards
        Mohamed Hamed

  • http://www.jacobsalmela.com Jacob Salmela

    My *nix skills seem to fade if I don’t use them for a while, so I cannot answer this upfront. I am planning to follow my own tutorial and set this up on the faster B+ model and maybe make some sort of RPi mesh network or something…

  • http://gravatar.com/pmurad25 Pablo

    Hey bud, a simple 5v power supply can afford a usb wireless adapter?

  • Pingback: 設定 Raspberry Pi 成為 3G Router 教學 | Focus()

  • Pingback: Raspberry Pi – Turn your Pi into a Wireless Router | theezitguy()

  • leuk_he

    This tutorial makes a fine access point from the wlan interface, but it does not function as a nat router for me.

    The windows pc still is connecting to the upstream dhcp and gets an address in the range of the upstream (tplink) router.

    e.g. i am missing the place where a ip number is assigned to the wlan interface.

    • http://www.jacobsalmela.com Jacob Salmela

      What do you have set in your dnsmasq.conf file? You should have the dhcp-range= option set in order to distribute DHCP addresses.

      /etc/network/interfaces is the file where you can assign how an interface gets its IP address. In this walkthrough, I had my Pi connected directly to my router via eth0, so I had this in the file: iface eth0 inet dhcp. This says that eth0 should have its IP set via DHCP (i.e. from my existing router). I set it this way so I could configure the entire thing via SSH.

      You will probably want to look at adjusting both of the files mentioned above.

  • iskender

    thank you for tutorial but I can connect raspberry but there is no internet?

    • iskender

      I am sorry. Everything works well. Thank you again

  • iskender

    Is there a way to learn ip of devices connect to raspberry ?

    • http://www.jacobsalmela.com Jacob Salmela

      I think the easiest way would be to run this command:
      cat /var/lib/misc/dnsmasq.leases
      Client requets also show up in the main log file along with other information:
      cat /var/log/daemon.log

  • Deakster

    Nice Tutorial! Saved me several hours of digging. Just one comment. IMHO I think the setup is little cleaner (and probably more secure) without a bridge between eth0 and wlan0. I configured wlan0 with a fixed address on the DHCP subnet and added a few extra entries in iptables to forward packets. This way both networks are correctly separated. Thanks!

    • jacobsalmela

      I agree it would be more secure. In this tutorial, the main goal was to hook up a cantenna. It’s fun that you were able to modify it though. Thanks for sharing!

      • Jouni Nobody

        What is the security issues on this type of simple router?

        • jacobsalmela

          I suppose its the same issues you would find with any router minus a WPS vector. You might even get a little security-through-obscurity, as comparatively, not that many people will be running a Pi router.

  • Derek Wise

    I am having trouble with this… i got everything setup and it works fine when i have it plugged in via ethernet cable, but i need to be able to use is as a true router, and have it unplugged.
    I am bulding a robot and have everything else working but need to know how to set this up as a standalone router. when it is unplugger from the ethernet i am able to connect to the network but my computer then says there i s an error and the rpi doesnt have a gateway.
    I have tried searching for an answer but nothing is working please help

    • jacobsalmela

      Certainly more of a challenge. Does the router need Internet access or do you just need it for ad-hoc purposes?

      • Derek Wise

        I only need it for ad-hoc purposes.

        and for some reason i thought it was a good idea to start on my robot project one week before i need to have the entire thing done..

        BTW thankyou for this tutorial it was really helpful.

        • jacobsalmela

          I have not tested this, but you should be able to just use it in ad-hoc mode as-is. If you went through the entire walkthrough, you should have set up DHCP. So any client that connects will get an IP address and can communicate with each other.

    • Deakster

      Hi Derek, I would recommend you do the same as me and not bridge eth0 with wlan0. You will need to remove the br0 interface and give wlan0 a static IP address on the same subnet you have assigned to the DHCP pool (but not one assigned to the pool of course). This way you will be able to connect to the Pi even when eth0 does not have an IP address.

      • jacobsalmela

        Sounds like that would work. I’m glad someone smarter than me thought of it!

      • Derek Wise

        Awesome, thankyou!

      • Clément

        Can you write the code please :))
        Thanks

  • Firass Issa

    oh bud. this is unbelievable. Seriously, in a short word: Your are a genius guy, I’ve never seen.
    Your tutorial is really the best one in the whole net about the seem issue, speciously on the driver wifi chip rtl8192cu that I have.
    believe it or not, I was digging around the net for the whole week to get my issue resolve for my boss.
    I found most the forums and discussions are about to recompile the kernal to get the rtl8192cu, and create an image then copy it to boot pi’s SD card. and there many methods to create that shit image, and I followed all of them step by step without any advance, because you know about more issues that I faced to create that image, like for example command: “make command” within the rtl8192cu driver folder to identify the wifi chip.
    honestly, I found your hostapd file very useful to get all issues done, and I change it your commands a little as following in general:

    1- downloading dhcp server and let it gives all your IPs.
    2- For the nat table, I added to it to more rows commands, and then swabbing between etho and wlan0, and let eth0 get the IP address by your external dhcp router, as long as it is connected by ethernet link to the router, so I can get to access to pi by ssh in later time.
    3- using static wlan0 instead of bridge.
    that is it, and now I can access to internet through pi as access point and browsing youtube, facebook, etc. from my laptop and iPhone mobile .
    and now I will prepare php script to get control for those customers on pi.
    NOTE:
    the pi after a while disconnected for one minute. and I think that for drop power. and there is a command to fix it.
    ———— ——MANY——————————–THANKS—————————-

    • jacobsalmela

      I sincerely appreciate your kind words!

      I, too, spent a long time searching for how to do this, so I cannot take all the credit. I just tried to make it a bit easier to follow in more of a step-by-step way.

      The hostapd file was from someone else, but I also saved a copy to my public Dropbox in case they ever stop sharing it for some reason.

      I’m glad you found the tutorial useful–it’s satisfying!

  • Luke Telford

    Hello,

    This tutorial is really good and descriptive! much better than any i have found on the net. I’m just having a slight issue, I’m a noob when it comes to anything linux/unix! The steps I’m having an issue with are:

    Configure hostapd Settings

    Next, make a backup of the /etc/hostapd/hostap.conf file and open it in a text editor to make some changes (ignore the first command if the file does not exist yet).

    I keep getting an error (see image attached) any help would be greatly appreciated!

    • jacobsalmela

      You do not need to back up the file because it does not exist, which is OK. Some users will have an file there already, which is what the backup is meant for. You can simply create the new file.

      • Luke Telford

        Thanks for getting back to me so quick! Thanks for that, was just a little worried I was missing something that I needed.

  • Luke Telford

    I have another issue again, sorry to be a pain! I have now followed all of the steps but when i go to restart the hostapd service it doesn’t restart, i was wondering if this could a driver issue? is any dongle that is compatible with the pi good for this? also i am using the original raspberry pi, would this cause an issue also?

    Thanks for all your assistance!

    (screenshot of the error i get when restarting the service)

    • jacobsalmela

      hostapd failing to start usually has something to do with an error in the config file. Try starting hostapd in debug mode using your config file with this command:

      sudo hostapd -d /etc/hostapd/hostapd.conf

      Look for any clues as to what might be causing it to fail. You can post the output here if you can’t figure it out.

      There are many dongles that will work out of the box. For this tutorial, I was most interested in an adapter that had a removable antenna so that I could connect my cantenna. But I’m sure if you get the right one, it will work much easier.

      • Luke Telford

        the error I’m getting back is for the driver?

        pi@raspberrypi ~ $ sudo hostapd -d /etc/hostapd/hostapd.conf

        random: Trying to read entropy from /dev/random

        Configuration file: /etc/hostapd/hostapd.conf

        Line 3: invalid/unknown driver ‘rtl871xdrv’

        ctrl_interface_group=0

        1 errors found in configuration file ‘/etc/hostapd/hostapd.conf’

        Here is a link to the package i got, I’m not using this pi though I’m just using the wifi dongle from it – http://www.amazon.co.uk/Raspberry-Pi-Quad-Starter-Bundle/dp/B00T7OHE9A/ref=sr_1_2?ie=UTF8&qid=1425647082&sr=8-2&keywords=raspberry+pi+2#productDetails

        thanks again for all your time and help

      • Luke Telford

        i managed to find the problem! it was a driver issue so i tried commenting it out and that worked! thanks for all your help man :)

    • Jimmy F

      This happened to me too. I fixed it by editing /etc/hostapd/hostapd.conf again. I found extra lines with random numbers on them. Delete those and you’ll be good.

  • Will

    Ok, so I was debugging the hostapd.conf file and the following message apeared: /usr/sbin/hostapd: 1: /usr/sbin/hostapd: syntax error: redirection unexpected

    What do I need to check?

    • jacobsalmela

      A syntax error means there is a typo somewhere or some character it does not like. Redirection unexpected could have something to do with this.

  • wideraft

    Would something like this work to turn the Pi into a wired router? I would like to tether my iPhone via USB and have the Pi act as a wired router (no wifi desired). I would run the ethernet from the Pi to an ethernet over powerline device.

    • jacobsalmela

      I don’t see why not. You would just need to adjust the interfaces appropriately. Perhaps get some sort of ethernet splitter for more ports or something.

  • Jimmy F

    How do you turn off the router? Sorry if this is a stupid question.

    • jacobsalmela

      You can follow the steps in reverse and restore the original config files, which would be the easiest. You could also uninstall all the services.

      • Jimmy F

        I meant temporarily, like a single command that can turn it off, for like, overnight or something.

        • Wirehead

          The following should disable it:
          sudo ifdown eth0
          To reenable:
          sudo ifup eth0

  • AnnitaP

    I am using Raspberry Pi Model A which doesn’t have an ethernet port. Can I still do it? And If yes, how am i going to install hostapd and the drivers for the Wi-Fi dongle without the ethernet cable? Thanks!

    • jacobsalmela

      You might be able to use a USB to Ethernet adapter, but you might have to find drivers for that. Once you get it working, then you could download whatever you need from online.

      • AnnitaP

        Great thank you :)

    • AnnitaP

      I have found a USB to ethernet cable but supports only windows and mac OS X. Will it be working with the Raspberry pi? This is the one: http://global.level1.com/Network-Card/USB-0401/p-3209.htm

      • jacobsalmela

        I cannot guarantee anything, but it looks like you can use the driver found here. I found this information along with some directions on this page.

  • Mitch

    So, of course with the statement “If the output of the following command does not show anything about AP mode, then the dongle will not work for this project.” one has to ask,

    1. Is there a repo or list somewhere of AP mode supported dongles (ideally for 802.11ac) out there?

    2. I’m assuming MIMO’s out of the question with this solution?

    3. Due to comm’s limitations on the board via the USB channels (even at USB 2.0), I could see this getting really hot, is there any danger (or at the very least performance risk) to not running an active cooling solution while running in AP mode? Wouldn’t be difficult to pin off a case face but before adding that headache to mix I figured I’d ask first.

    • jacobsalmela

      I do not know of a repo that lists whether or not the dongle supports AP mode. There is a column for AP mode listed on this page, but they are all question marks.

    • jacobsalmela

      As for your other question, it seems to run fine without overheating, but I’m sure it could if you pushed it hard enough.

  • Neil

    Hi, Great How-to, but can someone tell me where “sudo iptables -t nat -A POSTROUTING -j MASQUERADE” is stored as I can not find it

    • jacobsalmela

      I’m not sure of the file, but you can view current rules with

      iptables -L

      and if you want to delete, use the -D flag

  • Neil

    Thanks for the quick response. I’m trying to set Rpi AP without br0 interface, and not sure what rules I need to enter. Any help would be appriciated

    • jacobsalmela

      iptables has always been the bane of my existence, so I’m afraid I won’t be able to help much. I usually just Google whenever I need to find how to set a specific rule, but even then…

  • AnnitaP

    Hi, and thanks for the great tutorial!I am using the Edimax ew-7811un nano usb for WIFI dongle and I want to create a standalone router for ad-hoc purposes. Not sure though which changes I should make.Could you please help me?
    Thank you for your time

    • jacobsalmela

      I believe for that model you need to use the older hostapd and then create the file as I have it written under the “Configure hostapd Settings” section.

      • AnnitaP

        Ok thank you. Since I need not to connect to existing internet network, does this tutorial still apply to my case since you are bridging ? or can it still work?

        • jacobsalmela

          Making the bridge lets you get out to the Internet, but if you just want to use it as a local access point, then you don’t need to do that part.

  • ttbocx

    Thank you for the tutorial.
    The process seems kind of easy as described and I think that I might be able to do it on my Arch system as well. Nevertheless, I would like to ask you a question. Is the DHCP server capability limited to the wlan0 interface only? I am interested in it, because I cannot allow the DHCP server to offer ip addresses to the LAN through eth0. A router we used did this (did offer IP addresses via WAN port) after a power shortage and we were without internet at work for a while because of conflicting DHCP broadcasts.

    • jacobsalmela

      You can change the interface to whatever you want. I believe it is just a setting in dnsmasq.