2 Star 0 Fork 0

carlmax_my/console-core-go

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
iface.go 1.85 KB
一键复制 编辑 原始数据 按行查看 历史
carlmax_my 提交于 2025-06-22 13:31 +08:00 . clean code
package iface
import (
"log"
"net"
"strings"
"gitee.com/carlmax_my/console-core-go/pkg/net/ip_util"
"github.com/pkg/errors"
)
// lo, eth
func FindIfaceByIp(ipaddr string) (ifaceName string, err error) {
ifaces, err := net.Interfaces()
if err != nil {
return "", errors.Wrapf(err, "FindIfaceByIp[%s] err", ipaddr)
}
if len(ifaces) == 0 {
return "", nil
}
for _, iface := range ifaces {
if iface.Flags&net.FlagLoopback != 0 {
continue
}
if iface.Flags&net.FlagUp == 0 {
continue
}
addrs, err := iface.Addrs()
if err != nil {
log.Println("iface.Addrs err", err.Error())
}
if ip_util.IsIpInAddrs(addrs, ipaddr) {
return iface.Name, nil
}
}
return "", nil
}
func GetIfacesNameByPrefix(prefix string) ([]string, error) {
ifaces, err := net.Interfaces()
if err != nil {
return nil, errors.Wrapf(err, "GetIfacesNameByPrefix(%s) error", prefix)
}
if len(ifaces) == 0 {
return nil, nil
}
ret := []string{}
for _, i := range ifaces {
if strings.HasPrefix(i.Name, prefix) {
ret = append(ret, i.Name)
}
}
return ret, nil
}
// net.InterfaceByName(), err 会有 "no such network interface"
// if strings.Contains(err.Error(), "no such network interface") {
func FindIface(iface string) (*net.Interface, error) {
list, err := net.Interfaces()
if err != nil {
return nil, errors.Wrapf(err, "FindIface(%s) error", iface)
}
if len(list) == 0 {
return nil, nil
}
for _, v := range list {
if v.Name == iface {
return &v, nil
}
}
return nil, nil
}
func IsIfaceExist(iface string) (bool, error) {
i, err := FindIface(iface)
if err != nil {
return false, err
}
return i != nil, nil
}
func IsIfaceUp(iface string) (bool, error) {
ifaceObj, err := FindIface(iface)
if err != nil {
return false, err
}
if ifaceObj == nil {
return false, nil
}
up := ifaceObj.Flags & net.FlagUp
return up != 0, nil
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/carlmax_my/console-core-go.git
git@gitee.com:carlmax_my/console-core-go.git
carlmax_my
console-core-go
console-core-go
v0.1.110

搜索帮助