Tutorial :How do I get the external ip address with NSHost?



Question:

I'm trying to find my external IP address, but I get local ones only, behind the NAT.

NSArray *addresses = [[NSHost currentHost] addresses];  

Is there a way to print out the public address? Using NSHost is it a good idea?


Solution:1

There may not always be a reliable way to get at your public IP, but the DNSService API in OS X will use UPnP and/or the NAT port mapping protocol to get the public IP (amongst other things). The code illustrating how to use the C API would be a bit large (50-60 lines) to show here, but there's some Apple sample code which implements a nice ObjC wrapper around the functionality, and even offers a pair of functions to directly return UInt32 and NSString representations of the public IP address.

The relevant code itself is located here, but you're probably best off just downloading the zip file and including PortMapper.h and PortMapper.m in your project and using them directly. Then all you'd need to do is:

NSString * publicAddressString = [PortMapper findPublicAddress];  


Solution:2

If you ever get to look at a network topology chart for a major organization, do so. It's enlightening. The whole point of NAT, firewalls and all that other "black magic" is to allow the network to manage addresses (including protecting you) without your knowledge.

There are only three ways in which I've been able to reliably (and reliable is a relative concept here) get the external-facing IP address of a server.

The first is to as the network gods themselves (and make sure you refer to them as gods when asking, this will assist you in getting the information). Sometimes (not always), it's a simple mapping of the top bytes of your IP address whilst retaining the low-order bytes. Sometimes it's more complex, but still follows rules that you can use. Just keep in mind these rules can change at any time.

The second is to have a box outside of your network which you can query and it, in turn, can let you know your IP address.

The third is to specifically attach to an outside DNS server (not your corporate one) to retrieve the information.

Of course, you should question the need to know your external IP address. The whole point of DNS is to avoid having to worry too much about IP addresses and just refer to machines by the domain names.


Solution:3

There is no reliable way to get your public IP. Depending on your network topology, you may not be able to depend on the outgoing address for a number of reasons: IP address pools, dynamic routes, multiple layers of NAT, proxy servers, etc.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »