我需要知道如何使用像 inet_addr("192.168.0.2"); 这样的 IP 地址在 C++ 中 其中返回 DWORD。我的 C# 包装器将此字段视为 Int?
任何人都可以帮助解决这个误解吗?
最佳答案
您应该使用 IPAddress 类。它会给你带来一些麻烦,因为它试图阻止你依赖 IP4 地址。 Address 成员已被声明为过时。解决方法如下:
using System;
using System.Net;
class Program {
static void Main(string[] args) {
var addr = IPAddress.Parse("192.168.0.2");
int ip4 = BitConverter.ToInt32((addr.GetAddressBytes()), 0);
Console.WriteLine("{0:X8}", ip4);
Console.ReadLine();
}
}
输出:0200A8C0
请注意,地址采用正确的网络顺序(大端)。
关于c++ - C# 中的 inet_addr 函数等效于什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2850815/