amuz.es/src/go/misc@v1.0.1/networking/ip.go (about)

     1  package networking
     2  
     3  import (
     4  	"net"
     5  )
     6  
     7  // Bigger than we need, not too big to worry about overflow
     8  const big = 0x100
     9  
    10  // Parse IPv4 address (d.d.d.d).
    11  func ParseIPv4(s []byte) net.IP {
    12  	var p [net.IPv4len]byte
    13  	for i := 0; i < net.IPv4len; i++ {
    14  		if len(s) == 0 {
    15  			// Missing octets.
    16  			return nil
    17  		}
    18  
    19  		if i > 0 {
    20  			if s[0] != '.' {
    21  				return nil
    22  			}
    23  			s = s[1:]
    24  		}
    25  
    26  		n, c, ok := dtoi(s)
    27  		if !ok {
    28  			return nil
    29  		}
    30  		if c > 1 && s[0] == '0' {
    31  			// Reject non-zero components with leading zeroes.
    32  			return nil
    33  		}
    34  		s = s[c:]
    35  		p[i] = byte(n)
    36  	}
    37  	if len(s) != 0 {
    38  		return nil
    39  	}
    40  	return net.IPv4(p[0], p[1], p[2], p[3])
    41  }
    42  
    43  // Decimal to integer.
    44  // Returns number, characters consumed, success.
    45  func dtoi(s []byte) (n int, i int, ok bool) {
    46  	n = 0
    47  	for i = 0; i < len(s) && '0' <= s[i] && s[i] <= '9'; i++ {
    48  		n = n*10 + int(s[i]-'0')
    49  		if n >= big {
    50  			return big, i, false
    51  		}
    52  	}
    53  	if i == 0 {
    54  		return 0, 0, false
    55  	}
    56  	return n, i, true
    57  }