本文整理匯總了Golang中github.com/miekg/dns.Id函數的典型用法代碼示例。如果您正苦於以下問題:Golang Id函數的具體用法?Golang Id怎麽用?Golang Id使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Id函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: RoundRobin
func (s *server) RoundRobin(rrs []dns.RR) {
if !s.config.RoundRobin {
return
}
// If we have more than 1 CNAME don't touch the packet, because some stub resolver (=glibc)
// can't deal with the returned packet if the CNAMEs need to be accesses in the reverse order.
cname := 0
for _, r := range rrs {
if r.Header().Rrtype == dns.TypeCNAME {
cname++
if cname > 1 {
return
}
}
}
switch l := len(rrs); l {
case 2:
if dns.Id()%2 == 0 {
rrs[0], rrs[1] = rrs[1], rrs[0]
}
default:
for j := 0; j < l*(int(dns.Id())%4+1); j++ {
q := int(dns.Id()) % l
p := int(dns.Id()) % l
if q == p {
p = (p + 1) % l
}
rrs[q], rrs[p] = rrs[p], rrs[q]
}
}
}
示例2: 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
}
示例3: handleRecursive
func (h *handler) handleRecursive(w dns.ResponseWriter, req *dns.Msg) {
h.ns.debugf("recursive request: %+v", *req)
// Resolve unqualified names locally
if len(req.Question) == 1 {
hostname := dns.Fqdn(req.Question[0].Name)
if strings.Count(hostname, ".") == 1 {
h.handleLocal(w, req)
return
}
}
upstreamConfig, err := h.upstream.Config()
if err != nil {
h.ns.errorf("unable to read upstream config: %s", err)
}
for _, server := range upstreamConfig.Servers {
reqCopy := req.Copy()
reqCopy.Id = dns.Id()
response, _, err := h.client.Exchange(reqCopy, fmt.Sprintf("%s:%s", server, upstreamConfig.Port))
if (err != nil && err != dns.ErrTruncated) || response == nil {
h.ns.debugf("error trying %s: %v", server, err)
continue
}
response.Id = req.Id
if h.responseTooBig(req, response) {
response.Compress = true
}
h.respond(w, response)
return
}
h.respond(w, h.makeErrorResponse(req, dns.RcodeServerFailure))
}
示例4: TestDNSHandlerMultiQuestions
func TestDNSHandlerMultiQuestions(t *testing.T) {
var (
h = newDNSHandler(&testStore{}, "tt", dns.Fqdn("test.glimpse.io"))
m = &dns.Msg{}
w = &testWriter{}
)
m.Id = dns.Id()
m.RecursionDesired = true
m.Question = make([]dns.Question, 3)
for i := range m.Question {
m.Question[i] = dns.Question{
Name: "foo.bar.baz.",
Qtype: dns.TypeA,
Qclass: dns.ClassINET,
}
}
h.ServeDNS(w, m)
r := w.msg
if want, have := dns.RcodeNotImplemented, r.Rcode; want != have {
t.Errorf(
"want rcode %s, have %s",
dns.RcodeToString[want],
dns.RcodeToString[have],
)
}
}
示例5: TestStress
func TestStress(t *testing.T) {
domains := []string{"www.google.com.", "www.isc.org.", "www.outlook.com.", "miek.nl.", "doesnotexist.miek.nl."}
l := len(domains)
max := 8
procs := runtime.GOMAXPROCS(max)
wg := new(sync.WaitGroup)
wg.Add(max)
u := New()
defer u.Destroy()
if err := u.ResolvConf("/etc/resolv.conf"); err != nil {
return
}
for i := 0; i < max; i++ {
go func() {
for i := 0; i < 100; i++ {
d := domains[int(dns.Id())%l]
r, err := u.Resolve(d, dns.TypeA, dns.ClassINET)
if err != nil {
t.Log("failure to resolve: " + d)
continue
}
if !r.HaveData && d != "doesnotexist.miek.nl." {
t.Log("no data when resolving: " + d)
continue
}
}
wg.Done()
}()
}
wg.Wait()
runtime.GOMAXPROCS(procs)
}
示例6: queryDNSServer
// Uses github.com/miekg/dns package, in order to invoke one query.
func (r *Resolver) queryDNSServer(dnsServer, domainname, rrType string, edns bool) (*dns.Msg, error) {
fqdn := dns.Fqdn(domainname)
r.dnsQueryMsg.Id = dns.Id()
r.dnsQueryMsg.SetQuestion(fqdn, dns.StringToType[rrType])
dnsServerSocket := dnsServer + ":" + DNSPORT
dnsResponseMsg, err := dns.Exchange(r.dnsQueryMsg, dnsServerSocket)
if err != nil {
return nil, errors.New("dns.Exchange() failed")
}
if r.dnsQueryMsg.Id != dnsResponseMsg.Id {
log.Printf("DNS msgID mismatch: Request-ID(%d), Response-ID(%d)", r.dnsQueryMsg.Id, dnsResponseMsg.Id)
return nil, errors.New("DNS Msg-ID mismatch")
}
if dnsResponseMsg.MsgHdr.Truncated {
if r.dnsClient.Net == "tcp" {
return nil, errors.New("Received invalid truncated Msg over TCP") //fmt.Errorf("Got truncated message on tcp")
}
if edns {
r.dnsClient.Net = "tcp"
}
return r.queryDNSServer(dnsServer, domainname, rrType, !edns)
}
return dnsResponseMsg, nil
}
示例7: handleRecursive
func (d *DNSServer) handleRecursive(client *dns.Client, defaultMaxResponseSize int) func(dns.ResponseWriter, *dns.Msg) {
return func(w dns.ResponseWriter, req *dns.Msg) {
d.ns.debugf("recursive request: %+v", *req)
// Resolve unqualified names locally
if len(req.Question) == 1 && req.Question[0].Qtype == dns.TypeA {
hostname := dns.Fqdn(req.Question[0].Name)
if strings.Count(hostname, ".") == 1 {
d.handleLocal(defaultMaxResponseSize)(w, req)
return
}
}
for _, server := range d.upstream.Servers {
reqCopy := req.Copy()
reqCopy.Id = dns.Id()
response, _, err := client.Exchange(reqCopy, fmt.Sprintf("%s:%s", server, d.upstream.Port))
if err != nil || response == nil {
d.ns.debugf("error trying %s: %v", server, err)
continue
}
d.ns.debugf("response: %+v", response)
response.Id = req.Id
if err := w.WriteMsg(response); err != nil {
d.ns.infof("error responding: %v", err)
}
return
}
d.errorResponse(req, dns.RcodeServerFailure, w)
}
}
示例8: DirectedQuery
func DirectedQuery(servers []string, rd bool, q dns.Question, ctx context.Context) (*dns.Msg, error) {
cl := dns.Client{
Net: "tcp",
}
m := &dns.Msg{
MsgHdr: dns.MsgHdr{
Id: dns.Id(),
RecursionDesired: rd,
},
Compress: true,
Question: []dns.Question{q},
}
m = m.SetEdns0(4096, false)
type txResult struct {
Response *dns.Msg
Err error
}
maxTries := len(servers)
if maxTries < 3 {
maxTries = 3
}
var mainErr error
for i := 0; i < maxTries; i++ {
s := servers[i%len(servers)]
host, port, err := denet.FuzzySplitHostPort(s)
if err != nil {
return nil, err
}
if port == "" {
port = "53"
}
txResultChan := make(chan txResult, 1)
go func() {
r, _, err := cl.Exchange(m, net.JoinHostPort(host, port))
txResultChan <- txResult{r, err}
}()
select {
case <-ctx.Done():
return nil, ctx.Err()
case txResult := <-txResultChan:
if txResult.Err == nil {
return txResult.Response, nil
}
mainErr = txResult.Err
}
}
return nil, mainErr
}
示例9: ServeDNS
func (s *server) ServeDNS(w dns.ResponseWriter, req *dns.Msg) {
q := req.Question[0]
name := strings.ToLower(q.Name)
if q.Qtype == dns.TypeIXFR || q.Qtype == dns.TypeAXFR {
m := new(dns.Msg)
m.SetRcode(req, dns.RcodeNotImplemented)
w.WriteMsg(m)
return
}
allServers, err := s.router.Match(name)
if err != nil || len(allServers) == 0 {
m := new(dns.Msg)
m.SetRcode(req, dns.RcodeServerFailure)
w.WriteMsg(m)
return
}
serv := allServers[int(dns.Id())%len(allServers)]
log.Printf("routing %s to %s", name, serv)
c := new(dns.Client)
ret, _, err := c.Exchange(req, serv) // serv has the port
if err != nil {
m := new(dns.Msg)
m.SetRcode(req, dns.RcodeServerFailure)
w.WriteMsg(m)
return
}
w.WriteMsg(ret)
}
示例10: 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
}
示例11: 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
}
示例12: check
func check(c *dns.Client, m *dns.Msg, addr string) bool {
m.Id = dns.Id()
in, _, err := c.Exchange(m, addr)
if err != nil {
return false
}
if in.Rcode != dns.RcodeSuccess {
return false
}
return true
}
示例13: DnsGetDoaminIP
func DnsGetDoaminIP(domain string) (string, error) {
m := new(dns.Msg)
m.Id = dns.Id()
m.SetQuestion(dns.Fqdn(domain), dns.TypeA)
m.RecursionDesired = true
res, err := dnsQuery(m)
if nil != err {
return "", err
}
return pickIP(res), nil
}
示例14: Test
func (d *DnsDomain) Test() bool {
if !(*Domain)(d).Test() {
return false
}
fqdn := d.Name
if strings.HasPrefix(fqdn, "*.") {
fqdn = "a" + fqdn[1:]
}
if !strings.HasSuffix(fqdn, ".") {
fqdn = fqdn + "."
}
any_ok := false
d.DNS = make([]*DnsRecords, 0, len(DNS_servers))
for name, addr := range DNS_servers {
records := new(DnsRecords)
records.Server = name
records.NS = addr
d.DNS = append(d.DNS, records)
req := new(dns.Msg)
req.Id = dns.Id()
req.RecursionDesired = true
req.Question = []dns.Question{
dns.Question{fqdn, dns.TypeA, dns.ClassINET},
}
resp, err := dns_client.Exchange(req, addr)
if err != nil {
records.Status = 900
records.Message = err.Error()
continue
}
records.IPs = make([]string, 0, len(resp.Answer))
for _, rr := range resp.Answer {
switch a := rr.(type) {
case *dns.RR_A:
records.IPs = append(records.IPs, a.A.String())
}
}
if len(records.IPs) > 0 {
any_ok = true
} else {
records.Status = 900
records.Message = "No records"
}
}
return any_ok
}
示例15: roundRobin
func roundRobin(in []dns.RR) []dns.RR {
cname := []dns.RR{}
address := []dns.RR{}
rest := []dns.RR{}
for _, r := range in {
switch r.Header().Rrtype {
case dns.TypeCNAME:
cname = append(cname, r)
case dns.TypeA, dns.TypeAAAA:
address = append(address, r)
default:
rest = append(rest, r)
}
}
switch l := len(address); l {
case 0, 1:
break
case 2:
if dns.Id()%2 == 0 {
address[0], address[1] = address[1], address[0]
}
default:
for j := 0; j < l*(int(dns.Id())%4+1); j++ {
q := int(dns.Id()) % l
p := int(dns.Id()) % l
if q == p {
p = (p + 1) % l
}
address[q], address[p] = address[p], address[q]
}
}
out := append(cname, rest...)
out = append(out, address...)
return out
}