package nettools
import (
"encoding/hex"
"log"
"math/big"
"net"
"net/http"
)
// 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())
// Inet6AtonDecode decodes ip address from hex
func Inet6AtonDecode(ipHex string) (ip net.IP) {
hex, err := hex.DecodeString(ipHex)
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())
return "unknown host"
return names[0]