How to build a simple server running on OpenWrt

I want to build a simple example where I can have my own "server" running along with OpenWRT (I am a newbie in OpenWRT so sorry for the basic questions). This server application works in the simplest form as follows:

  • OpenWRT functions as a router as usual (with Luci included)
  • On the router's boot, my application will start.
  • It will listen on a certain port (e.g. 9099) for any requests from external. Then respond with some data.

Let's assume that I can write a C program to open a socket and listen/respond on it. And I can include it in a Makefile, then make it available in "make menuconfig" so that it can be selected along with Luci to be included in the target firmware.

What I would like to know is:

  1. How to make my program start automatically on boot ? I know in Linux, you can put it in /etc/init.d and /etc/rc.d to have it autostarted. But with openWrt, I don't know how to make it possible.
  2. To make the port accessible to my application, what's the configuration that I need to do on the OpenWRT GUI ?
  3. My understanding is that if you include your application (e.g. HelloWorld) in the "make menuconfig", it will be included in the firmware. But how can I make use of (e.g. start/stop) my application via the OpenWRT GUI ?

Thanks a lot for any help

You either add the command to start it in /etc/rc.local or you make a proper service-file for it in /etc/init.d

By default, traffic from LAN is already allowed. If you want it accessible from WAN, you need to allow traffic to that port in firewall-settings.

You make a proper service-file in /etc/init.d

2 Likes

Thanks WereCatf.

Being a newbie with OpenWRT, I was hoping to get the steps elaborated. But that's fine, I guess I will need to do some exercises to get some experiences.

Well, I'm not sure what you want me to elaborate on. I can answer questions, if you have any specifics, but other than that, the wiki-page at https://openwrt.org/docs/guide-developer/procd-init-scripts and the existing scripts in /etc/init.d are literally the best source on how to do it.

They don't really require much, you just need to add the following to the beginning of the script:

#!/bin/sh /etc/rc.common
 
USE_PROCD=1

And then define the start_service() and stop_service() functions.

1 Like

/etc/rc.d and /etc/init.d are same as in vanilla Linux.
Creating and adding your own application will be a bigger headache.

1 Like

In addition to what @WereCatf indicates, note this point in the wiki https://openwrt.org/docs/guide-developer/procd-init-scripts#init_scripts_during_compilation and spend some time understanding /etc/rc.common and /lib/functions/service.sh.

OK, thanks Werecatf and everyone for your help.