Get/Set Network interface in pure GO code

I have an arm IOT device running Ubuntu server and I need to both read and write the following in GO code

  1. IP Address (IPV4)
  2. Subnet Mask
  3. Default Gateway
  4. Primary DNS
  5. Secondary DNS

I know I can set them from the command line using ifconfig, route and nameserver and put these commands in a bash script followed by running /etc/init.d/networking restart to make the change permanent.

I could even write a file handler to edit /etc/network/interfaces directly BUT both of these options seem like a hack so I would much rather do it in pure GO.

Funny thing is that docker is written in GO and the containers have their own ip address so its surely possible unless they are making low level kernel calls.

I have looked in the os and net packages and nothing jumps out and slaps me in the face, so I woud really appreciate any help in this area.

Look at Docker source at Github, maybe libnetwork/osl/interface_linux.go

Thanks I was going to do that as a last resort if I couldn’t work out how to do it. I do actually have a solution now after much hacking which I thought I would post in case any one else has a similar problem.

func subnetMask() (addr string) {

return (net.IP(net.CIDRMask(24, 32))).To4().String()

}

func ipAddress() (addr string) {

local := "127.0.0.1"
addrs, _ := net.InterfaceAddrs()

for _, a := range addrs {
	if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
		if ipnet.IP.To4() != nil {
			local = ipnet.IP.String()
		}
	}
}

return local

}

func defaultGateway() (addr string) {

local := "127.0.0.1"

routeCmd := exec.Command("route", "-n")
output, _ := routeCmd.CombinedOutput()

lines := strings.Split(string(output), "\n")
for _, line := range lines {
	fields := strings.Fields(line)
	if len(fields) >= 2 && fields[0] == "0.0.0.0" {
		ip := net.ParseIP(fields[1])
		if ip != nil {
			return ip.To4().String()
		}
	}
}

return local

}

func dnsServer(ordinal string) (addr string) {

local := ""

routeCmd := exec.Command("nmcli", "device", "list")
output, err := routeCmd.CombinedOutput()
if err != nil {
	routeCmd = exec.Command("nmcli", "device", "show")
	output, _ = routeCmd.CombinedOutput()
}
/* ********************************************************/

lines := strings.Split(string(output), "\n")
for _, line := range lines {
	fields := strings.Fields(line)
	if len(fields) >= 2 && fields[0] == "IP4.DNS["+ordinal+"]:" {
		ip := net.ParseIP(fields[1])
		if ip != nil {
			return ip.To4().String()
		}
	}
}

return local

}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.