2024-04-05 02:09:16 +00:00
|
|
|
package network
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-04-05 02:18:42 +00:00
|
|
|
"fmt"
|
2024-04-05 02:09:16 +00:00
|
|
|
"github.com/songquanpeng/one-api/common/logger"
|
|
|
|
"net"
|
|
|
|
)
|
|
|
|
|
2024-04-05 02:18:42 +00:00
|
|
|
func IsValidSubnet(subnet string) error {
|
|
|
|
_, _, err := net.ParseCIDR(subnet)
|
2024-04-05 04:40:03 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to parse subnet: %w", err)
|
|
|
|
}
|
|
|
|
return nil
|
2024-04-05 02:18:42 +00:00
|
|
|
}
|
|
|
|
|
2024-04-05 02:09:16 +00:00
|
|
|
func IsIpInSubnet(ctx context.Context, ip string, subnet string) bool {
|
|
|
|
_, ipNet, err := net.ParseCIDR(subnet)
|
|
|
|
if err != nil {
|
2024-04-05 02:18:42 +00:00
|
|
|
logger.Errorf(ctx, "failed to parse subnet: %s", err.Error())
|
2024-04-05 02:09:16 +00:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
return ipNet.Contains(net.ParseIP(ip))
|
|
|
|
}
|