punchnet-macos/Tun/Punchnet/SDLUtil.swift
2026-01-14 11:13:15 +08:00

53 lines
1.4 KiB
Swift

//
// Util.swift
// Tun
//
// Created by on 2024/1/19.
//
import Foundation
struct SDLUtil {
public static func int32ToIp(_ num: UInt32) -> String {
let ip0 = (UInt8) (num >> 24 & 0xFF)
let ip1 = (UInt8) (num >> 16 & 0xFF)
let ip2 = (UInt8) (num >> 8 & 0xFF)
let ip3 = (UInt8) (num & 0xFF)
return "\(ip0).\(ip1).\(ip2).\(ip3)"
}
public static func netMaskIp(maskLen: UInt8) -> String {
let len0 = 32 - maskLen
let num: UInt32 = (0xFFFFFFFF >> len0) << len0
let ip0 = (UInt8) (num >> 24 & 0xFF)
let ip1 = (UInt8) (num >> 16 & 0xFF)
let ip2 = (UInt8) (num >> 8 & 0xFF)
let ip3 = (UInt8) (num & 0xFF)
return "\(ip0).\(ip1).\(ip2).\(ip3)"
}
// ip
public static func inSameNetwork(ip: UInt32, compareIp: UInt32, maskLen: UInt8) -> Bool {
if ip == compareIp {
return true
}
let len0 = 32 - maskLen
//
let mask: UInt32 = (0xFFFFFFFF >> len0) << len0
return ip & mask == compareIp & mask
}
public static func formatMacAddress(mac: Data) -> String {
let bytes = [UInt8](mac)
return bytes.map { String(format: "%02X", $0) }.joined(separator: ":").lowercased()
}
}