2022-03-08 14:58:41 +01:00
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
2022-03-14 11:40:23 +01:00
|
|
|
"errors"
|
2022-03-08 14:58:41 +01:00
|
|
|
"fmt"
|
|
|
|
"net"
|
2022-03-12 19:12:19 +01:00
|
|
|
"strings"
|
2022-03-08 14:58:41 +01:00
|
|
|
)
|
|
|
|
|
2022-03-12 19:12:19 +01:00
|
|
|
// NetworkLister List all network interface available
|
2022-03-08 14:58:41 +01:00
|
|
|
func NetworkLister() {
|
|
|
|
// Retrieve Interfaces
|
|
|
|
inter, err := net.Interfaces()
|
|
|
|
|
|
|
|
// Process errors
|
|
|
|
if err != nil {
|
|
|
|
println("[ERROR] An error occurred : " + err.Error())
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Display items
|
|
|
|
println("\n\nNetwork interface list :")
|
|
|
|
for i, val := range inter {
|
|
|
|
fmt.Printf("%d. %s\n", i, val.Name)
|
2022-03-12 20:36:12 +01:00
|
|
|
addrs, _ := val.Addrs()
|
|
|
|
for _, addr := range addrs {
|
|
|
|
println("-- ", addr.String())
|
|
|
|
}
|
2022-03-08 14:58:41 +01:00
|
|
|
}
|
|
|
|
print("\n")
|
|
|
|
}
|
2022-03-12 19:12:19 +01:00
|
|
|
|
2022-03-14 11:40:23 +01:00
|
|
|
// RetrieveIPv4FromInterface Retrieve the first IPv4 from an interface.
|
|
|
|
func RetrieveIPv4FromInterface(inter string) (net.IP, error) {
|
|
|
|
ief, err := net.InterfaceByName(inter)
|
|
|
|
addrs, err := ief.Addrs()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
for _, addr := range addrs {
|
|
|
|
switch v := addr.(type) {
|
|
|
|
case *net.IPNet:
|
|
|
|
//if !v.IP.IsLoopback() {
|
|
|
|
if v.IP.To4() != nil { //Verify if IP is IPV4
|
|
|
|
return v.IP, nil
|
|
|
|
}
|
|
|
|
//}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil, errors.New("no IPv4 found")
|
|
|
|
}
|
|
|
|
|
2022-03-12 19:12:19 +01:00
|
|
|
// IsIPv4 Check if the ip is a v4 or v6 ip
|
|
|
|
func IsIPv4(addr string) bool {
|
|
|
|
return strings.Count(addr, ":") < 2
|
|
|
|
}
|