Debian Codegraph @

dnsutil/response.go

raw
1 package dnsutil
2
3 import (
4 "net"
5 "net/netip"
6 "strconv"
7
8 "codeberg.org/miekg/dns"
9 )
10
11 // RemoteIP returns the IP address of the client making the request.
12 func RemoteIP(w dns.ResponseWriter) string {
13 switch t := w.RemoteAddr().(type) {
14 case *net.UDPAddr:
15 return t.IP.String()
16 case *net.TCPAddr:
17 return t.IP.String()
18 }
19 return ""
20 }
21
22 // LocalIP gets the IP address of server handling the request.
23 func LocalIP(w dns.ResponseWriter) string {
24 switch t := w.LocalAddr().(type) {
25 case *net.UDPAddr:
26 return t.IP.String()
27 case *net.TCPAddr:
28 return t.IP.String()
29 }
30 return ""
31 }
32
33 // RemotePort gets the port of the client making the request.
34 func RemotePort(w dns.ResponseWriter) string {
35 switch t := w.RemoteAddr().(type) {
36 case *net.UDPAddr:
37 return strconv.Itoa(t.Port)
38 case *net.TCPAddr:
39 return strconv.Itoa(t.Port)
40 }
41 return ""
42 }
43
44 // LocalPort gets the local port of the server handling the request.
45 func LocalPort(w dns.ResponseWriter) string {
46 switch t := w.LocalAddr().(type) {
47 case *net.UDPAddr:
48 return strconv.Itoa(t.Port)
49 case *net.TCPAddr:
50 return strconv.Itoa(t.Port)
51 }
52 return ""
53 }
54
55 // Network returns the network used to make the request, this can be udp or tcp.
56 func Network(w dns.ResponseWriter) string {
57 switch w.RemoteAddr().(type) {
58 case *net.UDPAddr:
59 return "udp"
60 case *net.TCPAddr:
61 return "tcp"
62 }
63 return "udp"
64 }
65
66 // Family returns the family of the transport, which is either [IPv4Family] or [IPv6Family] as defined by IANA.
67 func Family(w dns.ResponseWriter) int {
68 var a netip.Addr
69 switch t := w.RemoteAddr().(type) {
70 case *net.UDPAddr:
71 a = t.AddrPort().Addr()
72 case *net.TCPAddr:
73 a = t.AddrPort().Addr()
74 }
75
76 if a.Is4In6() {
77 return IPv4Family
78 }
79 if a.Is4() {
80 return IPv4Family
81 }
82 return IPv6Family
83 }
84
85 // The IP address families are defined by IANA, and can be found at https://www.iana.org/assignments/address-family-numbers/address-family-numbers.xhtml
86 const (
87 IPv4Family = 1
88 IPv6Family = 2
89 )