ios - 如何在 Objective-C 中将 IP 地址从 NSString 转换为 unsigned int?
<p><p>如何在Objective-C中将IP地址从<strong><code>NSString</code></strong>转换为<strong><code>unsigned int</code></strong>?</p >
<pre><code>NSString A = "192.168.43.149"
</code></pre>
<p>我尝试将其转换为 <strong><code>unsigned int</code></strong>,如下所示:</p>
<pre><code>unsigned int ip;
ip = (unsigned int);
</code></pre>
<p>或</p>
<pre><code>sscanf(, "%u", &ip);
</code></pre>
<p>结果总是只显示 <strong><code>192</code></strong>。</p>
<p>我希望它显示 <strong><code>0xc0a82b95</code></strong></p>
<p>如何在Objective-C中将IP地址从<strong><code>NSString</code></strong>转换为<strong><code>unsigned int</code></strong>?</p >
<p>提前致谢。</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>对于 IPv4 地址,您可以使用 <code>inet_aton()</code>,它将字符串转换为 Internet
地址:</p>
<pre><code>#include <arpa/inet.h>
NSString *addrString = @"192.168.43.149";
struct in_addr addr;
if (inet_aton(, &addr) != 0) {
uint32_t ip = ntohl(addr.s_addr);
NSLog(@"%08x", ip);
} else {
NSLog(@"invalid address");
}
// Output: c0a82b95
</code></pre></p>
<p style="font-size: 20px;">关于ios - 如何在 Objective-C 中将 IP 地址从 NSString 转换为 unsigned int?,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/26927759/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/26927759/
</a>
</p>
页:
[1]