Skip to content

Instantly share code, notes, and snippets.

@Code-Hex
Created August 2, 2022 15:03
Show Gist options
  • Save Code-Hex/706484a691b50a77bf2c1e60d449ae86 to your computer and use it in GitHub Desktop.
Save Code-Hex/706484a691b50a77bf2c1e60d449ae86 to your computer and use it in GitHub Desktop.
ls-upnp - List of UPnP devices on your local network. Written by Go
package main
import (
"fmt"
"net"
"os"
"strings"
"time"
)
func main() {
if err := run(); err != nil {
fmt.Fprintf(os.Stderr, "run failed: %q", err)
os.Exit(1)
}
}
var lines = []string{
"M-SEARCH * HTTP/1.1",
"HOST: 239.255.255.250:1900",
"MAN: ssdp:discover",
"MX: 5",
"ST: ssdp:all",
"",
"",
}
func run() error {
conn, err := net.ListenPacket("udp", ":0")
if err != nil {
return err
}
defer conn.Close()
upnpAddr, err := net.ResolveUDPAddr("udp", "239.255.255.250:1900")
if err != nil {
return fmt.Errorf("failed to resolve upnp addr: %w", err)
}
_, err = conn.WriteTo([]byte(strings.Join(lines, "\r\n")), upnpAddr)
if err != nil {
return fmt.Errorf("failed to write request: %w", err)
}
data := make([]byte, 4096)
for {
conn.SetReadDeadline(time.Now().Add(3 * time.Second))
n, remoteAddr, err := conn.ReadFrom(data)
if err != nil {
if os.IsTimeout(err) {
return nil
}
return err
}
fmt.Println("<---------------", remoteAddr.String())
fmt.Println(string(data[:n]))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment