I have made some code for getting the Wi-Fi current SSID and device current IP but i need to get the Network IP Address so if my device's IP is 192.168.4.3 i Know it is connected to 192.168.4.1 Network but I need not to make this assumption in the code ...
Get SSID:
private func fetchSSIDInfo() -> String? {
var ssid: String?
if let interfaces = CNCopySupportedInterfaces() as NSArray? {
for interface in interfaces {
if let interfaceInfo = CNCopyCurrentNetworkInfo(interface as! CFString) as NSDictionary? {
ssid = interfaceInfo[kCNNetworkInfoKeySSID as String] as? String
break
}
}
}
return ssid
}
Get Device's IP
static func getIPAddress()->String?{
var address : String?
// Get list of all interfaces on the local machine:
var ifaddr : UnsafeMutablePointer<ifaddrs>?
guard getifaddrs(&ifaddr) == 0 else { return nil }
guard let firstAddr = ifaddr else { return nil }
// For each interface ...
for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
let interface = ifptr.pointee
// Check for IPv4 or IPv6 interface:
let addrFamily = interface.ifa_addr.pointee.sa_family
if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {
// Check interface name:
let name = String(cString: interface.ifa_name)
if name == "en0" {
// Convert interface address to a human readable string:
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)
address = String(cString: hostname)
}
}
}
freeifaddrs(ifaddr)
return address
}
¿¿Network IP address??
** Edit ** if I call ifa_netmask it returns the netmask which it 255.255.255.0 for a 192.168.4.2/24 IP
It seems that you are looking for your external IP, while your local IP is 192.168.4.1. Without the help of some external service, it is impossible ...
UPDATE see rfc1533 rfc2131 for details, try in Playground :-)
On my environment it prints
where:
option 3 represents a list of the routers
option 6 represents a list of DNS servers
option 53 means DHCP Message Type DHCPACK
option 54 means DHCP Server Identifier (where is this particular response from)
option 1 represents Subnet Mask