package ip

import (
	"errors"
	"net"
)

func GetInterfaceIP(iface_name string) (net.IP, error) {
	ip := net.IP{}
	iface, err := net.InterfaceByName(iface_name)
	if err != nil {
		return ip, err
	}

	addrs, err := iface.Addrs()
	if err != nil {
		return ip, err
	}

	return GetPublicIp(addrs)
}

func GetPublicIp(list []net.Addr) (net.IP, error) {
	for _, addr := range list {
		ip, err := AddrToIP(addr)
		if err == nil && !ip.IsPrivate() {
			return ip, nil
		}
	}

	return nil, errors.New("no public ip found on interface")
}

func AddrToIP(addr net.Addr) (net.IP, error) {
	switch v := addr.(type) {
	case *net.IPNet:
		return v.IP, nil
	case *net.IPAddr:
		return v.IP, nil
	case *net.UDPAddr:
		return v.IP, nil
	case *net.TCPAddr:
		return v.IP, nil
	}
	return nil, errors.New("could not find ip")
}
