Golang obtiene la tarjeta de red cableada activa y la configuración IP del sistema Windows

código

package network

import (
	"errors"
	"fmt"
	"github.com/StackExchange/wmi"
	"golang.org/x/text/encoding/simplifiedchinese"
	"log"
	"net"
	"os/exec"
	"strings"
	"time"
)

type Win32_NetworkAdapterConfiguration struct {
    
    
	Caption                      string
	Description                  string
	SettingID                    string
	ArpAlwaysSourceRoute         bool
	ArpUseEtherSNAP              bool
	DatabasePath                 string
	DeadGWDetectEnabled          bool
	DefaultIPGateway             []string
	DefaultTOS                   uint8
	DefaultTTL                   uint8
	DHCPEnabled                  bool
	DHCPLeaseExpires             *time.Time
	DHCPLeaseObtained            *time.Time
	DHCPServer                   string
	DNSDomain                    string
	DNSDomainSuffixSearchOrder   []string
	DNSEnabledForWINSResolution  bool
	DNSHostName                  string
	DNSServerSearchOrder         []string
	DomainDNSRegistrationEnabled bool
	ForwardBufferMemory          uint32
	FullDNSRegistrationEnabled   bool
	GatewayCostMetric            []int32
	IGMPLevel                    uint8
	Index                        uint32
	InterfaceIndex               uint32
	IPAddress                    []string
	IPConnectionMetric           uint32
	IPEnabled                    bool
	IPFilterSecurityEnabled      bool
	IPPortSecurityEnabled        bool
	IPSecPermitIPProtocols       []string
	IPSecPermitTCPPorts          []string
	IPSecPermitUDPPorts          []string
	IPSubnet                     []string
	//IPUseZeroBroadcast           bool
	//IPXAddress                   string
	//IPXEnabled                   bool
	//IPXFrameType                 []uint32
	//IPXMediaType                 uint32
	IPXNetworkNumber []string
	//IPXVirtualNetNumber          string
	//KeepAliveInterval            uint32
	//KeepAliveTime                uint32
	MACAddress string
	//MTU                          uint32
	//NumForwardPackets            uint32
	//PMTUBHDetectEnabled          bool
	//PMTUDiscoveryEnabled         bool
	//ServiceName                  string
	//TcpipNetbiosOptions          uint32
	//TcpMaxConnectRetransmissions uint32
	//TcpMaxDataRetransmissions    uint32
	//TcpNumConnections            uint32
	//TcpUseRFC1122UrgentPointer   bool
	//TcpWindowSize                uint16
	//WINSEnableLMHostsLookup      bool
	//WINSHostLookupFile           string
	//WINSPrimaryServer            string
	//WINSScopeID                  string
	//WINSSecondaryServer          string
}

type EthernetInfo struct {
    
    
	IP                   string
	Mask                 string
	Gateway              string
	Index                uint32
	Name                 string
	DHCPEnabled          bool
	DNSServerSearchOrder []string
}

func QueryLocalActiveEthernet() (*EthernetInfo, error) {
    
    
	s, err := wmi.InitializeSWbemServices(wmi.DefaultClient)
	if err != nil {
    
    
		return nil, err
	}

	var dst []Win32_NetworkAdapterConfiguration
	q := wmi.CreateQuery(&dst, "WHERE IPEnabled=True")
	errQuery := s.Query(q, &dst)
	if errQuery != nil {
    
    
		return nil, errQuery
	}
	res := make([]Win32_NetworkAdapterConfiguration, 0)
	for _, adapter := range dst {
    
    
		if !strings.Contains(adapter.Caption, "Wireless") {
    
    
			res = append(res, adapter)
		}
	}
	length := len(res)
	if length == 0 {
    
    
		return nil, errors.New("未匹配到可用的网卡")
	} else if length > 1 {
    
    
		return nil, errors.New("活跃的网卡不止一个,请检查确认")
	} else {
    
    
		// 通过网卡序号获取网卡基本信息
		netInterface, err := net.InterfaceByIndex(int(res[0].InterfaceIndex))
		if err != nil {
    
    
			return nil, err
		}

		ethernet := EthernetInfo{
    
    
			Index:                res[0].InterfaceIndex,
			Name:                 netInterface.Name,
			DHCPEnabled:          res[0].DHCPEnabled,
			DNSServerSearchOrder: res[0].DNSServerSearchOrder,
		}
		if len(res[0].IPAddress) > 0 {
    
    
			ethernet.IP = res[0].IPAddress[0]
		}
		if len(res[0].IPSubnet) > 0 {
    
    
			ethernet.Mask = res[0].IPSubnet[0]
		}
		if len(res[0].DefaultIPGateway) > 0 {
    
    
			ethernet.Gateway = res[0].DefaultIPGateway[0]
		}
		return &ethernet, nil
	}
}

// winCmd 输入执行函数
func winCmd(s string) error {
    
    
	output, err := exec.Command("cmd", "/c", s).Output()
	if err != nil {
    
    
		log.Println(err.Error())
		return errors.New(ConvertByte2String(output, "GB18030"))
	}
	return nil
}

// SetIpMaskGW 设置网卡ip/mask/gw
func SetIpMaskGW(name, ip, mask, gateway, gwMetric string) error {
    
    
	// netsh interface ip set address "eth0" static 192.168.0.12 255.255.255.0 192.168.0.254 1
	setIpMaskCommand := fmt.Sprintf(
		"netsh interface ip set address \"%s\" static %s %s %s %s", name, ip, mask, gateway, gwMetric)
	// 执行cmd命令
	return winCmd(setIpMaskCommand)
}

// SetDNS 设置网卡DNS
func SetDNS(name string, dnsServerOrder []string) error {
    
    
	// 主DNS netsh interface ip set dns "eth0" static 218.2.135.1 primary
	// 辅DNS netsh interface ip add dns "eh0" 223.5.5.5
	for idx, dns := range dnsServerOrder {
    
    
		if idx == 0 {
    
    
			err := winCmd(fmt.Sprintf("netsh interface ip set dns \"%s\" static %s primary", name, dns))
			if err != nil {
    
    
				return err
			}
		} else {
    
    
			time.Sleep(time.Millisecond * 200) // 两条指令之间短暂延时
			err := winCmd(fmt.Sprintf("netsh interface ip add dns \"%s\" %s", name, dns))
			if err != nil {
    
    
				return err
			}
		}
	}
	return nil
}

// SetDHCP 设置为DHCP模式
func SetDHCP(name string) error {
    
    
	//返回用户需要设置的网卡名称
	// netsh interface ip set address "本地连接" dhcp
	// netsh interface ip set dns "本地连接" dhcp
	newDHCP := make([]string, 2)
	newDHCP[0] = fmt.Sprintf("netsh interface ip set address \"%s\" dhcp", name)
	newDHCP[1] = fmt.Sprintf("netsh interface ip set dns \"%s\" dhcp", name)
	//调用cmd输入
	if err := winCmd(newDHCP[0]); err != nil {
    
    
		return err
	}
	time.Sleep(time.Second * 1)
	return winCmd(newDHCP[1])
}

type Charset string

const (
	UTF8    = Charset("UTF-8")
	GB18030 = Charset("GB18030")
)

func ConvertByte2String(byte []byte, charset Charset) string {
    
    
	var str string
	switch charset {
    
    
	case GB18030:
		var decodeBytes, _ = simplifiedchinese.GB18030.NewDecoder().Bytes(byte)
		str = string(decodeBytes)
	case UTF8:
		fallthrough
	default:
		str = string(byte)
	}

	return str
}

Supongo que te gusta

Origin blog.csdn.net/qq_38923792/article/details/129418980
Recomendado
Clasificación