Created
December 23, 2016 11:36
-
-
Save miekg/3f2d21e5c2cf74572d888626e1bf193e to your computer and use it in GitHub Desktop.
parse server records
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"github.com/miekg/dns" | |
) | |
func main() { | |
fmt.Println("vim-go") | |
rr, _ := dns.NewRR("_sip._tcp.example.com. 86400 IN SRV 0 5 5060 sipserver.example.com.") | |
println(parseSRV(rr)) | |
rr, _ = dns.NewRR("miek.nl. 86400 IN SRV 0 5 5060 sipserver.example.com.") | |
println(parseSRV(rr)) | |
rr, _ = dns.NewRR("_si\\.p._tcp.example.com. 86400 IN SRV 0 5 5060 sipserver.example.com.") | |
println(parseSRV(rr)) | |
} | |
// ParseSRV parses a server records and removed the _http._tcp labels to leave the | |
// actual domain name. If the srv record's ownername does not follow this scheme | |
// then whole name it returned. | |
// The function checks if the first label start with an "_" and the second | |
// label is either "_tcp" or "_udp". | |
func parseSRV(srv dns.RR) string { | |
name := srv.Header().Name | |
// Does it start with a "_" ? | |
if len(name) > 0 && name[0] != '_' { | |
return name | |
} | |
// First label | |
first, end := dns.NextLabel(name, 0) | |
if end { | |
return name | |
} | |
// Second label | |
off, end := dns.NextLabel(name, first) | |
if end { | |
return name | |
} | |
// first:off has captured _tcp. or _udp. (if present) | |
second := name[first:off] | |
if len(second) > 0 && second[0] != '_' { | |
return name | |
} | |
if len(second) != 5 { | |
return name | |
} | |
// bit convoluted to avoid strings.ToLower | |
// matches _tcp | |
if (second[1] == 't' || second[1] == 'T') && (second[2] == 'c' || second[2] == 'C') && | |
(second[3] == 'p' || second[3] == 'P') { | |
return name[off:] | |
} | |
// matches _udp | |
if (second[1] == 'u' || second[1] == 'U') && (second[2] == 'd' || second[2] == 'D') && | |
(second[3] == 'p' || second[3] == 'P') { | |
return name[off:] | |
} | |
return name | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment