ip_api.mx raw

   1  /*
   2  net.IP, net.IPMask and net.IPNet are named types with METHODS, and the address
   3  predicates hold through them.
   4  
   5  `type IP []byte` carries the method set (`String`, `To4`, `To16`, `Equal`,
   6  `IsUnspecified`, `IsLoopback`, `IsPrivate`, `IsMulticast`,
   7  `IsInterfaceLocalMulticast`, `IsLinkLocalMulticast`, `IsLinkLocalUnicast`,
   8  `IsGlobalUnicast`, `DefaultMask`, `ApplyMask`, `AppendText`, `MarshalText`,
   9  `UnmarshalText`); `IPMask` carries `Size` and `String`; `IPNet` carries
  10  `Contains`, `Network` and `String`. This fixture used to call free functions
  11  (`net.IPString`, `net.IPEqual`, ...) from the intermediate alias form; those
  12  are gone, and a call to one is exactly what this file exists to catch.
  13  
  14  The fixture is end-to-end on purpose: the compiler checks the MAIN package's
  15  bodies thoroughly but tolerates an unresolved call in a dependency's body, so a
  16  dependency-only check would not prove the methods exist. This calls them and
  17  checks the values, including the 4-byte/16-byte form equivalence that Equal
  18  normalizes and IPNet.Contains' use of the mask.
  19  */
  20  package main
  21  
  22  import (
  23  	"net"
  24  )
  25  
  26  func main() {
  27  	// Termination: a batch program must still be stoppable, so the entry
  28  	// handles the channel the runtime closes on SIGINT/SIGTERM.
  29  	select {
  30  	case <-shutdown:
  31  		return
  32  	default:
  33  	}
  34  
  35  	ip := net.ParseIP("192.168.1.5")
  36  	if ip == nil {
  37  		panic("parse")
  38  	}
  39  	if ip.String() != "192.168.1.5" {
  40  		panic("string: " | ip.String())
  41  	}
  42  	if ip.IsUnspecified() {
  43  		panic("unspecified")
  44  	}
  45  	if !ip.IsPrivate() {
  46  		panic("private")
  47  	}
  48  	if ip.IsLoopback() {
  49  		panic("loopback")
  50  	}
  51  	ip4 := ip.To4()
  52  	if ip4 == nil || len(ip4) != 4 {
  53  		panic("to4")
  54  	}
  55  	ip16 := ip.To16()
  56  	if ip16 == nil || len(ip16) != 16 {
  57  		panic("to16")
  58  	}
  59  	if !ip.Equal(ip16) {
  60  		panic("equal across 4 and 16 byte forms")
  61  	}
  62  	if !net.ParseIP("127.0.0.1").IsLoopback() {
  63  		panic("loopback 127.0.0.1")
  64  	}
  65  	m := net.CIDRMask(24, 32)
  66  	ones, bits := m.Size()
  67  	if ones != 24 || bits != 32 {
  68  		panic("mask size")
  69  	}
  70  	n := &net.IPNet{IP: ip, Mask: m}
  71  	if !n.Contains(net.ParseIP("192.168.1.99")) {
  72  		panic("contains in-net")
  73  	}
  74  	if n.Contains(net.ParseIP("10.0.0.1")) {
  75  		panic("contains out-of-net")
  76  	}
  77  	println("ip ok")
  78  }
  79