host.go 934 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package json
  2. import (
  3. "encoding/json"
  4. "net"
  5. v2net "github.com/v2ray/v2ray-core/common/net"
  6. )
  7. type Host struct {
  8. domain string
  9. ip net.IP
  10. }
  11. func NewIPHost(ip net.IP) *Host {
  12. return &Host{
  13. ip: ip,
  14. }
  15. }
  16. func NewDomainHost(domain string) *Host {
  17. return &Host{
  18. domain: domain,
  19. }
  20. }
  21. func (this *Host) UnmarshalJSON(data []byte) error {
  22. var rawStr string
  23. if err := json.Unmarshal(data, &rawStr); err != nil {
  24. return err
  25. }
  26. ip := net.ParseIP(rawStr)
  27. if ip != nil {
  28. this.ip = ip
  29. } else {
  30. this.domain = rawStr
  31. }
  32. return nil
  33. }
  34. func (this *Host) IsIP() bool {
  35. return this.ip != nil
  36. }
  37. func (this *Host) IsDomain() bool {
  38. return !this.IsIP()
  39. }
  40. func (this *Host) IP() net.IP {
  41. return this.ip
  42. }
  43. func (this *Host) Domain() string {
  44. return this.domain
  45. }
  46. func (this *Host) Address() v2net.Address {
  47. if this.IsIP() {
  48. return v2net.IPAddress(this.IP())
  49. } else {
  50. return v2net.DomainAddress(this.Domain())
  51. }
  52. }