interface.odin 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #+build windows, linux, darwin, freebsd
  2. package net
  3. /*
  4. Package net implements cross-platform Berkeley Sockets, DNS resolution and associated procedures.
  5. For other protocols and their features, see subdirectories of this package.
  6. */
  7. /*
  8. Copyright 2022 Tetralux <[email protected]>
  9. Copyright 2022 Colin Davidson <[email protected]>
  10. Copyright 2022 Jeroen van Rijn <[email protected]>.
  11. Copyright 2024 Feoramund <[email protected]>.
  12. Made available under Odin's BSD-3 license.
  13. List of contributors:
  14. Tetralux: Initial implementation
  15. Colin Davidson: Linux platform code, OSX platform code, Odin-native DNS resolver
  16. Jeroen van Rijn: Cross platform unification, code style, documentation
  17. Feoramund: FreeBSD platform code
  18. */
  19. import "core:strings"
  20. MAX_INTERFACE_ENUMERATION_TRIES :: 3
  21. /*
  22. `enumerate_interfaces` retrieves a list of network interfaces with their associated properties.
  23. */
  24. enumerate_interfaces :: proc(allocator := context.allocator) -> (interfaces: []Network_Interface, err: Network_Error) {
  25. return _enumerate_interfaces(allocator)
  26. }
  27. /*
  28. `destroy_interfaces` cleans up a list of network interfaces retrieved by e.g. `enumerate_interfaces`.
  29. */
  30. destroy_interfaces :: proc(interfaces: []Network_Interface, allocator := context.allocator) {
  31. context.allocator = allocator
  32. for i in interfaces {
  33. delete(i.adapter_name)
  34. delete(i.friendly_name)
  35. delete(i.description)
  36. delete(i.dns_suffix)
  37. delete(i.physical_address)
  38. delete(i.unicast)
  39. delete(i.multicast)
  40. delete(i.anycast)
  41. delete(i.gateways)
  42. }
  43. delete(interfaces, allocator)
  44. }
  45. /*
  46. Turns a slice of bytes (from e.g. `get_adapters_addresses`) into a "XX:XX:XX:..." string.
  47. */
  48. physical_address_to_string :: proc(phy_addr: []u8, allocator := context.allocator) -> (phy_string: string) {
  49. context.allocator = allocator
  50. MAC_HEX := "0123456789ABCDEF"
  51. if len(phy_addr) == 0 {
  52. return ""
  53. }
  54. buf: strings.Builder
  55. for b, i in phy_addr {
  56. if i > 0 {
  57. strings.write_rune(&buf, ':')
  58. }
  59. hi := rune(MAC_HEX[b >> 4])
  60. lo := rune(MAC_HEX[b & 15])
  61. strings.write_rune(&buf, hi)
  62. strings.write_rune(&buf, lo)
  63. }
  64. return strings.to_string(buf)
  65. }