How to Get My Ip Address Programmatically on Ios/Macos

how to get ip address of iphone programmatically

#include <ifaddrs.h>
#include <arpa/inet.h>

// Get the INTERNAL ip address

- (NSString *)getIPAddress {

NSString *address = @"error";
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;
// retrieve the current interfaces - returns 0 on success
success = getifaddrs(&interfaces);
if (success == 0) {
// Loop through linked list of interfaces
temp_addr = interfaces;
while(temp_addr != NULL) {
if(temp_addr->ifa_addr->sa_family == AF_INET) {
// Check if interface is en0 which is the wifi connection on the iPhone
if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
// Get NSString from C String
address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];

}

}

temp_addr = temp_addr->ifa_next;
}
}
// Free memory
freeifaddrs(interfaces);
return address;

}

https://web.archive.org/web/20160527165909/http://www.makebetterthings.com/iphone/how-to-find-ip-address-of-iphone/

How to get the public IP address of the device

I have used ALSystemUtilities in the past. You basically have to make a call externally to find this out.

+ (NSString *)externalIPAddress {
// Check if we have an internet connection then try to get the External IP Address
if (![self connectedViaWiFi] && ![self connectedVia3G]) {
// Not connected to anything, return nil
return nil;
}

// Get the external IP Address based on dynsns.org
NSError *error = nil;
NSString *theIpHtml = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.dyndns.org/cgi-bin/check_ip.cgi"]
encoding:NSUTF8StringEncoding
error:&error];
if (!error) {
NSUInteger an_Integer;
NSArray *ipItemsArray;
NSString *externalIP;
NSScanner *theScanner;
NSString *text = nil;

theScanner = [NSScanner scannerWithString:theIpHtml];

while ([theScanner isAtEnd] == NO) {

// find start of tag
[theScanner scanUpToString:@"<" intoString:NULL] ;

// find end of tag
[theScanner scanUpToString:@">" intoString:&text] ;

// replace the found tag with a space
//(you can filter multi-spaces out later if you wish)
theIpHtml = [theIpHtml stringByReplacingOccurrencesOfString:
[ NSString stringWithFormat:@"%@>", text]
withString:@" "] ;
ipItemsArray = [theIpHtml componentsSeparatedByString:@" "];
an_Integer = [ipItemsArray indexOfObject:@"Address:"];
externalIP =[ipItemsArray objectAtIndex:++an_Integer];
}
// Check that you get something back
if (externalIP == nil || externalIP.length <= 0) {
// Error, no address found
return nil;
}
// Return External IP
return externalIP;
} else {
// Error, no address found
return nil;
}
}

Source from ALSystemUtilities

How to get Ip address in swift

As it turned out in the discussion, OP needs the interface address on a Mac and not on an iOS device as I thought initially. The code referenced in the question checks for the
interface name "en0", which is the WiFi interface on the iPhone. On a Mac it makes more
sense to check for any "up-and-running" interface instead.
Therefore I have rewritten the answer. It is now a Swift translation of the code in
Detect any connected network.


getifaddrs() is defined in <ifaddrs.h>, which is not included by default.
Therefore you have to create a bridging header and add

#include <ifaddrs.h>

The following function returns
an array with the names of all local "up-and-running" network interfaces.

func getIFAddresses() -> [String] {
var addresses = [String]()

// Get list of all interfaces on the local machine:
var ifaddr : UnsafeMutablePointer<ifaddrs> = nil
if getifaddrs(&ifaddr) == 0 {

// For each interface ...
var ptr = ifaddr
while ptr != nil {
defer { ptr = ptr.memory.ifa_next }

let flags = Int32(ptr.memory.ifa_flags)
let addr = ptr.memory.ifa_addr.memory

// Check for running IPv4, IPv6 interfaces. Skip the loopback interface.
if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING) {
if addr.sa_family == UInt8(AF_INET) || addr.sa_family == UInt8(AF_INET6) {

// Convert interface address to a human readable string:
var hostname = [CChar](count: Int(NI_MAXHOST), repeatedValue: 0)
if (getnameinfo(ptr.memory.ifa_addr, socklen_t(addr.sa_len), &hostname, socklen_t(hostname.count),
nil, socklen_t(0), NI_NUMERICHOST) == 0) {
if let address = String.fromCString(hostname) {
addresses.append(address)
}
}
}
}
}
freeifaddrs(ifaddr)
}

return addresses
}

Update for Swift 3: In addition to adopting the code to the
many changes in Swift 3,
iterating over all interfaces can now use the new generalized
sequence() function:

func getIFAddresses() -> [String] {
var addresses = [String]()

// Get list of all interfaces on the local machine:
var ifaddr : UnsafeMutablePointer<ifaddrs>?
guard getifaddrs(&ifaddr) == 0 else { return [] }
guard let firstAddr = ifaddr else { return [] }

// For each interface ...
for ptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
let flags = Int32(ptr.pointee.ifa_flags)
let addr = ptr.pointee.ifa_addr.pointee

// Check for running IPv4, IPv6 interfaces. Skip the loopback interface.
if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING) {
if addr.sa_family == UInt8(AF_INET) || addr.sa_family == UInt8(AF_INET6) {

// Convert interface address to a human readable string:
var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
if (getnameinfo(ptr.pointee.ifa_addr, socklen_t(addr.sa_len), &hostname, socklen_t(hostname.count),
nil, socklen_t(0), NI_NUMERICHOST) == 0) {
let address = String(cString: hostname)
addresses.append(address)
}
}
}
}

freeifaddrs(ifaddr)
return addresses
}

Swift - Get device's WIFI IP Address

According to several SO threads (e.g. What exactly means iOS networking interface name? what's pdp_ip ? what's ap?), the WiFi interface on an iOS device always has then name "en0".

Your code (which seems to be what I answered at How to get Ip address in swift :) retrieves a list of the IP addresses of all running network interfaces. It can easily be modified to return only the IP address
of the "en0" interface, and actually that is what I originally had
answered at that thread (and this is just a Swift translation of the
answer to how to get ip address of iphone programmatically):

// Return IP address of WiFi interface (en0) as a String, or `nil`
func getWiFiAddress() -> String? {
var address : String?

// Get list of all interfaces on the local machine:
var ifaddr : UnsafeMutablePointer<ifaddrs> = nil
if getifaddrs(&ifaddr) == 0 {

// For each interface ...
var ptr = ifaddr
while ptr != nil {
defer { ptr = ptr.memory.ifa_next }

let interface = ptr.memory

// Check for IPv4 or IPv6 interface:
let addrFamily = interface.ifa_addr.memory.sa_family
if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {

// Check interface name:
if let name = String.fromCString(interface.ifa_name) where name == "en0" {

// Convert interface address to a human readable string:
var hostname = [CChar](count: Int(NI_MAXHOST), repeatedValue: 0)
getnameinfo(interface.ifa_addr, socklen_t(interface.ifa_addr.memory.sa_len),
&hostname, socklen_t(hostname.count),
nil, socklen_t(0), NI_NUMERICHOST)
address = String.fromCString(hostname)
}
}
}
freeifaddrs(ifaddr)
}

return address
}

Usage:

if let addr = getWiFiAddress() {
print(addr)
} else {
print("No WiFi address")
}

Update for Swift 3: In addition to adopting the code to the
many changes in Swift 3,
iterating over all interfaces can now use the new generalized
sequence() function:

Do NOT forget to add #include <ifaddrs.h> in your bridging header

// Return IP address of WiFi interface (en0) as a String, or `nil`
func getWiFiAddress() -> 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
}

For those of you who came looking for more than the WIFI IP you could modify this code a little

func getAddress(for network: Network) -> 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 == network.rawValue {

// 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
}
enum Network: String {
case wifi = "en0"
case cellular = "pdp_ip0"
//... case ipv4 = "ipv4"
//... case ipv6 = "ipv6"
}

Then we have access to the cellular IP as well.

guard let wifiIp = getAddress(for: .wifi) else { return }

&

guard let cellularIp = getAddress(for: .cellular) else { return }

How to get IPhone's Public IP Address without using a third party url

import Darwin

var hostName = [Int8](count: 255, repeatedValue: 0)
gethostname(&hostName, hostName.count)

var hints = addrinfo()
var res = UnsafeMutablePointer<addrinfo>()
var p = UnsafeMutablePointer<addrinfo>()
var p4 = UnsafeMutablePointer<sockaddr_in>()
var p6 = UnsafeMutablePointer<sockaddr_in6>()

hints.ai_flags = AI_ALL
hints.ai_family = PF_UNSPEC
hints.ai_socktype = SOCK_STREAM
var ipstr = [CChar](count: Int(INET6_ADDRSTRLEN), repeatedValue: 0)

print("List of IP addresses on host \(String.fromCString(hostName)!)\n")

if getaddrinfo( hostName, "0", &hints, &res) == 0 {

var ipFamily = ""
var s: Int32 = 0
var port: in_port_t = 0
for(p = res; p != nil; p = p.memory.ai_next) {

switch p.memory.ai_family {
case PF_INET:
p4 = UnsafeMutablePointer<sockaddr_in>(p.memory.ai_addr)
inet_ntop(AF_INET, &p4.memory.sin_addr, &ipstr, socklen_t(INET6_ADDRSTRLEN))
ipFamily = "IPv4"
port = p4.memory.sin_port.bigEndian
case PF_INET6:
p6 = UnsafeMutablePointer<sockaddr_in6>(p.memory.ai_addr)
inet_ntop(AF_INET6, &p6.memory.sin6_addr, &ipstr, socklen_t(INET6_ADDRSTRLEN))
ipFamily = "IPv6"
port = p6.memory.sin6_port.bigEndian
default:

break
}
print("\t\(ipFamily):", String.fromCString(ipstr)!)

}
// free unmanaged memmory !!!!!
freeaddrinfo(res)
}

prints on my own computer

List of IP addresses on host Ivos-MacBook.local

IPv6: fe80::225:ff:fe40:9c72
IPv6: 2a02:130:200:1350:225:ff:fe40:9c72
IPv4: 192.168.1.106

for external IP, you need help of external service (not swift specific :-))

iPad: How to get Ethernet IP address programmatically

en2 interface.

Add:

[[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en2"]

to the first solution in
iPhone/iPad/OSX: How to get my IP address programmatically? to also get the device's IP address through wired connection.

UPDATE: Just expanding on @Raptor's solution linked above; this will return both wired and wireless IP Address, if both or either is present. Then just check the return dictionary's values' lengths to see what you're working with.

#import <ifaddrs.h>
#import <arpa/inet.h>

+ (NSDictionary *)getBothIPAddresses {
const NSString *WIFI_IF = @"en0";
NSArray *KNOWN_WIRED_IFS = @[@"en1",@"en2",@"en3",@"en4"];
NSArray *KNOWN_CELL_IFS = @[@"pdp_ip0",@"pdp_ip1",@"pdp_ip2",@"pdp_ip3"];

const NSString *UNKNOWN_IP_ADDRESS = @"";

NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithDictionary:@{@"wireless":UNKNOWN_IP_ADDRESS,
@"wired":UNKNOWN_IP_ADDRESS,
@"cell":UNKNOWN_IP_ADDRESS}];

struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;
// retrieve the current interfaces - returns 0 on success
success = getifaddrs(&interfaces);
if (success == 0) {
// Loop through linked list of interfaces
temp_addr = interfaces;
while(temp_addr != NULL) {
if (temp_addr->ifa_addr == NULL) {
temp_addr = temp_addr->ifa_next;
continue;
}
if(temp_addr->ifa_addr->sa_family == AF_INET) {
// Check if interface is en0 which is the wifi connection on the iPhone
if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:WIFI_IF]) {
// Get NSString from C String
[addresses setObject:[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)] forKey:@"wireless"];

}
// Check if interface is a wired connection
if([KNOWN_WIRED_IFS containsObject:[NSString stringWithUTF8String:temp_addr->ifa_name]]) {
[addresses setObject:[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)] forKey:@"wired"];
}
// Check if interface is a cellular connection
if([KNOWN_CELL_IFS containsObject:[NSString stringWithUTF8String:temp_addr->ifa_name]]) {
[addresses setObject:[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)] forKey:@"cell"];
}
}

temp_addr = temp_addr->ifa_next;
}
}
// Free memory
freeifaddrs(interfaces);

return addresses;
}

UPDATE:
en3 interface, another possibility; seems to depend on the type of adapter. Makes me think there could be more interfaces that I'm still missing based on hardware being used, so please comment if anyone discovers more.

UPDATE:
en4 as well; doesn't necessarily depend on adapter like I originally thought, because a Mini with all the same hardware at one point decided to switch from one interface to this new one. Also, I'm starting to think it may be easier to just compare the ifa_name to any string with a format of en[2..n], so long as it's in the AF_INET family (for example, en1 is NOT and doesn't return an address we're looking for); it's likely premature to implement something like that for Prod without more proof, so for now I manage with a list of 'known' wired interfaces.

UPDATE:
Considers cellular AF_INET interfaces too, mentioned in What exactly means iOS networking interface name? what's pdp_ip ? what's ap?

UPDATE:
Ethernet IP addresses have begun showing up on the en1 interface lately on certain new iPads, so it should also be considered when it's a member of the AF_INET family. No distinguishable rhyme or reason, it happens with varying iPad models and iOS versions.

iOS Swift: find Macbook Computer Name/Ip Address on connected Iphone

What I've experienced is that if you're building an Xcode project on an iOS device, and then run the project with the debugger attached, it routes all of the iOS device's networking through your computer. So it will only show your computer's IP address, not the device's. It looks in the debugger as if that's your iPhone's networking info, but it's really your computer's.

Get All of Mac's IP Addresses Using Objective-C

The answer here is that I am an idiot. As suggested by Rob Napier in their comment on my question, I was essentially filtering out the missing IP addresses:

NSString *key = [NSString stringWithFormat:@"%@/%@", name, type];
addresses[key] = [NSString stringWithUTF8String:addrBuf];

Each interface can have more than one IP address, but I since I was using the interface type as the unique key in my addresses dictionary, only one IP address per interface was present in the dictionary. I fixed this by returning an array of dictionaries rather than a single dictionary:

if (![[NSString stringWithFormat:@"%s", addrBuf] hasPrefix:@"fe80"])
{
NSDictionary *addressDict = [NSDictionary dictionaryWithObjectsAndKeys :
[NSString stringWithFormat:@"%@/%@", name, type], @"Interface",
[NSString stringWithFormat:@"%s", addrBuf], @"Address",
nil];

[addresses addObject:addressDict];
}

return addresses;


Related Topics



Leave a reply



Submit