I am trying to get the IP Address using NSHost
. With the NSHost
object I can use the addresses method to access an array of objects one of which is the IP Address. I fear though that the IP Address may change position in the array from one machine to the other. Is there a way to access this information in a universal way?
There was an attempt to answer this question in a previous post, but as you can see it falls short.
Here is my code:
+(NSString *) ipAddress {
NSHost * h = [[[NSHost currentHost] addresses] objectAtIndex:1];
return h ;
}
I have used this on many machines without problems.
NSString *stringAddress; is declared else where
Made an utility class to find the IP addresses. Minimalistic approach. You can robustify it with more conditions or regex checking.
This is the list returned by NSHost
Test method,
IPAddress.h
IPAddress.m
As the answers to the question you mention above have said, there are a variety of IP addresses that a single machine can have. If that is what you want, then you might be better off using the
names
method of NSHost to get an array of names, which you can then filter for the suffix (i.e *.lan) to get the name of the host you want with this name. In my case. the .lan address returns my network ip address as a dotted quad.If you want to find the external ip address, then this is a good answer to look at.
My first Answer is to supply the Private IP address assigned to the Machine on private network from say your router.
If you want to see the public IP, which is the one facing the internet. Normally assigned by your service provider. You may want to look at the answer by Jim Dovey --> here
I tested it and it worked well, but read the rest of the comments and answers which point to ambiguities in trying to get a public IP.
The only thing I can think of is to use something like "http://www.dyndns.org/cgi-bin/check_ip.cgi" others may have a better way.
This is an example,(i.e a quick cobbled together code)
I wanted to update my original answer on getting an external ip.
There is not much change but I wanted to show how to get and parse the HTML with use NSXMLDocument and Xquary
This also gives a small illustration of how you can parse HTML by getting the nodes. Which in my opinion is more straight forward. Although NSXMLDocument is initially for XML it will parse the HTML DOM tree