66 lines
1.3 KiB
Go
66 lines
1.3 KiB
Go
package nettools
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"log"
|
|
"math/big"
|
|
"net"
|
|
"net/http"
|
|
)
|
|
|
|
func BasicAuth(username, password string) map[string]string {
|
|
return map[string]string{
|
|
"Authorization": "Basic " + base64.StdEncoding.EncodeToString([]byte(username+":"+password)),
|
|
}
|
|
}
|
|
|
|
// IP returns IP address from requester
|
|
func IP(r *http.Request) (net.IP, error) {
|
|
realip := r.Header.Get("x-forwarded-for")
|
|
if realip != "" {
|
|
return net.ParseIP(realip), nil
|
|
}
|
|
ip, _, err := net.SplitHostPort(r.RemoteAddr)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return net.ParseIP(ip), nil
|
|
}
|
|
|
|
// Inet6Aton Encodes ip address to hex
|
|
func Inet6Aton(ip net.IP) string {
|
|
ipv4 := false
|
|
if ip.To4() != nil {
|
|
ipv4 = true
|
|
}
|
|
ipInt := big.NewInt(0)
|
|
if ipv4 {
|
|
ipInt.SetBytes(ip.To4())
|
|
ipHex := hex.EncodeToString(ipInt.Bytes())
|
|
return ipHex
|
|
}
|
|
ipInt.SetBytes(ip.To16())
|
|
ipHex := hex.EncodeToString(ipInt.Bytes())
|
|
return ipHex
|
|
}
|
|
|
|
// Inet6AtonDecode decodes ip address from hex
|
|
func Inet6AtonDecode(ipHex string) (ip net.IP) {
|
|
hex, err := hex.DecodeString(ipHex)
|
|
if err != nil {
|
|
log.Println(err)
|
|
return net.ParseIP("0.0.0.0")
|
|
}
|
|
return net.IP(hex)
|
|
}
|
|
|
|
// Hostname returns hostname
|
|
func Hostname(ip net.IP) (hostname string) {
|
|
names, err := net.LookupAddr(ip.String())
|
|
if err != nil {
|
|
return "unknown host"
|
|
}
|
|
return names[0]
|
|
}
|