ip.go 1.06 KB
package main

import (
	"errors"
	"regexp"
	"strconv"
)

func getIpAddress() string {
	env, err := getEnv(0)
	if err != nil {
		return ""
	}

	return env["ipaddr"]
}

func getIpAddress2() string {
	env, err := getEnv(0)
	if err != nil {
		return ""
	}

	return env["ipaddr2"]
}

func setIpAddress(address, address2 string) error {
	address = extractIpAddress(address)
	if address == "" {
		return errors.New("invalid IP address")
	}

	address2 = extractIpAddress(address2)
	if address2 == "" {
		return errors.New("invalid IP address2")
	}

	env, err := getEnv(0)
	if err != nil {
		return err
	}

	env["ipaddr"] = address
	env["ipaddr2"] = address2

	err = setEnv(0, env)
	if err != nil {
		return err
	}

	return nil
}

func extractIpAddress(address string) string {
	r := regexp.MustCompile(`([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)`)
	s := r.FindStringSubmatch(address)
	if len(s) != 5 {
		return ""
	}

	for i, v := range s {
		if i == 0 {
			continue
		}

		u, err := strconv.ParseUint(v, 10, 8)
		if err != nil {
			return ""
		}

		if u > 255 {
			return ""
		}
	}

	return s[0]
}