本文整理汇总了Golang中github.com/miekg/dns.Msg.RecursionDesired方法的典型用法代码示例。如果您正苦于以下问题:Golang Msg.RecursionDesired方法的具体用法?Golang Msg.RecursionDesired怎么用?Golang Msg.RecursionDesired使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类github.com/miekg/dns.Msg
的用法示例。
在下文中一共展示了Msg.RecursionDesired方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: query
// Performs the actual query by service name (browse) or service instance name (lookup),
// start response listeners goroutines and loops over the entries channel.
func (c *client) query(params *LookupParams) error {
var serviceName, serviceInstanceName string
serviceName = fmt.Sprintf("%s.%s.", trimDot(params.Service), trimDot(params.Domain))
if params.Instance != "" {
serviceInstanceName = fmt.Sprintf("%s.%s", params.Instance, serviceName)
}
// send the query
m := new(dns.Msg)
if serviceInstanceName != "" {
m.Question = []dns.Question{
dns.Question{serviceInstanceName, dns.TypeSRV, dns.ClassINET},
dns.Question{serviceInstanceName, dns.TypeTXT, dns.ClassINET},
}
m.RecursionDesired = false
} else {
m.SetQuestion(serviceName, dns.TypePTR)
m.RecursionDesired = false
}
if err := c.sendQuery(m); err != nil {
return err
}
return nil
}
示例2: main
func main() {
if len(os.Args) <= 1 {
log.Printf("Usage: %s domain", os.Args[0])
os.Exit(1)
}
config, _ := dns.ClientConfigFromFile("/etc/resolv.conf")
c := new(dns.Client)
m := new(dns.Msg)
m.SetQuestion(dns.Fqdn(os.Args[1]), dns.TypeMX)
m.RecursionDesired = true
r, _, err := c.Exchange(m, net.JoinHostPort(config.Servers[0], config.Port))
if r == nil {
log.Fatalf("*** error: %s\n", err.Error())
}
if r.Rcode != dns.RcodeSuccess {
log.Fatalf(" *** invalid answer name %s after MX query for %s\n", os.Args[1], os.Args[1])
}
// Stuff must be in the answer section
for _, a := range r.Answer {
fmt.Printf("%v\n", a)
}
}
示例3: assertExchange
// perform a DNS query and assert the reply code, number or answers, etc
func assertExchange(t *testing.T, z string, ty uint16, minAnswers int, maxAnswers int, expErr int) *dns.Msg {
c := new(dns.Client)
c.UDPSize = testUDPBufSize
m := new(dns.Msg)
m.RecursionDesired = true
m.SetQuestion(z, ty)
m.SetEdns0(testUDPBufSize, false) // we don't want to play with truncation here...
r, _, err := c.Exchange(m, fmt.Sprintf("127.0.0.1:%d", testPort))
t.Logf("Response:\n%+v\n", r)
wt.AssertNoErr(t, err)
if minAnswers == 0 && maxAnswers == 0 {
wt.AssertStatus(t, r.Rcode, expErr, "DNS response code")
} else {
wt.AssertStatus(t, r.Rcode, dns.RcodeSuccess, "DNS response code")
}
answers := len(r.Answer)
if minAnswers >= 0 && answers < minAnswers {
wt.Fatalf(t, "Number of answers >= %d", minAnswers)
}
if maxAnswers >= 0 && answers > maxAnswers {
wt.Fatalf(t, "Number of answers <= %d", maxAnswers)
}
return r
}
示例4: lookupHost
func (self *DnsResolver) lookupHost(host string, triesLeft int) ([]net.IP, error) {
m1 := new(dns.Msg)
m1.Id = dns.Id()
m1.RecursionDesired = true
m1.Question = make([]dns.Question, 1)
m1.Question[0] = dns.Question{dns.Fqdn(host), dns.TypeA, dns.ClassINET}
in, err := dns.Exchange(m1, self.Servers[self.r.Intn(len(self.Servers))])
result := []net.IP{}
if err != nil {
if strings.HasSuffix(err.Error(), "i/o timeout") && triesLeft > 0 {
triesLeft -= 1
return self.lookupHost(host, triesLeft)
} else {
return result, err
}
}
if in != nil && in.Rcode != dns.RcodeSuccess {
return result, errors.New(dns.RcodeToString[in.Rcode])
}
for _, record := range in.Answer {
if t, ok := record.(*dns.A); ok {
result = append(result, t.A)
}
}
return result, err
}
示例5: Discover
func (c *Client) Discover(domain string, cb func(*dns.Msg)) {
m := new(dns.Msg)
m.SetQuestion(dns.Fqdn(domain), dns.TypePTR)
m.RecursionDesired = true
addr := &net.UDPAddr{
IP: net.ParseIP("224.0.0.251"),
Port: 5353,
}
conn, err := net.ListenMulticastUDP("udp4", nil, addr)
if err != nil {
panic(err)
}
defer conn.Close()
c.conn = conn
out, err := m.Pack()
if err != nil {
panic(err)
}
_, err = conn.WriteToUDP(out, addr)
if err != nil {
panic(err)
}
c.handleReceiveMsg(domain, cb)
}
示例6: assertExchange
// Perform a DNS query and assert the reply code, number or answers, etc
func assertExchange(t *testing.T, z string, ty uint16, port int, minAnswers int, maxAnswers int, expErr int) (*dns.Msg, *dns.Msg) {
require.NotEqual(t, 0, port, "invalid DNS server port")
c := &dns.Client{
UDPSize: testUDPBufSize,
}
m := new(dns.Msg)
m.RecursionDesired = true
m.SetQuestion(z, ty)
m.SetEdns0(testUDPBufSize, false) // we don't want to play with truncation here...
lstAddr := fmt.Sprintf("127.0.0.1:%d", port)
r, _, err := c.Exchange(m, lstAddr)
t.Logf("Response from '%s':\n%+v\n", lstAddr, r)
if err != nil {
t.Errorf("Error when querying DNS server at %s: %s", lstAddr, err)
}
require.NoError(t, err)
if minAnswers == 0 && maxAnswers == 0 {
require.Equal(t, expErr, r.Rcode, "DNS response code")
} else {
require.Equal(t, dns.RcodeSuccess, r.Rcode, "DNS response code")
}
answers := len(r.Answer)
if minAnswers >= 0 && answers < minAnswers {
require.FailNow(t, fmt.Sprintf("Number of answers >= %d", minAnswers))
}
if maxAnswers >= 0 && answers > maxAnswers {
require.FailNow(t, fmt.Sprintf("Number of answers <= %d", maxAnswers))
}
return m, r
}
示例7: dnsQuery
// dnsQuery will query a nameserver, iterating through the supplied servers as it retries
// The nameserver should include a port, to facilitate testing where we talk to a mock dns server.
func dnsQuery(fqdn string, rtype uint16, nameservers []string, recursive bool) (in *dns.Msg, err error) {
m := new(dns.Msg)
m.SetQuestion(fqdn, rtype)
m.SetEdns0(4096, false)
if !recursive {
m.RecursionDesired = false
}
// Will retry the request based on the number of servers (n+1)
for i := 1; i <= len(nameservers)+1; i++ {
ns := nameservers[i%len(nameservers)]
udp := &dns.Client{Net: "udp", Timeout: DNSTimeout}
in, _, err = udp.Exchange(m, ns)
if err == dns.ErrTruncated {
tcp := &dns.Client{Net: "tcp", Timeout: DNSTimeout}
// If the TCP request suceeds, the err will reset to nil
in, _, err = tcp.Exchange(m, ns)
}
if err == nil {
break
}
}
return
}
示例8: SendQuery
// Async
func (c *MDNSClient) SendQuery(name string, querytype uint16, insistent bool, responseCh chan<- *Response) {
c.actionChan <- func() {
query, found := c.inflight[name]
if !found {
m := new(dns.Msg)
m.SetQuestion(name, querytype)
m.RecursionDesired = false
buf, err := m.Pack()
if err != nil {
responseCh <- &Response{err: err}
close(responseCh)
return
}
query = &inflightQuery{
name: name,
id: m.Id,
}
if _, err = c.conn.WriteTo(buf, c.addr); err != nil {
responseCh <- &Response{err: err}
close(responseCh)
return
}
c.inflight[name] = query
}
info := &responseInfo{
ch: responseCh,
timeout: time.Now().Add(mDNSTimeout),
insistent: insistent,
}
// Invariant on responseInfos: they are in ascending order of
// timeout. Since we use a fixed interval from Now(), this
// must be after all existing timeouts.
query.responseInfos = append(query.responseInfos, info)
}
}
示例9: makeDnsTxtRequest
func makeDnsTxtRequest(domain string, server string) (string, error) {
var err error
var conn *dns.Conn
if conn, err = dns.Dial("udp", server); err != nil {
return "", err
}
m := new(dns.Msg)
m.SetQuestion(dns.Fqdn(domain), dns.TypeTXT)
m.RecursionDesired = true
if err = conn.WriteMsg(m); err != nil {
return "", err
}
var rm *dns.Msg
if rm, err = conn.ReadMsg(); err != nil {
return "", err
}
if txt, ok := rm.Answer[0].(*dns.TXT); !ok {
return "", fmt.Errorf("No TXT Answer")
} else {
return strings.Join(txt.Txt, ""), nil
}
}
示例10: createDKIMQuery
func createDKIMQuery(selector, domain string) *dns.Msg {
q := fmt.Sprintf("%s._domainkey.%s", selector, domain)
m := new(dns.Msg)
m.SetQuestion(dns.Fqdn(q), dns.TypeTXT)
m.RecursionDesired = true
return m
}
示例11: TestPrune
// Check that we can prune an answer
func TestPrune(t *testing.T) {
InitDefaultLogging(testing.Verbose())
Info.Println("TestPrune starting")
questionMsg := new(dns.Msg)
questionMsg.SetQuestion("name", dns.TypeA)
questionMsg.RecursionDesired = true
question := &questionMsg.Question[0]
records := []ZoneRecord{
Record{"name", net.ParseIP("10.0.1.1"), 0, 0, 0},
Record{"name", net.ParseIP("10.0.1.2"), 0, 0, 0},
Record{"name", net.ParseIP("10.0.1.3"), 0, 0, 0},
Record{"name", net.ParseIP("10.0.1.4"), 0, 0, 0},
}
reply := makeAddressReply(questionMsg, question, records, DefaultLocalTTL)
reply.Answer[0].Header().Ttl = DefaultLocalTTL
pruned := pruneAnswers(reply.Answer, 1)
require.Equal(t, 1, len(pruned), "wrong number of answers")
pruned = pruneAnswers(reply.Answer, 2)
require.Equal(t, 2, len(pruned), "wrong number of answers")
pruned = pruneAnswers(reply.Answer, 0)
require.Equal(t, len(records), len(pruned), "wrong number of answers")
}
示例12: DnsQuery
func DnsQuery(query string, wg *sync.WaitGroup, config *dns.ClientConfig, cm *chanman.ChanMan) {
defer wg.Done()
dnsClient := new(dns.Client)
message := new(dns.Msg)
message.SetQuestion(dns.Fqdn(query), dns.TypeA)
message.RecursionDesired = true
response, rtt, err := dnsClient.Exchange(message, net.JoinHostPort(config.Servers[0], "53"))
if err != nil {
log.Println(err)
cm.RunChan <- true
}
if response == nil {
} else {
if response.Rcode != dns.RcodeSuccess {
log.Println(" query fail")
}
var stat = new(dnsstat.Info)
stat.Rtt = rtt
cm.StatsChan <- stat
cm.RunChan <- true
}
}
示例13: newMsg
func newMsg(host string, qClass uint16) *dns.Msg {
m1 := new(dns.Msg)
m1.Id = dns.Id()
m1.RecursionDesired = true
m1.Question = make([]dns.Question, 1)
m1.Question[0] = dns.Question{host, qClass, dns.ClassINET}
return m1
}
示例14: localQuery
func localQuery(mychan chan DNSreply, qname string, qtype uint16) {
var result DNSreply
var trials uint
result.qname = qname
result.qtype = qtype
result.r = nil
result.err = errors.New("No name server to answer the question")
localm := new(dns.Msg)
localm.Id = dns.Id()
localm.RecursionDesired = true
localm.Question = make([]dns.Question, 1)
localm.SetEdns0(EDNSBUFFERSIZE, false) // Even if no EDNS requested, see #9 May be we should retry without it if timeout?
localc := new(dns.Client)
localc.ReadTimeout = timeout
localm.Question[0] = dns.Question{qname, qtype, dns.ClassINET}
Tests:
for trials = 0; trials < uint(*maxTrials); trials++ {
Resolvers:
for serverIndex := range conf.Servers {
server := conf.Servers[serverIndex]
result.nameserver = server
// Brackets around the server address are necessary for IPv6 name servers
r, rtt, err := localc.Exchange(localm, "["+server+"]:"+conf.Port) // Do not use net.JoinHostPort, see https://github.com/bortzmeyer/check-soa/commit/3e4edb13855d8c4016768796b2892aa83eda1933#commitcomment-2355543
if r == nil {
result.r = nil
result.err = err
if strings.Contains(err.Error(), "timeout") {
// Try another resolver
break Resolvers
} else { // We give in
break Tests
}
} else {
result.rtt = rtt
if r.Rcode == dns.RcodeSuccess {
// TODO: as a result, NODATA (NOERROR/ANSWER=0) are silently ignored (try "foo", for instance, the name exists but no IP address)
// TODO: for rcodes like SERVFAIL, trying another resolver could make sense
result.r = r
result.err = nil
break Tests
} else {
// All the other codes are errors. Yes, it may
// happens that one resolver returns REFUSED
// and the others work but we do not handle
// this case. TODO: delete the resolver from
// the list and try another one
result.r = r
result.err = errors.New(dns.RcodeToString[r.Rcode])
break Tests
}
}
}
}
if *debug {
fmt.Printf("DEBUG: end of DNS request \"%s\" / %d\n", qname, qtype)
}
mychan <- result
}
示例15: probe
// Perform probing & announcement
//TODO: implement a proper probing & conflict resolution
func (s *Server) probe() {
q := new(dns.Msg)
q.SetQuestion(s.service.ServiceInstanceName(), dns.TypePTR)
q.RecursionDesired = false
srv := &dns.SRV{
Hdr: dns.RR_Header{
Name: s.service.ServiceInstanceName(),
Rrtype: dns.TypeSRV,
Class: dns.ClassINET,
Ttl: s.ttl,
},
Priority: 0,
Weight: 0,
Port: uint16(s.service.Port),
Target: s.service.HostName,
}
txt := &dns.TXT{
Hdr: dns.RR_Header{
Name: s.service.ServiceInstanceName(),
Rrtype: dns.TypeTXT,
Class: dns.ClassINET,
Ttl: s.ttl,
},
Txt: s.service.Text,
}
q.Ns = []dns.RR{srv, txt}
randomizer := rand.New(rand.NewSource(time.Now().UnixNano()))
for i := 0; i < 3; i++ {
if err := s.multicastResponse(q); err != nil {
log.Println("[ERR] bonjour: failed to send probe:", err.Error())
}
time.Sleep(time.Duration(randomizer.Intn(250)) * time.Millisecond)
}
resp := new(dns.Msg)
resp.MsgHdr.Response = true
resp.Answer = []dns.RR{}
resp.Extra = []dns.RR{}
s.composeLookupAnswers(resp, s.ttl)
// From RFC6762
// The Multicast DNS responder MUST send at least two unsolicited
// responses, one second apart. To provide increased robustness against
// packet loss, a responder MAY send up to eight unsolicited responses,
// provided that the interval between unsolicited responses increases by
// at least a factor of two with every response sent.
timeout := 1 * time.Second
for i := 0; i < 3; i++ {
if err := s.multicastResponse(resp); err != nil {
log.Println("[ERR] bonjour: failed to send announcement:", err.Error())
}
time.Sleep(timeout)
timeout *= 2
}
}