Skip to content

Instantly share code, notes, and snippets.

@kisom
Last active August 29, 2015 14:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kisom/5234b114dd37ca14e4f9 to your computer and use it in GitHub Desktop.
Save kisom/5234b114dd37ca14e4f9 to your computer and use it in GitHub Desktop.
// This program is a simple web server that listens for IP address
// updates. There's no authentication or security at all; I use it
// to keep track of beaglebones on a LAN.
package main
import (
"fmt"
"log"
"net/http"
"os"
"time"
)
type entry struct {
IP string
Update time.Time
}
var table = map[string]*entry{}
func receiveAddr(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s", r.RemoteAddr, r.URL)
ip := r.FormValue("ip")
host := r.FormValue("host")
table[host] = &entry{
IP: ip,
Update: time.Now(),
}
}
func displayIP(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s", r.RemoteAddr, r.URL)
for host, entry := range table {
out := fmt.Sprintf("%s\n\tIP: %s\n\tUpdate: %s\n",
host, entry.IP, entry.Update)
w.Write([]byte(out))
}
}
func dropHost(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s", r.RemoteAddr, r.URL)
host := r.FormValue("host")
delete(table, host)
}
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
http.HandleFunc("/", displayIP)
http.HandleFunc("/update", receiveAddr)
http.HandleFunc("/delete", dropHost)
log.Fatal(http.ListenAndServe(":"+port, nil))
}
# Throw this in /etc/network/if-up.d, chmod+x, and when your machine's
# network comes up, it will send it's address to the server. It will
# always exit without error to ensure that it doesn't conflict with
# booting.
#!/bin/sh
SERVER=addr.example.local
PORT=8080
[ -z "$IFACE" ] && exit 0
[ "$IFACE" != "lo" ] || exit 0
IP="$(ifconfig $IFACE | grep inet | grep -v inet6 | awk '{print $2;}' | awk -F: '{print $2;}')"
echo "$IFACE IP: ${IP}"
[ -z "$IP" ] && exit 0
curl "$SERVER:$PORT/update?ip=$IP&host=$(hostname)-$IFACE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment