What is the equivalent of the inet_addr function 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. Is my wrapper in C # treating this field as Int?

Can anyone help with this misunderstanding?

+2


a source to share


2 answers


You must use the IPAddress class. This bothers you a little because it tries to prevent you from depending on IP4 addresses. The Address element has been deprecated. Here's a 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 correct network order (big end).

+4


a source


Ok if it is .net I am assuming this is a small end machine, so you "can" do it like this:

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

      



I'm sure this is the right way :)

0


a source







All Articles