This repository has been archived on 2024-08-02. You can view files and clone it, but cannot push or open issues or pull requests.
orion/openwrt/dhcp_client.go

81 lines
1.6 KiB
Go
Raw Normal View History

2018-09-20 10:59:11 +02:00
package openwrt
import (
"bufio"
"regexp"
"strings"
)
2018-09-20 10:59:11 +02:00
// DhcpClient represents a dhcp client ... :)
type DhcpClient struct {
exec Executor
iface string
}
// DhcpResult contains sorted result form AskFroIP
type DhcpResult struct {
CmdRes *CommandResult
IP string
Netmask string
}
2018-09-20 10:59:11 +02:00
// NewDhcpClient return an UCI instance to interact with UCI
func NewDhcpClient(netIface string) *DhcpClient {
exec := &localExecutor{}
iface := netIface
return &DhcpClient{exec, iface}
}
// NewDhcpClientWithExecutor return an UCI instance to interact with UCI
func NewDhcpClientWithExecutor(netIface string, exe Executor) *DhcpClient {
exec := exe
iface := netIface
return &DhcpClient{exec, iface}
}
// NewDhcpClient return an UCI instance to interact with UCI
//func NewDhcpClient(netIface string, exe Executor) *DhcpClient {
// var exec Executor
// if exe == nil {
// exec = &localExecutor{}
// } else {
// exec = exe
// }
// iface := netIface
// return &DhcpClient{exec, iface}
//}
func parseDhcpClientOut(out *CommandResult) *DhcpResult {
if out.ReturnCode != 0 {
return &DhcpResult{
out,
"",
"",
}
}
scanner := bufio.NewScanner(strings.NewReader(out.Stdout))
for scanner.Scan() {
line := scanner.Text()
re := regexp.MustCompile(`^udhcpc: ifconfig`)
if re.MatchString(line) {
spl := strings.Split(line, " ")
ip := spl[3]
mask := spl[5]
return &DhcpResult{
out,
ip,
mask,
}
}
}
return nil
}
2018-09-20 10:59:11 +02:00
// AskForIP runs a dhclient ip request with udhcpc
func (dc *DhcpClient) AskForIP() *DhcpResult {
out := dc.exec.Run("udhcpc", "-i", dc.iface)
return parseDhcpClientOut(out)
2018-09-20 10:59:11 +02:00
}