Browse Source

init

master v0.1.0
guzeng 3 years ago
parent
commit
894062c641
10 changed files with 760 additions and 0 deletions
  1. +86
    -0
      http.go
  2. +52
    -0
      http_test.go
  3. +210
    -0
      ip.go
  4. +50
    -0
      ip_test.go
  5. +46
    -0
      ping.go
  6. +21
    -0
      ping_test.go
  7. +91
    -0
      port.go
  8. +16
    -0
      port_test.go
  9. +166
    -0
      url.go
  10. +22
    -0
      url_test.go

+ 86
- 0
http.go View File

@ -0,0 +1,86 @@
package network
import (
"io/ioutil"
"net/http"
"strings"
)
/**
* 自定义HTTP请求
*/
func MethodHttp(method, url, param string, header ...map[string]string) ([]byte, error) {
httpClient := &http.Client{}
req, err := http.NewRequest(method, url, strings.NewReader(param))
if err != nil {
return []byte(""), err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if len(header) > 0 {
for _, item := range header {
for k, v := range item {
req.Header.Set(k, v)
}
}
}
resp, err := httpClient.Do(req)
if err != nil {
return []byte(""), err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return []byte(""), err
}
return body, nil
}
/**
* 自定义HTTP请求
*/
func SendHttp(method, url string, param map[string]string, header ...map[string]string) ([]byte, error) {
httpClient := &http.Client{}
paramStr := ""
if len(param) > 0 {
for key, value := range param {
paramStr += key + "=" + value + "&"
}
paramStr = paramStr[0 : len(paramStr)-1]
}
req, err := http.NewRequest(method, url, strings.NewReader(paramStr))
if err != nil {
return []byte(""), err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if len(header) > 0 {
for _, item := range header {
for k, v := range item {
req.Header.Set(k, v)
}
}
}
resp, err := httpClient.Do(req)
if err != nil {
return []byte(""), err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return []byte(""), err
}
return body, nil
}

+ 52
- 0
http_test.go View File

@ -0,0 +1,52 @@
package network
import (
"fmt"
"net/url"
"testing"
)
func Test_MethodHttp(t *testing.T) {
uri := "http://Controller_Ip/SaaS/nextcloud/remote.php/webdav"
u, err := url.Parse(uri)
fmt.Println(u, err)
fmt.Println(u.Scheme, u.Host, u.Path, u.Fragment, u.RawQuery)
// url := "http://admin:123456@10.0.66.29/SaaS/nextcloud/remote.php/dav/files/admin/CZNTQK2"
// data, err := MethodHttp("DELETE", url, "")
// t.Log(string(data), err)
// url := "http://admin:123456@10.0.66.29/nextcloud/index.php/apps/files/ajax/getstoragestats.php?dir=/"
// data, err := MethodHttp("GET", url, "")
// t.Log(string(data))
// t.Log(err)
// url = "http://admin:123456@10.0.66.29/nextcloud/remote.php/dav/files/admin/"
// data, err = MethodHttp("PROPFIND", url, "")
// t.Log(string(data))
// t.Log(err)
// url = "http://admin:123456@10.0.66.29/nextcloud/index.php/settings/ajax/setquota.php"
// args := "username=admin&quota=30GB&norequesttoken=true"
// data, err = MethodHttp("POST", url, args)
// t.Log(string(data))
// t.Log(err)
// url = "http://admin:123456@10.0.66.29/nextcloud/index.php/apps/files/ajax/list.php?dir=/Photos"
// data, err = MethodHttp("GET", url, "")
// t.Log(string(data))
// t.Log(err)
// url = "http://" + "raydesktop.gxycloud.com" + ":" + "8082" + "/extranet"
// args = "key=DBKHPW39"
// data, err = MethodHttp("POST", url, args)
// t.Log(string(data))
// t.Log(err)
// url = "http://admin:123456@10.0.66.29/nextcloud/remote.php/dav/files/admin/ncikZ0fxX1gy5qV2018012504/7b531e26d2dee30271"
// data, err = MethodHttp("MKCOL", url, "")
// t.Log(string(data))
// t.Log(err)
}

+ 210
- 0
ip.go View File

@ -0,0 +1,210 @@
package network
import (
"errors"
"net"
"net/http"
"strconv"
"strings"
)
/**
* 取本地IP
*/
func GetLocalIps() []string {
addrs, err := net.InterfaceAddrs()
var list []string
if err != nil {
return list
}
for _, address := range addrs {
// 检查ip地址判断是否回环地址
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil && !ipnet.IP.IsLinkLocalUnicast() {
if IsPrivateIp(ipnet.IP.String()) {
list = append(list, ipnet.IP.String())
}
}
}
}
return list
}
/**
* 取外网IP
*/
func GetInternetIps() []string {
addrs, err := net.InterfaceAddrs()
var list []string
if err != nil {
return list
}
for _, address := range addrs {
// 检查ip地址判断是否回环地址
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil && !ipnet.IP.IsLinkLocalUnicast() {
if !IsPrivateIp(ipnet.IP.String()) {
list = append(list, ipnet.IP.String())
}
}
}
}
return list
}
/**
* 是否本地(局域网)IP
*/
func IsPrivateIp(ip string) bool {
process_ip := getIpNumber(ip)
/**
* 私有IPA类 10.0.0.0 -10.255.255.255
* B类 172.16.0.0 -172.31.255.255
* C类 192.168.0.0 -192.168.255.255
* D类 127.0.0.0 -127.255.255.255(环回地址)
*/
a_begin := getIpNumber("10.0.0.0")
a_end := getIpNumber("10.255.255.255")
if process_ip >= a_begin && process_ip <= a_end {
return true
}
b_begin := getIpNumber("172.16.0.0")
b_end := getIpNumber("172.31.255.255")
if process_ip >= b_begin && process_ip <= b_end {
return true
}
c_begin := getIpNumber("192.168.0.0")
c_end := getIpNumber("192.168.255.255")
if process_ip >= c_begin && process_ip <= c_end {
return true
}
d_begin := getIpNumber("127.0.0.0")
d_end := getIpNumber("127.255.255.255")
if process_ip >= d_begin && process_ip <= d_end {
return true
}
return false
}
func getIpNumber(ip string) int64 {
ip_segment := strings.Split(ip, ".")
if len(ip_segment) != 4 {
return -1
}
segment_1, _ := strconv.ParseInt(ip_segment[0], 10, 64)
segment_2, _ := strconv.ParseInt(ip_segment[1], 10, 64)
segment_3, _ := strconv.ParseInt(ip_segment[2], 10, 64)
segment_4, _ := strconv.ParseInt(ip_segment[3], 10, 64)
ip_num := segment_1*256*256*256 + segment_2*256*256 + segment_3*256 + segment_4
return ip_num
}
/**
* 取来源地址
*/
func GetRemoteIp(req *http.Request) string {
forward_ip := req.Header.Get("X-Forwarded-For") //使用代理
if forward_ip != "" {
forward_ips := strings.Split(forward_ip, ",")
if len(forward_ips) > 0 && forward_ips[0] != "" {
remoteIp, _, err := net.SplitHostPort(forward_ips[0])
if err != nil {
remoteIp = forward_ips[0]
}
return remoteIp
}
}
if remoteIp, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
return remoteIp
}
return req.RemoteAddr
}
/**
* ip是否正确
*/
func GetNumber(ip, mask string) (string, error) {
a := net.ParseIP(ip)
if a == nil {
return "", errors.New("150057")
}
b := net.ParseIP(mask)
if b == nil {
return "", errors.New("150058")
}
ips := strings.Split(ip, ".")
a1, _ := strconv.Atoi(ips[0])
a2, _ := strconv.Atoi(ips[1])
a3, _ := strconv.Atoi(ips[2])
a4, _ := strconv.Atoi(ips[3])
masks := strings.Split(mask, ".")
m1, _ := strconv.Atoi(masks[0])
m2, _ := strconv.Atoi(masks[1])
m3, _ := strconv.Atoi(masks[2])
m4, _ := strconv.Atoi(masks[3])
n1 := a1 & m1
n2 := a2 & m2
n3 := a3 & m3
n4 := a4 & m4
return strconv.Itoa(n1) + "." + strconv.Itoa(n2) + "." + strconv.Itoa(n3) + "." + strconv.Itoa(n4), nil
}
/*
* CIDR取IP mask
* 2019/03/07
*/
func GetIpMaskFromCIDR(ip string) (string, string, error) {
ips, ipNet, err := net.ParseCIDR(ip)
if err != nil {
return "", "", err
}
val := make([]byte, len(ipNet.Mask))
copy(val, ipNet.Mask)
var s []string
for _, i := range val[:] {
s = append(s, strconv.Itoa(int(i)))
}
return ips.String(), strings.Join(s, "."), nil
}
/*
* net mask转换, 255.255.255.0 -> 24
* 2019/03/07
*/
func ChangeMask(mask string) string {
s := strings.Split(mask, ".")
s1, _ := strconv.Atoi(s[0])
s2, _ := strconv.Atoi(s[1])
s3, _ := strconv.Atoi(s[2])
s4, _ := strconv.Atoi(s[3])
ipmask := net.IPv4Mask(byte(s1), byte(s2), byte(s3), byte(s4))
ones, _ := ipmask.Size()
return strconv.Itoa(ones)
}

+ 50
- 0
ip_test.go View File

@ -0,0 +1,50 @@
package network
import (
"fmt"
"testing"
)
func Test_IsPrivateIp(t *testing.T) {
str := "10.1.77.54"
is := IsPrivateIp(str)
fmt.Println("is private ip", is)
}
func Test_GetLocalIps(t *testing.T) {
ips := GetLocalIps()
fmt.Println(ips)
}
func Test_GetInternetIps(t *testing.T) {
ips := GetInternetIps()
fmt.Println(ips)
}
func Test_GetNumber(t *testing.T) {
ip := "192.168.122.21"
mask := "255.255.255.0"
n, err := GetNumber(ip, mask)
t.Log(n, err)
ip = "192.168.112.253"
mask = "255.255.120.0"
n, err = GetNumber(ip, mask)
t.Log(n, err)
ip = "172.16.23.23"
mask = "255.255.255.0"
n, err = GetNumber(ip, mask)
t.Log(n, err)
}
func Test_GetIpMaskFromCIDR(t *testing.T) {
ip := "192.168.141.22/24"
ip, mask, err := GetIpMaskFromCIDR(ip)
t.Log(ip, mask, err)
}
func Test_ChangeMask(t *testing.T) {
mask := "255.255.255.0"
a := ChangeMask(mask)
t.Log(a)
}

+ 46
- 0
ping.go View File

@ -0,0 +1,46 @@
package network
import (
"os/exec"
"runtime"
"strings"
)
func Ping(ip string) bool {
if ip == "" {
return false
}
var cmd *exec.Cmd
if strings.ToLower(runtime.GOOS) == "linux" {
cmd = exec.Command("ping", ip, "-c", "1")
} else {
cmd = exec.Command("ping", ip, "-n", "1")
}
out, err := cmd.Output()
cmd.Run()
str := strings.ToLower(string(out))
if err == nil && strings.Contains(str, "ttl") {
return true
}
return false
}
func CanConnect(ip, port string) bool {
cmd := exec.Command("telnet", ip, port)
out, _ := cmd.Output()
cmd.Run()
s := string(out)
if strings.Contains(s, "Connected") && strings.Contains(s, "Escape") {
return true
}
return false
}

+ 21
- 0
ping_test.go View File

@ -0,0 +1,21 @@
package network
import (
// "fmt"
"testing"
)
func Test_Ping(t *testing.T) {
str := "10.0.100.10"
ret := Ping(str)
fmt.Println(ret)
}
func Test_CanConnect(t *testing.T) {
ip := "10.0.106.212"
port := ""
ret := CanConnect(ip, port)
t.Log(ret)
}

+ 91
- 0
port.go View File

@ -0,0 +1,91 @@
package network
import (
"crypto/rand"
"math/big"
"net"
"strconv"
)
/**
扫描本机空闲端口
参数说明
startPort 扫描开始端口 不包含这个端口
endPort 扫描结束端口 不包含这个端口
count 扫描端口数量
*/
func ScanPort(startPort, endPort int64, count int) []int64 {
usePort := make([]int64, 0)
for startPort < endPort {
startPort = startPort + 1
udpserver, err := net.ResolveUDPAddr("udp", ":"+strconv.FormatInt(int64(startPort), 10))
if err != nil {
continue
}
udpConn, err := net.ListenUDP("udp", udpserver)
if err != nil {
continue
}
udpConn.Close()
ln, err := net.Listen("tcp", "0.0.0.0:"+strconv.FormatInt(int64(startPort), 10))
if err != nil {
continue
}
usePort = append(usePort, startPort)
ln.Close()
if len(usePort) >= count {
break
}
}
return usePort
}
/**
* 取随机端口
*/
func RandPort(min, max int64) int64 {
var port int64
for {
port = RandInt64(min, max)
udpserver, err := net.ResolveUDPAddr("udp", ":"+strconv.FormatInt(int64(port), 10))
if err != nil {
continue
}
udpConn, err := net.ListenUDP("udp", udpserver)
if err != nil {
continue
}
udpConn.Close()
ln, err := net.Listen("tcp", "0.0.0.0:"+strconv.FormatInt(int64(port), 10))
if err != nil {
continue
}
ln.Close()
break
}
return port
}
/**
* 取随机数
*/
func RandInt64(min, max int64) int64 {
var randnum int64
for {
maxBigInt := big.NewInt(max)
i, _ := rand.Int(rand.Reader, maxBigInt)
if i.Int64() > min {
randnum = i.Int64()
break
}
}
return randnum
}

+ 16
- 0
port_test.go View File

@ -0,0 +1,16 @@
package network
import (
"fmt"
"testing"
)
func TestScanPort(t *testing.T) {
ports := ScanPort(55000, 60000, 2)
fmt.Println(ports)
}
func TestRandPort(t *testing.T) {
port := RandPort(50000, 60000)
fmt.Println("port:", port)
}

+ 166
- 0
url.go View File

@ -0,0 +1,166 @@
/*
* url functions
*/
package network
import (
"crypto/md5"
"encoding/hex"
"errors"
"io/ioutil"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"git.tetele.net/tgo/crypter"
)
/**
* post 请求
*/
func FnPost(url, param string) ([]byte, error) {
httpClient := &http.Client{}
req, err := http.NewRequest("POST", url, strings.NewReader(param))
if err != nil {
return []byte(""), err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded") //"application/x-www-form-urlencoded"
resp, err := httpClient.Do(req)
if err != nil {
return []byte(""), err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return []byte(""), err
}
return body, nil
}
/**
* 取本地IP
*/
func GetLocalIp() string {
addrs, err := net.InterfaceAddrs()
if err != nil {
return ""
}
for _, address := range addrs {
// 检查ip地址判断是否回环地址
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil && !ipnet.IP.IsLinkLocalUnicast() {
return ipnet.IP.String()
}
}
}
return ""
}
/**
* 生成一个token
*/
func CreateTokenWithTime(sToken string) string {
now := time.Now()
iNow := now.Format("20060102150405")
sToken += iNow
h := md5.New()
h.Write([]byte(sToken)) // 需要加密的字符串
cipher2Str := h.Sum(nil)
return hex.EncodeToString(cipher2Str) // 输出加密结果
}
/**
* 生成一个token
*/
// func CreateToken(sToken string) string {
// now := time.Now()
// iNow := now.Format("20060102150405")
// sToken += iNow
// h := md5.New()
// h.Write([]byte(sToken)) // 需要加密的字符串
// cipher2Str := h.Sum(nil)
// sMd5 := hex.EncodeToString(cipher2Str) // 输出加密结果
// tokenEn := crypter.DesEn(sToken, "gzyc8642")
// return sMd5 + "|" + ToString(now.Unix()) + "|" + tokenEn
// }
/**
* 验证token
*/
func CheckToken(token string) (bool, string) {
arr := strings.Split(token, "|")
if len(arr) != 3 {
return false, ""
}
tokenDes := crypter.DesDe(arr[2], "gzyc8642")
tokenTime := tokenDes[len(tokenDes)-14:]
timeInt, err := strconv.ParseInt(arr[1], 10, 64)
if err != nil {
return false, ""
}
currentTime := time.Unix(timeInt, 0).Format("20060102150405")
if currentTime != tokenTime {
return false, ""
}
h := md5.New()
h.Write([]byte(tokenDes)) // 需要加密的字符串
cipher2Str := h.Sum(nil)
sMd5 := hex.EncodeToString(cipher2Str) // 输出加密结果
if sMd5 == arr[0] {
return true, tokenDes[0 : len(tokenDes)-14]
}
return false, ""
}
/**
* 给参数签名
*/
func QuerySign(mQuery map[string]string) string {
sParam := ""
for k, v := range mQuery {
sParam += k + "=" + v + "&"
}
query, Err := url.ParseQuery(sParam)
if Err != nil {
return ""
} else {
return crypter.Md5Password(query.Encode(), "guzeng1")
}
}
/**
* 从url中取域名端口
* 2019/05/20
*/
func GetIpPortFromUrl(sUrl string) (string, string, error) {
if sUrl == "" {
return "", "", errors.New("param error")
}
if !strings.Contains(sUrl, "http://") && !strings.Contains(sUrl, "https://") {
sUrl = "http://" + sUrl
}
u, err := url.Parse(sUrl)
if err != nil {
return "", "", err
}
return u.Hostname(), u.Port(), nil
}

+ 22
- 0
url_test.go View File

@ -0,0 +1,22 @@
package network
import (
"testing"
)
func Test_CheckToken(t *testing.T) {
code := "127328"
token := CreateToken(code)
t.Log(token)
str := "1dcfbe790d270f45ae35779afbc4072e|1532068096|90EDAA4C1E97C7517E9D10AB9157E4D0D9CC51996E3827F2"
check, user := CheckToken(str)
t.Log(check)
t.Log(user)
}
func Test_GetIpPortFromUrl(t *testing.T) {
url := "http://raydesktop.gxycloud.com:8082/getmaster"
GetIpPortFromUrl(url)
}

Loading…
Cancel
Save