44 lines
670 B
Go
Raw Normal View History

2017-06-23 13:38:46 +00:00
package middleware
import (
"net"
"time"
2019-05-11 14:12:36 +00:00
"github.com/akyoto/cache"
2017-06-23 13:38:46 +00:00
)
2019-05-11 14:12:36 +00:00
var ipToHosts = cache.New(60 * time.Minute)
2017-06-23 13:38:46 +00:00
// GetHostsForIP returns all host names for the given IP (if cached).
2018-07-07 04:17:30 +00:00
func GetHostsForIP(ip string) ([]string, bool) {
2017-06-23 13:38:46 +00:00
hosts, found := ipToHosts.Get(ip)
2017-06-23 13:51:26 +00:00
if !found {
hosts = findHostsForIP(ip)
}
if hosts == nil {
2018-07-07 04:17:30 +00:00
return nil, found
2017-06-23 13:38:46 +00:00
}
2018-07-07 04:17:30 +00:00
return hosts.([]string), found
2017-06-23 13:38:46 +00:00
}
// Finds all host names for the given IP
2017-06-23 13:51:26 +00:00
func findHostsForIP(ip string) []string {
2017-06-23 13:38:46 +00:00
hosts, err := net.LookupAddr(ip)
if err != nil {
2017-06-23 13:51:26 +00:00
return nil
2017-06-23 13:38:46 +00:00
}
if len(hosts) == 0 {
2017-06-23 13:51:26 +00:00
return nil
2017-06-23 13:38:46 +00:00
}
// Cache host names
2019-05-11 14:12:36 +00:00
ipToHosts.Set(ip, hosts, 60*time.Minute)
2017-06-23 13:51:26 +00:00
return hosts
2017-06-23 13:38:46 +00:00
}