1 Star 1 Fork 1

坐公交也用券 / gns

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
ip.go 5.36 KB
一键复制 编辑 原始数据 按行查看 历史
lenove 提交于 2023-04-26 12:05 . 增加丢包率
package gns
import (
"fmt"
"net"
"regexp"
"sort"
"strings"
"gitee.com/liumou_site/logger"
"github.com/spf13/cast"
)
// GetIntranetAddressList 获取本机所有IP列表
func (api *IpApi) GetIntranetAddressList() (bool, []string) {
var IpList []string
address, err := net.InterfaceAddrs()
if err != nil {
logger.Error("GetIntranetAddress failed")
return false, strings.Split(" ", " ")
}
for _, addr := range address {
if IpNet, ok := addr.(*net.IPNet); ok && !IpNet.IP.IsLoopback() {
if IpNet.IP.To4() != nil {
ip := IpNet.IP.String()
//ip_ = string(ip_) + " " + ip
IpList = append(IpList, ip)
logger.Info("IP: ", ip)
}
}
}
return true, IpList
}
// GetUseIP 通过Udp协议发送请求获取正在使用的IP(默认路由IP,如果做了自定义路由并且设置了目标服务器,则会获取到对应的本地IP)
func (api *IpApi) GetUseIP() (string, error) {
dnsList := []string{api.dns1, api.dns2}
for _, dns := range dnsList {
server := string(dns) + ":" + cast.ToString(api.port)
if api.debug {
logger.Debug("Server: ", server)
}
conn, err := net.Dial("udp", server)
// 获取本地IP
if err != nil {
// 延迟函数
defer func(conn net.Conn) {
err := conn.Close()
if err != nil {
return
}
}(conn)
logger.Error("获取失败,请检查网络是否正常连接网络: ", err)
if dns == api.dns2 {
return "failed", err
}
} else {
LocalIpInfo := conn.LocalAddr().String()
// 获取:号的index值,然后截取
LocalIp := strings.LastIndex(LocalIpInfo, ":")
if api.debug {
logger.Debug("本地请求信息: ", LocalIpInfo)
logger.Debug(":号索引值: ", LocalIp)
}
err := conn.Close()
if err != nil {
return "", err
}
return LocalIpInfo[0:LocalIp], nil
}
}
return "failed", fmt.Errorf("获取异常")
}
// IpGenerateList 生成IP列表,传入子网(192.168.1),开始IP(0),结束IP(255)用于生成一个列表切片
func IpGenerateList(subnet string, start, stop uint8) ([]string, error) {
qp := strings.Split(subnet, ".")
if start >= stop {
err := fmt.Errorf("传入的初始值大于或等于终止值")
return qp, err
}
TestIp := subnet + ".2" // 生成一个测试IP
_, s := IpParse(TestIp) // 检测生成的IP是否符合IPV4规范
if s == 4 {
// 如果符合IPV4规范则开始生成
var IpList []string
for i := start; i <= stop; i++ {
ip := subnet + "." + cast.ToString(i)
IpList = append(IpList, ip)
}
return IpList, nil
}
// 如果不符合规范则返回错误信息
logger.Error("生成的测试IP: ", TestIp)
return qp, fmt.Errorf("传入了非标准IP地址,标准网段参考: 192.168.1")
}
// IpCutSubnet 通过传入一个完整IP(192.168.1.1)截取该IP的网段(192.168.1)
func IpCutSubnet(ip string) string {
s := strings.Split(ip, ".")
subs := s[:3]
subnet := SliceToString(subs, ".")
return subnet
}
// IpCutEndId 通过传入一个完整IP(192.168.1.1)截取该IP的ID(1)
func IpCutEndId(ip string) (index int, err error) {
_, ips := IpParse(ip)
if ips == 4 {
s := strings.Split(ip, ".")
subs := s[3]
index = cast.ToInt(subs)
} else {
err = fmt.Errorf("IP格式不正确")
index = 0
}
return
}
// IpSort 通过传入一个IP切片进行排序处理
func IpSort(ip string) (index int, err error) {
_, ips := IpParse(ip) // 判断IP是否标准
if ips == 4 {
s := strings.Split(ip, ".")
subs := s[3]
index = cast.ToInt(subs)
} else {
err = fmt.Errorf("IP格式不正确")
index = 0
}
return
}
// IpGenerateIndex 通过传入一个标准IP和切片列表生成IP进行排序处理
// [1 3 7 10 20 5 6]
// [192.168.1.1 192.168.1.3 192.168.1.5 192.168.1.6 192.168.1.7 192.168.1.10 192.168.1.20]
func IpGenerateIndex(ip string, ipSlice []int) (IpList []string, err error) {
var sub string
_, ips := IpParse(ip) // 判断传入的IP是否符合规范
if ips == 4 {
sub = IpCutSubnet(ip) // 切割IP获取网段信息
} else {
// 如果传入的不是IPV4标准地址则返回错误
return IpList, fmt.Errorf("IP格式错误")
}
if len(ipSlice) == 0 {
return IpList, fmt.Errorf("传入列表为空")
}
sort.Ints(ipSlice) // 使用排序处理
//fmt.Println(ipSlice)
for _, ipIndex := range ipSlice { // 开始遍历传入的列表
ipTmp := sub + "." + cast.ToString(ipIndex)
_, ips = IpParse(ipTmp) // 判断IP是否标准
if ips == 4 {
IpList = append(IpList, ipTmp)
} else {
logger.Error("IP格式不正确: ", ipTmp)
}
}
return IpList, nil
}
// IpParse 判断IP是否规范及类型(4/6)
func IpParse(s string) (net.IP, int) {
ip := net.ParseIP(s)
// 如果返回零值则判断格式不正确
if ip == nil {
return nil, 0
}
for i := 0; i < len(s); i++ {
switch s[i] {
case '.':
return ip, 4
case ':':
return ip, 6
}
}
return nil, 0
}
// IpStrGetAddr 从字符串中提取所有IPV4地址
func IpStrGetAddr(text string) (error, []net.IP) {
var res []net.IP
// Sample input string
// "Some text with IP address 192.168.1.1 and some more text with IP address 10.0.0.1"
// Regular expression to match IPV4 addresses
regex := regexp.MustCompile(`\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b`)
// Find all matches
matches := regex.FindAllString(text, -1)
if len(matches) >= 1 {
for _, match := range matches {
r, n := IpParse(match)
if n == 4 {
res = append(res, r)
}
}
if len(res) >= 1 {
return nil, res
}
}
return fmt.Errorf("匹配失败"), res
}
Go
1
https://gitee.com/liumou_site/gns.git
git@gitee.com:liumou_site/gns.git
liumou_site
gns
gns
v1.3.3

搜索帮助

53164aa7 5694891 3bd8fe86 5694891