简体   繁体   中英

What is the inet_addr function equivalent in C#

i need to know how to use an IP address like inet_addr("192.168.0.2"); in C++ where this returns DWORD. My wrapper in C# treats this field as an Int?

Can anyone help on this misunderstanding?

You should use the IPAddress class. It will hassle you a bit because it tries to prevent you from taking a dependency on IP4 addresses. The Address member is declared obsolete. Here is the workaround:

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();
    }
}

Output: 0200A8C0

Note that the address is in proper network order (big endian).

Well if it .net I assume its a little endian machine so you "could" do it as follows:

address = (192 << 0) | (168 << 8) | (0 << 16) | (2 << 24);

I'm pretty sure thats the right way round :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM