//
//  DNSResolver.swift
//  punchnet
//
//  Created by 安礼成 on 2025/5/14.
//
import Foundation
import Darwin

struct DNSResolver {
    
    // 解析域名获取域名对应的ip地址
    static func resolveAddrInfos(_ hostname: String) -> [String] {
        var hints = addrinfo(
            ai_flags: AI_ALL,
            ai_family: AF_UNSPEC,
            ai_socktype: SOCK_STREAM,
            ai_protocol: 0,
            ai_addrlen: 0,
            ai_canonname: nil,
            ai_addr: nil,
            ai_next: nil
        )
        
        var result: UnsafeMutablePointer<addrinfo>?
        let error = getaddrinfo(hostname, nil, &hints, &result)
        guard error == 0 else {
            return []
        }
        
        var ips = [String]()
        var current = result
        while current != nil {
            var host = [CChar](repeating: 0, count: Int(NI_MAXHOST))
            if let addr = current?.pointee.ai_addr {
                getnameinfo(
                    addr,
                    socklen_t(addr.pointee.sa_len),
                    &host,
                    socklen_t(host.count),
                    nil,
                    0,
                    NI_NUMERICHOST
                )
                let ip = String(cString: host)
                ips.append(ip)
            }
            current = current?.pointee.ai_next
        }
        
        freeaddrinfo(result)
        return ips
    }
    
}
