local.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package scan
  2. import (
  3. "fmt"
  4. "log"
  5. "net"
  6. "net/netip"
  7. "strings"
  8. )
  9. type AllAddress struct {
  10. Addr []net.IP `json:"addresses"`
  11. }
  12. type NetworkInterfaceNotFound struct {Passed string}
  13. // Implementing error interface
  14. func (n *NetworkInterfaceNotFound) Error() string {
  15. return fmt.Sprintf("Interface: '%s' not found.", n.Passed)
  16. }
  17. /*
  18. Recursive function to get all of the IPv4 addresses for each IPv4 network that the host is on
  19. :param addr: the address to recursively find the next address for
  20. :param out: a pointer to a struct containing a list of addresses
  21. */
  22. func addressRecurse(addr netip.Addr, out *AllAddress) {
  23. ref := net.ParseIP(addr.String())
  24. next := net.ParseIP(addr.Next().String())
  25. v, err := netip.ParseAddr(next.String())
  26. if err != nil {
  27. log.Fatal(err)
  28. }
  29. if ref.Mask(ref.DefaultMask()).String() == next.Mask(next.DefaultMask()).String() {
  30. out.Addr = append(out.Addr, next)
  31. addressRecurse(v, out)
  32. }
  33. }
  34. /*
  35. Retrieve the address of a specific interface
  36. :param name: the name of the interface to get the address of
  37. */
  38. func getAddressByInterface(name string) ([]net.Addr, error) {
  39. interfaces, err := net.Interfaces()
  40. if err != nil {
  41. return nil, err
  42. }
  43. for idx := range interfaces {
  44. if interfaces[idx].Name == name {
  45. return interfaces[idx].Addrs()
  46. }
  47. }
  48. return nil, &NetworkInterfaceNotFound{Passed: name}
  49. }
  50. /*
  51. Utilized a recursive function to find all addresses in the address space that the host belongs.
  52. Returns a pointer to an AllAddresses struct who has a list of net.IP structs inside
  53. */
  54. func GetAllAddresses(name string) (*AllAddress, error){
  55. addresses, err := getAddressByInterface(name)
  56. if err != nil {
  57. return nil, err
  58. }
  59. out := &AllAddress{}
  60. for idx := range addresses {
  61. ip := net.ParseIP(strings.Split(addresses[idx].String(), "/")[0])
  62. root, err := netip.ParseAddr(ip.Mask(ip.DefaultMask()).String())
  63. if err != nil {
  64. continue
  65. }
  66. if root.IsLoopback() {
  67. continue
  68. }
  69. addressRecurse(root, out)
  70. }
  71. return out, nil
  72. }