83 lines
1.6 KiB
Go
83 lines
1.6 KiB
Go
package owrt
|
|
|
|
import (
|
|
"bufio"
|
|
"fmt"
|
|
"regexp"
|
|
"strings"
|
|
)
|
|
|
|
// 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
|
|
}
|
|
|
|
// 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
|
|
}
|
|
|
|
// AskForIP runs a dhclient ip request with udhcpc
|
|
func (dc *DhcpClient) AskForIP() *DhcpResult {
|
|
out := dc.exec.Run("udhcpc", "-i", dc.iface)
|
|
fmt.Printf("%s\n", out.Stdout)
|
|
return parseDhcpClientOut(out)
|
|
}
|