嗨,我可以使用这个解决方案获得本地网络IP地址。我尝试使用这个解决方案来获得广播IP地址,使用这个Objective-C解决方案。
static func getBroadCastAddress() -> String? {
var address: String?
var ifaddr: UnsafeMutablePointer<ifaddrs>? = nil
if getifaddrs(&ifaddr) == 0 {
var ptr = ifaddr
while ptr != nil {
defer { ptr = ptr?.pointee.ifa_next }
guard let interface = ptr?.pointee else { return "" }
let addrFamily = interface.ifa_addr.pointee.sa_family
if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {
let name: String = String(cString: (interface.ifa_name))
if name == "en0" || name == "en2" || name == "en3" || name == "en4" || name == "pdp_ip0" || name == "pdp_ip1" || name == "pdp_ip2" || name == "pdp_ip3" {
var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
getnameinfo(interface.ifa_addr, socklen_t((interface.ifa_addr.pointee.sa_len)), &hostname, socklen_t(hostname.count), nil, socklen_t(0), NI_NUMERICHOST)
// inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_dstaddr)->sin_addr)
if let sinAddress = (interface.ifa_dstaddr as? sockaddr_in)?.sin_addr{ //=> It's always fail
address = String(utf8String: inet_ntoa(sinAddress))
}
}
}
}
freeifaddrs(ifaddr)
}
return address ?? ""
}
问题是,我不能得到sin_addr
从interface
像inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_dstaddr)->sin_addr)
在objective c代码。
谁能帮助我得到广播IP地址在可可使用Swift?谢谢你的宝贵时间。
let acceptedInterfaces = ["en0", "en2", "en3", "en4", "pdp_ip0", "pdp_ip1", "pdp_ip2", "pdp_ip3"]
func getBroadCastAddress() {
var interfaceAddresses : [String : String] = [:]
var ifaddr: UnsafeMutablePointer<ifaddrs>? = nil
if getifaddrs(&ifaddr) == 0 {
defer { freeifaddrs(ifaddr) }
var currentInterface = ifaddr
while currentInterface != nil {
defer { currentInterface = currentInterface!.pointee.ifa_next }
let interface = currentInterface!.pointee
let addrFamily = interface.ifa_addr.pointee.sa_family
guard addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) else { continue }
let interfaceName = String(cString: interface.ifa_name)
if acceptedInterfaces.contains(interfaceName) {
currentInterface!.withMemoryRebound(to: sockaddr_in.self, capacity: 1) {
sockaddr in
if let addressCString = inet_ntoa(sockaddr.pointee.sin_addr) {
interfaceAddresses[interfaceName] = String(cString: addressCString)
}
}
}
}
}
debugPrint(interfaceAddresses)
}
它打印:
["en0": "194.127.0.0"]