| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- package validator
- import (
- "fmt"
- "net"
- "networktool/internal/model"
- )
- type Service struct{}
- func New() *Service { return &Service{} }
- func (s *Service) Validate(input model.InterfaceConfig) model.ValidateResponse {
- resp := model.ValidateResponse{Valid: false, Warnings: []string{}, Errors: []string{}}
- if input.Interface == "" {
- resp.Errors = append(resp.Errors, "目标接口不能为空。")
- }
- if input.Dhcp4 {
- resp.Valid = len(resp.Errors) == 0
- return resp
- }
- ip := net.ParseIP(input.IP)
- if ip == nil || ip.To4() == nil {
- resp.Errors = append(resp.Errors, "IP 地址格式不正确。")
- }
- if input.Prefix < 0 || input.Prefix > 32 {
- resp.Errors = append(resp.Errors, "前缀长度不正确。")
- }
- if input.Gateway != "" {
- gateway := net.ParseIP(input.Gateway)
- if gateway == nil || gateway.To4() == nil {
- resp.Errors = append(resp.Errors, "网关格式不正确。")
- } else if ip != nil && ip.To4() != nil && input.Prefix >= 0 && input.Prefix <= 32 {
- mask := net.CIDRMask(input.Prefix, 32)
- ipNet := &net.IPNet{IP: ip.Mask(mask), Mask: mask}
- if !ipNet.Contains(gateway) {
- resp.Errors = append(resp.Errors, "网关与目标接口 IP 不在同一子网。")
- }
- }
- }
- for _, dns := range input.DNS {
- if dns == "" {
- continue
- }
- parsed := net.ParseIP(dns)
- if parsed == nil || parsed.To4() == nil {
- resp.Errors = append(resp.Errors, fmt.Sprintf("DNS 格式不正确:%s", dns))
- }
- }
- if ip != nil && ip.To4() != nil {
- if ip[0] == 169 && ip[1] == 254 {
- resp.Warnings = append(resp.Warnings, "目标接口使用的是链路本地地址,通常仅适合同链路通信。")
- }
- }
- resp.Valid = len(resp.Errors) == 0
- return resp
- }
|