How to get external IP address using NSHost?

I am trying to find my external IP address, but I only get local ones for NAT.

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

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

+2
objective-c cocoa
source share
3 answers

There may not always be a reliable way to access your public IP address, but the DNSService API on OS X will use the UPnP mapping protocol and / or NAT to obtain a public IP address (among other things). The code illustrating how to use the C API will be a bit large (50-60 lines) to show here, but there are some examples of Apple code that implement the beautiful ObjC wrapper around functionality and even offer a couple of functions to directly return UInt32 and NSString for public IP addresses

The corresponding code is here , but you are probably best off just downloading the zip file and including PortMapper.h and PortMapper. m in your project and use them directly. Then all you have to do is:

 NSString * publicAddressString = [PortMapper findPublicAddress]; 
+11
source share

If you ever take a look at the network topology diagram for a large organization, do it. This is enlightenment. All NAT point, firewalls and all this "black magic" allow the network to manage addresses (including protecting you) without your knowledge.

There are only three ways in which I could reliably (and reliably relative concept here) get the external address of the server IP address.

Firstly, as the gods of the network themselves (and make sure that you refer to them as gods when you ask, this will help you in obtaining information). Sometimes (not always) this is a simple mapping of the upper bytes of your IP address, while preserving the lower order bytes. Sometimes it's harder, but still follows the rules you can use. Just keep in mind that these rules are subject to change at any time.

Secondly, you have a field outside your network that you can request, and it, in turn, can tell you your IP address.

The third is to specifically connect an external DNS server (and not corporate) to receive information.

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

+2
source share

There is no reliable way to get your public IP address. Depending on the topology of your network, you will not be able to depend on the outgoing address for several reasons: IP address pools, dynamic routes, several NAT levels, proxies, etc.

+1
source share

All Articles