Gauche Devlog

< Hygienic macro intro | Running code once and only once >

2016/01/28

Automatic port selection for httpd

When you run a small http server temporarily, sometimes you want the server to pick an unused port number automatically, instead of your specifying one. For example, a test program may need to spawn a server, and hardcoding the port number will prevent you from running more than one instance of the test program simultaneously.

Giving 0 as the port number to make-server-socket or make-server-sockets let the system choose a port number for you. You need to know which port number is picked. With Gauche-makiki, you can use :startup-callback argument to examine server sockets to find out the port number. The following snippet shows echoing the port number to stdout after starting the server:

Note that server may open multiple sockets (e.g. one for ipv4, one for ipv6) so the callback receives a list of sockets. Their port numbers should be the same, though.

With this setup, you can spawn a server in a subprocess and talk to it, for example:

Tags: makiki, Tips

Past comment(s)

skimu (2016/01/29 03:49:36):

Thanks for writing this. This is exactly what I wanted to know.

Post a comment

Name: