Swift:如何将 IPv4 字符串地址转换为整数,反之亦然
我需要将 IP 地址(例如“127.0.0.1”)转换为整数值,反之亦然。我找到了 ObjC 的一些示例:
如何在 Swift 中执行此操作最好的方法是什么?
I need to convert IP address (e.g. "127.0.0.1") to integer value and vice-versa for my logger. I've found some samples for ObjC:
- How to convert an IP address from NSString to unsigned int in Objective-C?
- iOS convert IP Address to integer and backwards
How to do it in Swift and what the best way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这就是我处理转换的方式。它可能看起来有点过度工程,但所有属性在其他上下文中也很有用:
以下实现依赖于网络技术:
用法:
This is how I would approach the conversion. It might look a bit over engineering but all properties are useful in other contexts as well:
The following implementations rely on Network Technology:
Usage:
在 Swift 中,有两种可能的方法:
inet_aton
和inet_ntoa
Network
中的IPv4Address
如何使用:
There two possible approaches to do it in Swift:
inet_aton
andinet_ntoa
IPv4Address
fromNetwork
How to use: