44 lines
670 B
Go
Raw Normal View History

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