.NET Fiddle

CSharp · Console

/Program.cs

using System;
using System.Runtime.InteropServices;

 //The Struct needs to be annotated as "Explicit Layout", like this:
 [System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit)]
 struct IpAddress
 {
   //The "FieldOffset:" means that this Integer starts 
   //a offset 0, in bytes, (with sizeof(int) = 4 bytes length): 
   [System.Runtime.InteropServices.FieldOffset(0)]
   public int intAddress;

   //Offset 0, (length sizeof(byte) = 1 byte)...   
   [System.Runtime.InteropServices.FieldOffset(0)]
   public byte Byte1;

   //Offset 1, (length sizeof(byte) = 1 byte)...     
   [System.Runtime.InteropServices.FieldOffset(1)]
   public byte Byte2;

   //Offset 2, (length sizeof(byte) = 1 byte)...   
   [System.Runtime.InteropServices.FieldOffset(2)]
   public byte Byte3;
     
   //Offset 3, (length sizeof(byte) = 1 byte)...    
   [System.Runtime.InteropServices.FieldOffset(3)]
   public byte Byte4;     
     
   public IpAddress(int address) {
         //All elements have to be initialized. it is a good idea to initialize the 
         //ones not being explicitly set first.
         Byte1 = Byte2 = Byte3 = Byte4 = 0;

         //Now, when we init the Int, the Bytes will change too.
         //If we had done this backwards, it would zero out the intAddress. 
         intAddress = address;
   }
     
     //Now we can use the explicit layout to access the 
     //bytes separately, without doing any conversion
     public override string ToString() {
         
         return (new System.Text.StringBuilder()).Append(Byte1).Append('.')
                 .Append(Byte2).Append('.')
                 .Append(Byte3).Append('.')
                 .Append(Byte4).Append('.').ToString();
             
     }
 }


public class MainClass { 

	public static void Main()
    {
     var ip = new IpAddress((new Random()).Next());
     Console.Out.WriteLine(ip + "\t= " + ip.intAddress);
     ip.Byte1 = 100;
     Console.Out.WriteLine(ip + "\t= " + ip.intAddress);
    }	
	
}
;