2

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?

3
  • What are you trying to do exactly? C# already has wrappers around the entire IP stack -- you shouldn't need to be P/Invoking those. May 17, 2010 at 16:34
  • I have a wrapper in a C++ library, i just read the documentation to use the library, but the examples are in C++ code, which i dont understand quite enough in some places. On place is this while setting an IP Address to a DWORD type field where my wrapper has as int field. So i wonder how to convert the IP Address string (etc. "192.168.0.2") and set it to the int field. May 17, 2010 at 17:06
  • It might help your question if you showed us the C++ code and the C# code where you're stuck. May 17, 2010 at 17:22

2 Answers 2

4

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).

0
0

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 :)

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.