本文整理匯總了Golang中github.com/miekg/dns.Client.Net方法的典型用法代碼示例。如果您正苦於以下問題:Golang Client.Net方法的具體用法?Golang Client.Net怎麽用?Golang Client.Net使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類github.com/miekg/dns.Client
的用法示例。
在下文中一共展示了Client.Net方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: forwardQuestion
func forwardQuestion(q *dns.Question, forwarders []string) []dns.RR {
//qType := dns.Type(q.Qtype).String() // query type
//log.Printf("[Forwarder Lookup [%s] [%s]]\n", q.Name, qType)
myReq := new(dns.Msg)
myReq.SetQuestion(q.Name, q.Qtype)
if len(forwarders) == 0 {
// we have no upstreams, so we'll just not use any
} else if strings.TrimSpace(forwarders[0]) == "!" {
// we've been told explicitly to not pass anything along to any upsteams
} else {
c := new(dns.Client)
for _, server := range forwarders {
c.Net = "udp"
m, _, err := c.Exchange(myReq, strings.TrimSpace(server))
if m != nil && m.MsgHdr.Truncated {
c.Net = "tcp"
m, _, err = c.Exchange(myReq, strings.TrimSpace(server))
}
// FIXME: Cache misses. And cache hits, too.
if err != nil {
//log.Printf("[Forwarder Lookup [%s] [%s] failed: [%s]]\n", q.Name, qType, err)
log.Println(err)
} else {
//log.Printf("[Forwarder Lookup [%s] [%s] success]\n", q.Name, qType)
return m.Answer
}
}
}
return nil
}
示例2: ServerHandler
// Returns an anonymous function configured to resolve DNS
// queries with a specific set of remote servers.
func ServerHandler(addresses []string) handler {
randGen := rand.New(rand.NewSource(time.Now().UnixNano()))
// This is the actual handler
return func(w dns.ResponseWriter, req *dns.Msg) {
nameserver := addresses[randGen.Intn(len(addresses))]
var protocol string
switch t := w.RemoteAddr().(type) {
default:
log.Printf("ERROR: Unsupported protocol %T\n", t)
return
case *net.UDPAddr:
protocol = "udp"
case *net.TCPAddr:
protocol = "tcp"
}
for _, q := range req.Question {
log.Printf("Incoming request #%v: %s %s %v - using %s\n",
req.Id,
dns.ClassToString[q.Qclass],
dns.TypeToString[q.Qtype],
q.Name, nameserver)
}
c := new(dns.Client)
c.Net = protocol
resp, rtt, err := c.Exchange(req, nameserver)
Redo:
switch {
case err != nil:
log.Printf("ERROR: %s\n", err.Error())
sendFailure(w, req)
return
case req.Id != resp.Id:
log.Printf("ERROR: Id mismatch: %v != %v\n", req.Id, resp.Id)
sendFailure(w, req)
return
case resp.MsgHdr.Truncated && protocol != "tcp":
log.Printf("WARNING: Truncated answer for request %v, retrying TCP\n", req.Id)
c.Net = "tcp"
resp, rtt, err = c.Exchange(req, nameserver)
goto Redo
}
log.Printf("Request #%v: %.3d µs, server: %s(%s), size: %d bytes\n", resp.Id, rtt/1e3, nameserver, c.Net, resp.Len())
w.WriteMsg(resp)
} // end of handler
}
示例3: shouldTransfer
// shouldTransfer checks the primaries of zone, retrieves the SOA record, checks the current serial
// and the remote serial and will return true if the remote one is higher than the locally configured one.
func (z *Zone) shouldTransfer() (bool, error) {
c := new(dns.Client)
c.Net = "tcp" // do this query over TCP to minimize spoofing
m := new(dns.Msg)
m.SetQuestion(z.origin, dns.TypeSOA)
var Err error
serial := -1
Transfer:
for _, tr := range z.TransferFrom {
Err = nil
ret, err := middleware.Exchange(c, m, tr)
if err != nil || ret.Rcode != dns.RcodeSuccess {
Err = err
continue
}
for _, a := range ret.Answer {
if a.Header().Rrtype == dns.TypeSOA {
serial = int(a.(*dns.SOA).Serial)
break Transfer
}
}
}
if serial == -1 {
return false, Err
}
return less(z.Apex.SOA.Serial, uint32(serial)), Err
}
示例4: DoDNSquery
func (this Server) DoDNSquery(m dns.Msg, TransProString string, server []string, timeout time.Duration) (*dns.Msg, error) {
dnsClient := new(dns.Client)
if dnsClient == nil {
return nil, errors.New("Cannot create DNS client")
}
dnsClient.ReadTimeout = timeout
dnsClient.WriteTimeout = timeout
if TransProString != "TCP" && TransProString != "UDP" {
return nil, errors.New("TransProString run")
}
dnsClient.Net = strings.ToLower(TransProString)
ServerStr := server[rand.Intn(len(server))]
ServerAddr := net.ParseIP(ServerStr)
if ServerAddr.To16() != nil {
ServerStr = "[" + ServerStr + "]:" + this.Port
} else if ServerAddr.To4() != nil {
ServerStr = ServerStr + this.Port
} else {
return nil, errors.New("invalid Server Address")
}
dnsResponse, _, err := dnsClient.Exchange(&m, ServerStr)
if err != nil {
return nil, err
}
return dnsResponse, nil
}
示例5: resolve
// Perform DNS resolution
func resolve(w http.ResponseWriter, r *http.Request, server string, domain string, querytype uint16) {
m := new(dns.Msg)
m.SetQuestion(domain, querytype)
m.MsgHdr.RecursionDesired = true
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
c := new(dns.Client)
Redo:
if in, _, err := c.Exchange(m, server); err == nil { // Second return value is RTT, not used for now
if in.MsgHdr.Truncated {
c.Net = "tcp"
goto Redo
}
switch in.MsgHdr.Rcode {
case dns.RcodeServerFailure:
error(w, 500, 502, "The name server encountered an internal failure while processing this request (SERVFAIL)")
case dns.RcodeNameError:
error(w, 500, 503, "Some name that ought to exist, does not exist (NXDOMAIN)")
case dns.RcodeRefused:
error(w, 500, 505, "The name server refuses to perform the specified operation for policy or security reasons (REFUSED)")
default:
jsonify(w, r, in.Question, in.Answer, in.Ns, in.Extra)
}
} else {
error(w, 500, 501, "DNS server could not be reached")
}
}
示例6: lookup
func lookup(msg *dns.Msg, client *dns.Client, server string, edns bool) (*dns.Msg, error) {
if edns {
opt := &dns.OPT{
Hdr: dns.RR_Header{
Name: ".",
Rrtype: dns.TypeOPT,
},
}
opt.SetUDPSize(dns.DefaultMsgSize)
msg.Extra = append(msg.Extra, opt)
}
response, _, err := client.Exchange(msg, server)
if err != nil {
return nil, err
}
if msg.Id != response.Id {
return nil, fmt.Errorf("DNS ID mismatch, request: %d, response: %d", msg.Id, response.Id)
}
if response.MsgHdr.Truncated {
if client.Net == "tcp" {
return nil, fmt.Errorf("Got truncated message on tcp")
}
if edns { // Truncated even though EDNS is used
client.Net = "tcp"
}
return lookup(msg, client, server, !edns)
}
return response, nil
}
示例7: NewDNSResolverImpl
// NewDNSResolverImpl constructs a new DNS resolver object that utilizes the
// provided list of DNS servers for resolution.
func NewDNSResolverImpl(
readTimeout time.Duration,
servers []string,
caaSERVFAILExceptions map[string]bool,
stats metrics.Scope,
clk clock.Clock,
maxTries int,
) *DNSResolverImpl {
// TODO(jmhodges): make constructor use an Option func pattern
dnsClient := new(dns.Client)
// Set timeout for underlying net.Conn
dnsClient.ReadTimeout = readTimeout
dnsClient.Net = "tcp"
return &DNSResolverImpl{
dnsClient: dnsClient,
servers: servers,
allowRestrictedAddresses: false,
caaSERVFAILExceptions: caaSERVFAILExceptions,
maxTries: maxTries,
clk: clk,
stats: stats,
txtStats: stats.NewScope("TXT"),
aStats: stats.NewScope("A"),
aaaaStats: stats.NewScope("AAAA"),
caaStats: stats.NewScope("CAA"),
mxStats: stats.NewScope("MX"),
}
}
示例8: lookup
func lookup(name string, queryType uint16, client *dns.Client, servAddr string, suffix string, edns bool) (*dns.Msg, error) {
msg := &dns.Msg{}
lname := strings.Join([]string{name, suffix}, ".")
msg.SetQuestion(dns.Fqdn(lname), queryType)
if edns {
msg.SetEdns0(dns.DefaultMsgSize, false)
}
response, _, err := client.Exchange(msg, servAddr)
if err == dns.ErrTruncated {
if client.Net == "tcp" {
return nil, fmt.Errorf("got truncated message on TCP (64kiB limit exceeded?)")
}
if edns { // Truncated even though EDNS is used
client.Net = "tcp"
}
return lookup(name, queryType, client, servAddr, suffix, !edns)
}
if err != nil {
return nil, err
}
if msg.Id != response.Id {
return nil, fmt.Errorf("DNS ID mismatch, request: %d, response: %d", msg.Id, response.Id)
}
return response, nil
}
示例9: TestDNSForward
func TestDNSForward(t *testing.T) {
s := newTestServer("", "", "8.8.8.8:53")
defer s.Stop()
c := new(dns.Client)
m := new(dns.Msg)
m.SetQuestion("www.example.com.", dns.TypeA)
resp, _, err := c.Exchange(m, "localhost:"+StrPort)
if err != nil {
t.Fatal(err)
}
if len(resp.Answer) == 0 || resp.Rcode != dns.RcodeSuccess {
t.Fatal("Answer expected to have A records or rcode not equal to RcodeSuccess")
}
// TCP
c.Net = "tcp"
resp, _, err = c.Exchange(m, "localhost:"+StrPort)
if err != nil {
t.Fatal(err)
}
if len(resp.Answer) == 0 || resp.Rcode != dns.RcodeSuccess {
t.Fatal("Answer expected to have A records or rcode not equal to RcodeSuccess")
}
// TODO(miek): DNSSEC DO query
}
示例10: TestDNSForwardLocal
func TestDNSForwardLocal(t *testing.T) {
forwardServer := newTestServer(t, false)
service := &msg.Service{
Host: "199.43.132.53", Key: "a.skydns.test.",
}
addService(t, forwardServer, service.Key, 0, service)
defer delService(t, forwardServer, service.Key)
s := newTestServer(t, false)
s.config.Nameservers = []string{forwardServer.config.DnsAddr}
s.config.ForwardLocal = true
defer s.Stop()
c := new(dns.Client)
m := new(dns.Msg)
m.SetQuestion("a.skydns.test.", dns.TypeA)
resp, _, err := c.Exchange(m, "127.0.0.1:"+StrPort)
if err != nil {
// try twice
resp, _, err = c.Exchange(m, "127.0.0.1:"+StrPort)
if err != nil {
t.Fatal(err)
}
}
if len(resp.Answer) == 0 || resp.Rcode != dns.RcodeSuccess {
t.Fatal("answer expected to have A records or rcode not equal to RcodeSuccess")
}
// TCP
c.Net = "tcp"
resp, _, err = c.Exchange(m, "127.0.0.1:"+StrPort)
if err != nil {
t.Fatal(err)
}
if len(resp.Answer) == 0 || resp.Rcode != dns.RcodeSuccess {
t.Fatal("answer expected to have A records or rcode not equal to RcodeSuccess")
}
m.SetQuestion("bbbbb.skydns.test.", dns.TypeA)
resp, _, err = c.Exchange(m, "127.0.0.1:"+StrPort)
if err != nil {
t.Fatal(err)
}
if len(resp.Answer) != 0 {
t.Fatal("answer expected to have zero A records")
}
// disable recursion and check
s.config.NoRec = true
m.SetQuestion("a.skydns.test.", dns.TypeA)
resp, _, err = c.Exchange(m, "127.0.0.1:"+StrPort)
if err != nil {
t.Fatal(err)
}
if resp.Rcode != dns.RcodeServerFailure {
t.Fatal("answer expected to have rcode equal to RcodeFailure")
}
}
示例11: exchange
func (r *Resolver) exchange(m *dns.Msg, a string, original []string) (res *dns.Msg, err error) {
question := m.Question[0]
sort.Strings(original)
key := cachekey{question, fmt.Sprintf("%v", original)}
if r.Debug {
log.Println("KEY: ", key)
}
rt, ok := r.cache.Get(key)
if ok {
if r.Debug {
log.Println("Cache HIT")
}
r1 := rt.(*dns.Msg)
res = r1.Copy()
return
}
if r.Debug {
log.Println("Cache MISS")
log.Println("QUERY: ", question.Name, "via", a)
}
res, err = dns.Exchange(m, a)
if err != nil {
if r.Debug {
log.Println(err)
}
return
}
//Retry in case it was truncated
if res.Truncated {
if r.Debug {
log.Println("truncated, retrying with tcp")
}
cl := new(dns.Client)
cl.Net = "tcp"
res, _, err = cl.Exchange(m, a)
if err != nil {
if r.Debug {
log.Println(err)
}
return
}
}
if r.Debug {
log.Println(res)
}
if res.Rcode != dns.RcodeSuccess {
return
}
if r.Debug {
log.Println("Inserting into cache")
}
r.cache.Add(key, res)
return
}
示例12: sendRequest
/*
* sendRequest() - send a DNS query
*/
func sendRequest(ctx *Context, m *dns.Msg, transport string, timeout time.Duration) (response *dns.Msg, rtt time.Duration, err error) {
c := new(dns.Client)
c.Timeout = timeout
c.Net = transport // "udp" or "tcp"
response, rtt, err = c.Exchange(m, addressString(ctx.server, ctx.port))
return
}
示例13: queryRemote
func queryRemote(r *dns.Msg, ch chan *dns.Msg) {
c := new(dns.Client)
c.Net = "tcp"
in, _, err := c.Exchange(r, *remoteDNS)
if err == nil {
ch <- in
} else {
logger.Printf("Failed to query, %q", err)
}
}
示例14: tcpLookupIP
// tcpLookupIP is a helper to initiate a TCP-based DNS lookup for the given host.
// The built-in Go resolver will do a UDP lookup first, and will only use TCP if
// the response has the truncate bit set, which isn't common on DNS servers like
// Consul's. By doing the TCP lookup directly, we get the best chance for the
// largest list of hosts to join. Since joins are relatively rare events, it's ok
// to do this rather expensive operation.
func (m *Memberlist) tcpLookupIP(host string, defaultPort uint16) ([]ipPort, error) {
// Don't attempt any TCP lookups against non-fully qualified domain
// names, since those will likely come from the resolv.conf file.
if !strings.Contains(host, ".") {
return nil, nil
}
// Make sure the domain name is terminated with a dot (we know there's
// at least one character at this point).
dn := host
if dn[len(dn)-1] != '.' {
dn = dn + "."
}
// See if we can find a server to try.
cc, err := dns.ClientConfigFromFile(m.config.DNSConfigPath)
if err != nil {
return nil, err
}
if len(cc.Servers) > 0 {
// We support host:port in the DNS config, but need to add the
// default port if one is not supplied.
server := cc.Servers[0]
if !hasPort(server) {
server = net.JoinHostPort(server, cc.Port)
}
// Do the lookup.
c := new(dns.Client)
c.Net = "tcp"
msg := new(dns.Msg)
msg.SetQuestion(dn, dns.TypeANY)
in, _, err := c.Exchange(msg, server)
if err != nil {
return nil, err
}
// Handle any IPs we get back that we can attempt to join.
var ips []ipPort
for _, r := range in.Answer {
switch rr := r.(type) {
case (*dns.A):
ips = append(ips, ipPort{rr.A, defaultPort})
case (*dns.AAAA):
ips = append(ips, ipPort{rr.AAAA, defaultPort})
case (*dns.CNAME):
m.logger.Printf("[DEBUG] memberlist: Ignoring CNAME RR in TCP-first answer for '%s'", host)
}
}
return ips, nil
}
return nil, nil
}
示例15: doQuery
func doQuery(c dns.Client, m dns.Msg, ds, dp string, queryType uint16, close chan struct{}) *dns.Msg {
// r := &dns.Msg{}
// var ee error
//fmt.Println(utils.GetDebugLine(), " doQuery: ", " m.Question: ", m.Question,
// " ds: ", ds, " dp: ", dp, " queryType ", queryType)
utils.ServerLogger.Debug(" doQuery: m.Question: %v ds: %s dp: %s queryType: %v", m.Question, ds, dp, queryType)
select {
case <-close:
return nil
default:
for l := 0; l < 3; l++ {
r, _, ee := c.Exchange(&m, ds+":"+dp)
if (ee != nil) || (r == nil) || (r.Answer == nil) {
utils.ServerLogger.Error(" doQuery: retry: %s times error: %s", strconv.Itoa(l), ee.Error())
if (queryType == dns.TypeA) || (queryType == dns.TypeCNAME) {
if strings.Contains(ee.Error(), "connection refused") {
if c.Net == TCP {
c.Net = UDP
}
} else if (ee == dns.ErrTruncated) && queryType == dns.TypeA {
utils.ServerLogger.Error(" doQuery: response truncated: %v", r)
// m.SetEdns0(4096,false)
// m.SetQuestion(dns.Fqdn(domainName),dns.TypeCNAME)
c.Net = TCP
} else {
if c.Net == TCP {
c.Net = UDP
} else {
c.Net = TCP
}
}
}
} else {
return r
}
}
}
return nil
}