ipv4addr.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. package sockaddr
  2. import (
  3. "encoding/binary"
  4. "fmt"
  5. "net"
  6. "regexp"
  7. "strconv"
  8. "strings"
  9. )
  10. type (
  11. // IPv4Address is a named type representing an IPv4 address.
  12. IPv4Address uint32
  13. // IPv4Network is a named type representing an IPv4 network.
  14. IPv4Network uint32
  15. // IPv4Mask is a named type representing an IPv4 network mask.
  16. IPv4Mask uint32
  17. )
  18. // IPv4HostMask is a constant represents a /32 IPv4 Address
  19. // (i.e. 255.255.255.255).
  20. const IPv4HostMask = IPv4Mask(0xffffffff)
  21. // ipv4AddrAttrMap is a map of the IPv4Addr type-specific attributes.
  22. var ipv4AddrAttrMap map[AttrName]func(IPv4Addr) string
  23. var ipv4AddrAttrs []AttrName
  24. var trailingHexNetmaskRE *regexp.Regexp
  25. // IPv4Addr implements a convenience wrapper around the union of Go's
  26. // built-in net.IP and net.IPNet types. In UNIX-speak, IPv4Addr implements
  27. // `sockaddr` when the the address family is set to AF_INET
  28. // (i.e. `sockaddr_in`).
  29. type IPv4Addr struct {
  30. IPAddr
  31. Address IPv4Address
  32. Mask IPv4Mask
  33. Port IPPort
  34. }
  35. func init() {
  36. ipv4AddrInit()
  37. trailingHexNetmaskRE = regexp.MustCompile(`/([0f]{8})$`)
  38. }
  39. // NewIPv4Addr creates an IPv4Addr from a string. String can be in the form
  40. // of either an IPv4:port (e.g. `1.2.3.4:80`, in which case the mask is
  41. // assumed to be a `/32`), an IPv4 address (e.g. `1.2.3.4`, also with a `/32`
  42. // mask), or an IPv4 CIDR (e.g. `1.2.3.4/24`, which has its IP port
  43. // initialized to zero). ipv4Str can not be a hostname.
  44. //
  45. // NOTE: Many net.*() routines will initialize and return an IPv6 address.
  46. // To create uint32 values from net.IP, always test to make sure the address
  47. // returned can be converted to a 4 byte array using To4().
  48. func NewIPv4Addr(ipv4Str string) (IPv4Addr, error) {
  49. // Strip off any bogus hex-encoded netmasks that will be mis-parsed by Go. In
  50. // particular, clients with the Barracuda VPN client will see something like:
  51. // `192.168.3.51/00ffffff` as their IP address.
  52. if match := trailingHexNetmaskRE.FindStringIndex(ipv4Str); match != nil {
  53. ipv4Str = ipv4Str[:match[0]]
  54. }
  55. // Parse as an IPv4 CIDR
  56. ipAddr, network, err := net.ParseCIDR(ipv4Str)
  57. if err == nil {
  58. ipv4 := ipAddr.To4()
  59. if ipv4 == nil {
  60. return IPv4Addr{}, fmt.Errorf("Unable to convert %s to an IPv4 address", ipv4Str)
  61. }
  62. // If we see an IPv6 netmask, convert it to an IPv4 mask.
  63. netmaskSepPos := strings.LastIndexByte(ipv4Str, '/')
  64. if netmaskSepPos != -1 && netmaskSepPos+1 < len(ipv4Str) {
  65. netMask, err := strconv.ParseUint(ipv4Str[netmaskSepPos+1:], 10, 8)
  66. if err != nil {
  67. return IPv4Addr{}, fmt.Errorf("Unable to convert %s to an IPv4 address: unable to parse CIDR netmask: %v", ipv4Str, err)
  68. } else if netMask > 128 {
  69. return IPv4Addr{}, fmt.Errorf("Unable to convert %s to an IPv4 address: invalid CIDR netmask", ipv4Str)
  70. }
  71. if netMask >= 96 {
  72. // Convert the IPv6 netmask to an IPv4 netmask
  73. network.Mask = net.CIDRMask(int(netMask-96), IPv4len*8)
  74. }
  75. }
  76. ipv4Addr := IPv4Addr{
  77. Address: IPv4Address(binary.BigEndian.Uint32(ipv4)),
  78. Mask: IPv4Mask(binary.BigEndian.Uint32(network.Mask)),
  79. }
  80. return ipv4Addr, nil
  81. }
  82. // Attempt to parse ipv4Str as a /32 host with a port number.
  83. tcpAddr, err := net.ResolveTCPAddr("tcp4", ipv4Str)
  84. if err == nil {
  85. ipv4 := tcpAddr.IP.To4()
  86. if ipv4 == nil {
  87. return IPv4Addr{}, fmt.Errorf("Unable to resolve %+q as an IPv4 address", ipv4Str)
  88. }
  89. ipv4Uint32 := binary.BigEndian.Uint32(ipv4)
  90. ipv4Addr := IPv4Addr{
  91. Address: IPv4Address(ipv4Uint32),
  92. Mask: IPv4HostMask,
  93. Port: IPPort(tcpAddr.Port),
  94. }
  95. return ipv4Addr, nil
  96. }
  97. // Parse as a naked IPv4 address
  98. ip := net.ParseIP(ipv4Str)
  99. if ip != nil {
  100. ipv4 := ip.To4()
  101. if ipv4 == nil {
  102. return IPv4Addr{}, fmt.Errorf("Unable to string convert %+q to an IPv4 address", ipv4Str)
  103. }
  104. ipv4Uint32 := binary.BigEndian.Uint32(ipv4)
  105. ipv4Addr := IPv4Addr{
  106. Address: IPv4Address(ipv4Uint32),
  107. Mask: IPv4HostMask,
  108. }
  109. return ipv4Addr, nil
  110. }
  111. return IPv4Addr{}, fmt.Errorf("Unable to parse %+q to an IPv4 address: %v", ipv4Str, err)
  112. }
  113. // AddressBinString returns a string with the IPv4Addr's Address represented
  114. // as a sequence of '0' and '1' characters. This method is useful for
  115. // debugging or by operators who want to inspect an address.
  116. func (ipv4 IPv4Addr) AddressBinString() string {
  117. return fmt.Sprintf("%032s", strconv.FormatUint(uint64(ipv4.Address), 2))
  118. }
  119. // AddressHexString returns a string with the IPv4Addr address represented as
  120. // a sequence of hex characters. This method is useful for debugging or by
  121. // operators who want to inspect an address.
  122. func (ipv4 IPv4Addr) AddressHexString() string {
  123. return fmt.Sprintf("%08s", strconv.FormatUint(uint64(ipv4.Address), 16))
  124. }
  125. // Broadcast is an IPv4Addr-only method that returns the broadcast address of
  126. // the network.
  127. //
  128. // NOTE: IPv6 only supports multicast, so this method only exists for
  129. // IPv4Addr.
  130. func (ipv4 IPv4Addr) Broadcast() IPAddr {
  131. // Nothing should listen on a broadcast address.
  132. return IPv4Addr{
  133. Address: IPv4Address(ipv4.BroadcastAddress()),
  134. Mask: IPv4HostMask,
  135. }
  136. }
  137. // BroadcastAddress returns a IPv4Network of the IPv4Addr's broadcast
  138. // address.
  139. func (ipv4 IPv4Addr) BroadcastAddress() IPv4Network {
  140. return IPv4Network(uint32(ipv4.Address)&uint32(ipv4.Mask) | ^uint32(ipv4.Mask))
  141. }
  142. // CmpAddress follows the Cmp() standard protocol and returns:
  143. //
  144. // - -1 If the receiver should sort first because its address is lower than arg
  145. // - 0 if the SockAddr arg is equal to the receiving IPv4Addr or the argument is
  146. // of a different type.
  147. // - 1 If the argument should sort first.
  148. func (ipv4 IPv4Addr) CmpAddress(sa SockAddr) int {
  149. ipv4b, ok := sa.(IPv4Addr)
  150. if !ok {
  151. return sortDeferDecision
  152. }
  153. switch {
  154. case ipv4.Address == ipv4b.Address:
  155. return sortDeferDecision
  156. case ipv4.Address < ipv4b.Address:
  157. return sortReceiverBeforeArg
  158. default:
  159. return sortArgBeforeReceiver
  160. }
  161. }
  162. // CmpPort follows the Cmp() standard protocol and returns:
  163. //
  164. // - -1 If the receiver should sort first because its port is lower than arg
  165. // - 0 if the SockAddr arg's port number is equal to the receiving IPv4Addr,
  166. // regardless of type.
  167. // - 1 If the argument should sort first.
  168. func (ipv4 IPv4Addr) CmpPort(sa SockAddr) int {
  169. var saPort IPPort
  170. switch v := sa.(type) {
  171. case IPv4Addr:
  172. saPort = v.Port
  173. case IPv6Addr:
  174. saPort = v.Port
  175. default:
  176. return sortDeferDecision
  177. }
  178. switch {
  179. case ipv4.Port == saPort:
  180. return sortDeferDecision
  181. case ipv4.Port < saPort:
  182. return sortReceiverBeforeArg
  183. default:
  184. return sortArgBeforeReceiver
  185. }
  186. }
  187. // CmpRFC follows the Cmp() standard protocol and returns:
  188. //
  189. // - -1 If the receiver should sort first because it belongs to the RFC and its
  190. // arg does not
  191. // - 0 if the receiver and arg both belong to the same RFC or neither do.
  192. // - 1 If the arg belongs to the RFC but receiver does not.
  193. func (ipv4 IPv4Addr) CmpRFC(rfcNum uint, sa SockAddr) int {
  194. recvInRFC := IsRFC(rfcNum, ipv4)
  195. ipv4b, ok := sa.(IPv4Addr)
  196. if !ok {
  197. // If the receiver is part of the desired RFC and the SockAddr
  198. // argument is not, return -1 so that the receiver sorts before
  199. // the non-IPv4 SockAddr. Conversely, if the receiver is not
  200. // part of the RFC, punt on sorting and leave it for the next
  201. // sorter.
  202. if recvInRFC {
  203. return sortReceiverBeforeArg
  204. } else {
  205. return sortDeferDecision
  206. }
  207. }
  208. argInRFC := IsRFC(rfcNum, ipv4b)
  209. switch {
  210. case (recvInRFC && argInRFC), (!recvInRFC && !argInRFC):
  211. // If a and b both belong to the RFC, or neither belong to
  212. // rfcNum, defer sorting to the next sorter.
  213. return sortDeferDecision
  214. case recvInRFC && !argInRFC:
  215. return sortReceiverBeforeArg
  216. default:
  217. return sortArgBeforeReceiver
  218. }
  219. }
  220. // Contains returns true if the SockAddr is contained within the receiver.
  221. func (ipv4 IPv4Addr) Contains(sa SockAddr) bool {
  222. ipv4b, ok := sa.(IPv4Addr)
  223. if !ok {
  224. return false
  225. }
  226. return ipv4.ContainsNetwork(ipv4b)
  227. }
  228. // ContainsAddress returns true if the IPv4Address is contained within the
  229. // receiver.
  230. func (ipv4 IPv4Addr) ContainsAddress(x IPv4Address) bool {
  231. return IPv4Address(ipv4.NetworkAddress()) <= x &&
  232. IPv4Address(ipv4.BroadcastAddress()) >= x
  233. }
  234. // ContainsNetwork returns true if the network from IPv4Addr is contained
  235. // within the receiver.
  236. func (ipv4 IPv4Addr) ContainsNetwork(x IPv4Addr) bool {
  237. return ipv4.NetworkAddress() <= x.NetworkAddress() &&
  238. ipv4.BroadcastAddress() >= x.BroadcastAddress()
  239. }
  240. // DialPacketArgs returns the arguments required to be passed to
  241. // net.DialUDP(). If the Mask of ipv4 is not a /32 or the Port is 0,
  242. // DialPacketArgs() will fail. See Host() to create an IPv4Addr with its
  243. // mask set to /32.
  244. func (ipv4 IPv4Addr) DialPacketArgs() (network, dialArgs string) {
  245. if ipv4.Mask != IPv4HostMask || ipv4.Port == 0 {
  246. return "udp4", ""
  247. }
  248. return "udp4", fmt.Sprintf("%s:%d", ipv4.NetIP().String(), ipv4.Port)
  249. }
  250. // DialStreamArgs returns the arguments required to be passed to
  251. // net.DialTCP(). If the Mask of ipv4 is not a /32 or the Port is 0,
  252. // DialStreamArgs() will fail. See Host() to create an IPv4Addr with its
  253. // mask set to /32.
  254. func (ipv4 IPv4Addr) DialStreamArgs() (network, dialArgs string) {
  255. if ipv4.Mask != IPv4HostMask || ipv4.Port == 0 {
  256. return "tcp4", ""
  257. }
  258. return "tcp4", fmt.Sprintf("%s:%d", ipv4.NetIP().String(), ipv4.Port)
  259. }
  260. // Equal returns true if a SockAddr is equal to the receiving IPv4Addr.
  261. func (ipv4 IPv4Addr) Equal(sa SockAddr) bool {
  262. ipv4b, ok := sa.(IPv4Addr)
  263. if !ok {
  264. return false
  265. }
  266. if ipv4.Port != ipv4b.Port {
  267. return false
  268. }
  269. if ipv4.Address != ipv4b.Address {
  270. return false
  271. }
  272. if ipv4.NetIPNet().String() != ipv4b.NetIPNet().String() {
  273. return false
  274. }
  275. return true
  276. }
  277. // FirstUsable returns an IPv4Addr set to the first address following the
  278. // network prefix. The first usable address in a network is normally the
  279. // gateway and should not be used except by devices forwarding packets
  280. // between two administratively distinct networks (i.e. a router). This
  281. // function does not discriminate against first usable vs "first address that
  282. // should be used." For example, FirstUsable() on "192.168.1.10/24" would
  283. // return the address "192.168.1.1/24".
  284. func (ipv4 IPv4Addr) FirstUsable() IPAddr {
  285. addr := ipv4.NetworkAddress()
  286. // If /32, return the address itself. If /31 assume a point-to-point
  287. // link and return the lower address.
  288. if ipv4.Maskbits() < 31 {
  289. addr++
  290. }
  291. return IPv4Addr{
  292. Address: IPv4Address(addr),
  293. Mask: IPv4HostMask,
  294. }
  295. }
  296. // Host returns a copy of ipv4 with its mask set to /32 so that it can be
  297. // used by DialPacketArgs(), DialStreamArgs(), ListenPacketArgs(), or
  298. // ListenStreamArgs().
  299. func (ipv4 IPv4Addr) Host() IPAddr {
  300. // Nothing should listen on a broadcast address.
  301. return IPv4Addr{
  302. Address: ipv4.Address,
  303. Mask: IPv4HostMask,
  304. Port: ipv4.Port,
  305. }
  306. }
  307. // IPPort returns the Port number attached to the IPv4Addr
  308. func (ipv4 IPv4Addr) IPPort() IPPort {
  309. return ipv4.Port
  310. }
  311. // LastUsable returns the last address before the broadcast address in a
  312. // given network.
  313. func (ipv4 IPv4Addr) LastUsable() IPAddr {
  314. addr := ipv4.BroadcastAddress()
  315. // If /32, return the address itself. If /31 assume a point-to-point
  316. // link and return the upper address.
  317. if ipv4.Maskbits() < 31 {
  318. addr--
  319. }
  320. return IPv4Addr{
  321. Address: IPv4Address(addr),
  322. Mask: IPv4HostMask,
  323. }
  324. }
  325. // ListenPacketArgs returns the arguments required to be passed to
  326. // net.ListenUDP(). If the Mask of ipv4 is not a /32, ListenPacketArgs()
  327. // will fail. See Host() to create an IPv4Addr with its mask set to /32.
  328. func (ipv4 IPv4Addr) ListenPacketArgs() (network, listenArgs string) {
  329. if ipv4.Mask != IPv4HostMask {
  330. return "udp4", ""
  331. }
  332. return "udp4", fmt.Sprintf("%s:%d", ipv4.NetIP().String(), ipv4.Port)
  333. }
  334. // ListenStreamArgs returns the arguments required to be passed to
  335. // net.ListenTCP(). If the Mask of ipv4 is not a /32, ListenStreamArgs()
  336. // will fail. See Host() to create an IPv4Addr with its mask set to /32.
  337. func (ipv4 IPv4Addr) ListenStreamArgs() (network, listenArgs string) {
  338. if ipv4.Mask != IPv4HostMask {
  339. return "tcp4", ""
  340. }
  341. return "tcp4", fmt.Sprintf("%s:%d", ipv4.NetIP().String(), ipv4.Port)
  342. }
  343. // Maskbits returns the number of network mask bits in a given IPv4Addr. For
  344. // example, the Maskbits() of "192.168.1.1/24" would return 24.
  345. func (ipv4 IPv4Addr) Maskbits() int {
  346. mask := make(net.IPMask, IPv4len)
  347. binary.BigEndian.PutUint32(mask, uint32(ipv4.Mask))
  348. maskOnes, _ := mask.Size()
  349. return maskOnes
  350. }
  351. // MustIPv4Addr is a helper method that must return an IPv4Addr or panic on
  352. // invalid input.
  353. func MustIPv4Addr(addr string) IPv4Addr {
  354. ipv4, err := NewIPv4Addr(addr)
  355. if err != nil {
  356. panic(fmt.Sprintf("Unable to create an IPv4Addr from %+q: %v", addr, err))
  357. }
  358. return ipv4
  359. }
  360. // NetIP returns the address as a net.IP (address is always presized to
  361. // IPv4).
  362. func (ipv4 IPv4Addr) NetIP() *net.IP {
  363. x := make(net.IP, IPv4len)
  364. binary.BigEndian.PutUint32(x, uint32(ipv4.Address))
  365. return &x
  366. }
  367. // NetIPMask create a new net.IPMask from the IPv4Addr.
  368. func (ipv4 IPv4Addr) NetIPMask() *net.IPMask {
  369. ipv4Mask := net.IPMask{}
  370. ipv4Mask = make(net.IPMask, IPv4len)
  371. binary.BigEndian.PutUint32(ipv4Mask, uint32(ipv4.Mask))
  372. return &ipv4Mask
  373. }
  374. // NetIPNet create a new net.IPNet from the IPv4Addr.
  375. func (ipv4 IPv4Addr) NetIPNet() *net.IPNet {
  376. ipv4net := &net.IPNet{}
  377. ipv4net.IP = make(net.IP, IPv4len)
  378. binary.BigEndian.PutUint32(ipv4net.IP, uint32(ipv4.NetworkAddress()))
  379. ipv4net.Mask = *ipv4.NetIPMask()
  380. return ipv4net
  381. }
  382. // Network returns the network prefix or network address for a given network.
  383. func (ipv4 IPv4Addr) Network() IPAddr {
  384. return IPv4Addr{
  385. Address: IPv4Address(ipv4.NetworkAddress()),
  386. Mask: ipv4.Mask,
  387. }
  388. }
  389. // NetworkAddress returns an IPv4Network of the IPv4Addr's network address.
  390. func (ipv4 IPv4Addr) NetworkAddress() IPv4Network {
  391. return IPv4Network(uint32(ipv4.Address) & uint32(ipv4.Mask))
  392. }
  393. // Octets returns a slice of the four octets in an IPv4Addr's Address. The
  394. // order of the bytes is big endian.
  395. func (ipv4 IPv4Addr) Octets() []int {
  396. return []int{
  397. int(ipv4.Address >> 24),
  398. int((ipv4.Address >> 16) & 0xff),
  399. int((ipv4.Address >> 8) & 0xff),
  400. int(ipv4.Address & 0xff),
  401. }
  402. }
  403. // String returns a string representation of the IPv4Addr
  404. func (ipv4 IPv4Addr) String() string {
  405. if ipv4.Port != 0 {
  406. return fmt.Sprintf("%s:%d", ipv4.NetIP().String(), ipv4.Port)
  407. }
  408. if ipv4.Maskbits() == 32 {
  409. return ipv4.NetIP().String()
  410. }
  411. return fmt.Sprintf("%s/%d", ipv4.NetIP().String(), ipv4.Maskbits())
  412. }
  413. // Type is used as a type switch and returns TypeIPv4
  414. func (IPv4Addr) Type() SockAddrType {
  415. return TypeIPv4
  416. }
  417. // IPv4AddrAttr returns a string representation of an attribute for the given
  418. // IPv4Addr.
  419. func IPv4AddrAttr(ipv4 IPv4Addr, selector AttrName) string {
  420. fn, found := ipv4AddrAttrMap[selector]
  421. if !found {
  422. return ""
  423. }
  424. return fn(ipv4)
  425. }
  426. // IPv4Attrs returns a list of attributes supported by the IPv4Addr type
  427. func IPv4Attrs() []AttrName {
  428. return ipv4AddrAttrs
  429. }
  430. // ipv4AddrInit is called once at init()
  431. func ipv4AddrInit() {
  432. // Sorted for human readability
  433. ipv4AddrAttrs = []AttrName{
  434. "size", // Same position as in IPv6 for output consistency
  435. "broadcast",
  436. "uint32",
  437. }
  438. ipv4AddrAttrMap = map[AttrName]func(ipv4 IPv4Addr) string{
  439. "broadcast": func(ipv4 IPv4Addr) string {
  440. return ipv4.Broadcast().String()
  441. },
  442. "size": func(ipv4 IPv4Addr) string {
  443. return fmt.Sprintf("%d", 1<<uint(IPv4len*8-ipv4.Maskbits()))
  444. },
  445. "uint32": func(ipv4 IPv4Addr) string {
  446. return fmt.Sprintf("%d", uint32(ipv4.Address))
  447. },
  448. }
  449. }