homepage/mp.cgi.go

89 lines
1.8 KiB
Go
Raw Normal View History

2013-12-30 17:35:21 -07:00
package main
import (
"net"
"fmt"
"time"
2014-12-27 16:52:34 -07:00
"sync"
2013-12-30 17:35:21 -07:00
)
2015-10-29 08:43:15 -06:00
var hosts = []HostEntry{
{"h.woozle.org:30919", "Ginnie (tablet)"},
{"h.woozle.org:44321", "Ginnie"},
{"h.woozle.org:58000", "Amy"},
{"h.woozle.org:29837", "Neale"},
}
2013-12-30 17:35:21 -07:00
const MAGIC = "\x00\xff\xff\x00\xfe\xfe\xfe\xfe\xfd\xfd\xfd\xfd\x12\x34\x56\x78"
2014-12-27 16:52:34 -07:00
func isAlive(host string) bool {
conn, err := net.Dial("udp", host)
2013-12-30 17:35:21 -07:00
if err != nil {
return false
}
conn.SetReadDeadline(time.Now().Add(5 * time.Second))
pkt := "\x01" + "\x00\x00\x00\x00MERF" + MAGIC
conn.Write([]byte(pkt))
resp := make([]byte, 40)
rlen, err := conn.Read(resp)
if (err != nil) || (rlen == 0) {
return false
}
return true
}
2014-12-27 16:52:34 -07:00
var wg sync.WaitGroup
func waitClose(c chan<- string) {
wg.Wait()
close(c)
}
type HostEntry struct {
host string
owner string
}
func ping(results chan<- string, e HostEntry) {
defer wg.Done()
if isAlive(e.host) {
results <- fmt.Sprintf("%s is playing at %s", e.owner, e.host)
}
}
2013-12-30 17:35:21 -07:00
func main() {
2014-12-27 16:52:34 -07:00
results := make(chan string, 5)
for _, host := range hosts {
wg.Add(1)
go ping(results, host)
}
go waitClose(results)
2013-12-30 17:35:21 -07:00
fmt.Println("Content-type: text/html")
fmt.Println("")
fmt.Println("<!DOCTYPE html>")
fmt.Println("<html>")
fmt.Println("<head>")
fmt.Println("<meta name=\"viewport\" content=\"width=device-width\">")
2014-12-27 16:52:34 -07:00
fmt.Println("<style type=\"text/css\">#a{font-size: 120%; background: silver;}</style>")
fmt.Println("<title>Minecraft PE ping</title></head>")
2013-12-30 17:35:21 -07:00
fmt.Println("<body>")
2014-12-27 16:52:34 -07:00
fmt.Println("<h1>Are The Picketts playing Minecraft PE?</h1>")
fmt.Println("<ul id=\"a\">")
2014-12-27 16:55:03 -07:00
count := 0
2014-12-27 16:52:34 -07:00
for msg := range results {
fmt.Printf("<li>%s</li>\n", msg)
2014-12-27 16:55:03 -07:00
count += 1
2013-12-30 17:35:21 -07:00
}
2014-12-27 16:52:34 -07:00
fmt.Println("</ul>")
2014-12-27 16:55:03 -07:00
if count == 0 {
fmt.Println("<p>Sorry, looks like nobody's playing right now.</p>")
}
2013-12-30 17:35:21 -07:00
fmt.Println("</body></html>")
}