This repository has been archived on 2021-08-10. You can view files and clone it, but cannot push or open issues or pull requests.
gtools/nettools/net.go

83 lines
1.7 KiB
Go

package nettools
import (
"encoding/base64"
"encoding/hex"
"log"
"math/big"
"net"
"net/http"
"time"
"golang.org/x/net/proxy"
)
// BasicAuth encodes BasicAuth header
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]
}
// Proxy connect to proxy server using SOCKS5
func Proxy(network, address string, auth *proxy.Auth) (client *http.Client, err error) {
dialer, err := proxy.SOCKS5(network, address, auth, proxy.Direct)
if err != nil {
return nil, err
}
tr := &http.Transport{Dial: dialer.Dial}
return &http.Client{
Transport: tr,
Timeout: time.Second * 10,
}, nil
}