server_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package dns_test
  2. import (
  3. "testing"
  4. "v2ray.com/core"
  5. "v2ray.com/core/app/dispatcher"
  6. . "v2ray.com/core/app/dns"
  7. "v2ray.com/core/app/policy"
  8. "v2ray.com/core/app/proxyman"
  9. _ "v2ray.com/core/app/proxyman/outbound"
  10. "v2ray.com/core/common/net"
  11. "v2ray.com/core/common/serial"
  12. "v2ray.com/core/proxy/freedom"
  13. "v2ray.com/core/testing/servers/udp"
  14. . "v2ray.com/ext/assert"
  15. "github.com/miekg/dns"
  16. )
  17. type staticHandler struct {
  18. }
  19. func (*staticHandler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) {
  20. ans := new(dns.Msg)
  21. ans.Id = r.Id
  22. for _, q := range r.Question {
  23. if q.Name == "google.com." && q.Qtype == dns.TypeA {
  24. rr, _ := dns.NewRR("google.com. IN A 8.8.8.8")
  25. ans.Answer = append(ans.Answer, rr)
  26. } else if q.Name == "facebook.com." && q.Qtype == dns.TypeA {
  27. rr, _ := dns.NewRR("facebook.com. IN A 9.9.9.9")
  28. ans.Answer = append(ans.Answer, rr)
  29. }
  30. }
  31. w.WriteMsg(ans)
  32. }
  33. func TestUDPServer(t *testing.T) {
  34. assert := With(t)
  35. port := udp.PickPort()
  36. dnsServer := dns.Server{
  37. Addr: "127.0.0.1:" + port.String(),
  38. Net: "udp",
  39. Handler: &staticHandler{},
  40. UDPSize: 1200,
  41. }
  42. go dnsServer.ListenAndServe()
  43. config := &core.Config{
  44. App: []*serial.TypedMessage{
  45. serial.ToTypedMessage(&Config{
  46. NameServers: []*net.Endpoint{
  47. {
  48. Network: net.Network_UDP,
  49. Address: &net.IPOrDomain{
  50. Address: &net.IPOrDomain_Ip{
  51. Ip: []byte{127, 0, 0, 1},
  52. },
  53. },
  54. Port: uint32(port),
  55. },
  56. },
  57. }),
  58. serial.ToTypedMessage(&dispatcher.Config{}),
  59. serial.ToTypedMessage(&proxyman.OutboundConfig{}),
  60. serial.ToTypedMessage(&policy.Config{}),
  61. },
  62. Outbound: []*core.OutboundHandlerConfig{
  63. {
  64. ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
  65. },
  66. },
  67. }
  68. v, err := core.New(config)
  69. assert(err, IsNil)
  70. client := v.DNSClient()
  71. ips, err := client.LookupIP("google.com")
  72. assert(err, IsNil)
  73. assert(len(ips), Equals, 1)
  74. assert([]byte(ips[0]), Equals, []byte{8, 8, 8, 8})
  75. ips, err = client.LookupIP("facebook.com")
  76. assert(err, IsNil)
  77. assert(len(ips), Equals, 1)
  78. assert([]byte(ips[0]), Equals, []byte{9, 9, 9, 9})
  79. dnsServer.Shutdown()
  80. ips, err = client.LookupIP("google.com")
  81. assert(err, IsNil)
  82. assert(len(ips), Equals, 1)
  83. assert([]byte(ips[0]), Equals, []byte{8, 8, 8, 8})
  84. }