如何获得外部IP地址与NSHost? [英] How do I get the external ip address with NSHost?

查看:223
本文介绍了如何获得外部IP地址与NSHost?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到我的外部IP地址,但我只获得本地的IP地址,在NAT后面。

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

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

有没有办法打印公共地址?使用NSHost是一个好主意吗?

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

推荐答案

可能不会有一个可靠的方法来获取你的公共IP, OS X中的DNSService API将使用UPnP和/或NAT端口映射协议来获得公共IP(除此之外)。说明如何使用C API的代码将在这里显示一个有点大(50-60行),但有一些Apple示例代码实现了一个好的ObjC包装器的功能,甚至提供一对函数直接返回UInt32和NSString表示公共IP地址。

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.

相关代码本身位于这里,但你可能最好只是下载zip文件,包括PortMapper.h和PortMapper.m在你的项目中,并直接使用它们。然后你需要做的是:

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];

这篇关于如何获得外部IP地址与NSHost?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆