IP Address stored as 32-bit integer

Each IP address is a numeric representation of a 32 bit number, which is normally how it is retrieved from a PLC or digital drive.

In this example: 16.1.206.254 ==0x1001CEFE because:

16 10
1 01
206 CE
254 FE

There are two methods to extract the IP address from an integer:

Method 1:

UInt32 iIP = 0x1001CEFE;
arDrives[i].lNodeIP = Convert.ToInt32(iIP)
sMsg = string.Format("  IP: {0}.{1}.{2}.{3}",
                      (arDrives[i].lNodeIP >> 24) & 0xFF,
                      (arDrives[i].lNodeIP >> 16) & 0xFF,
                      (arDrives[i].lNodeIP >> 8) & 0xFF,
                       arDrives[i].lNodeIP & 0xFF);
Console.WriteLine(sMsg);

Method 2:

public void GetAddr(Int32 lAddr, ref Int32[] ip) {
       ip[3] = (lAddr / 0x1000000);
       ip[2] = (lAddr / 0x10000) % 0x100;
       ip[1] = (lAddr / 0x100) % 0x100;
       ip[0] = (lAddr % 0x100);
 }

ts.GetAddr(arDrives[i].lNodeIP, ref ip)

sMsg = string.Format("  IP: {0}.{1}.{2}.{3}",
                      ip[3],
                      ip[2],
                      ip[1],
                      ip[0]);
Console.WriteLine(sMsg);

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: