Paul blog

Explaining thoughts and findings is a great way to learn

April 2009 - Posts

IP address spoofing in c# using P/Invoke

According to Wiki, the term IP (Internet Protocol) address spoofing refers to the creation of IP packets with a forged (spoofed) source IP address with the purpose of concealing the identity of the sender or impersonating another computing system. For one of my project, I needed IP spoofing. According to a requirement, I need to commutate with a device over crossover cable for configuring it. But the problem is , when device boots  up , it gets an arbitrary IP when it is operating  over crossover connection as it cannot contract with DHCP Server. My PC is in a different network from the device. So i cannot communicate with that device thru socket programming. But one thing I can do, i can search the device using some proprietary protocol and find its information like its IP.

As I can get the IP of device, if I change the pc IP according to Device IP so that they are in the same network then I will be able to communicate with the device and configure it.  AddIPAddress Function of iphlpapi.dll can be used to add a specified IPv4 address to the specified adapter and    DeleteIPAddress function can be used to delete an IP address previously added using AddIPAddress. So using these two functions you can do IP spoofing .Your real IP4 address will be changed for a very short time when you are sending the packet. Another thing to note, a network interface can hold multiple IIP address and holds it in a IP table.

The code that is used is in the following:

   1: [DllImport("iphlpapi.dll", SetLastError = true)]
   2:  static extern UInt32 AddIPAddress(UInt32 Address, UInt32 IpMask, int IfIndex, out IntPtr NTEContext, out IntPtr NTEInstance);
   3:  
   4: [DllImport("iphlpapi.dll", SetLastError = true)]
   5: static extern UInt32 DeleteIPAddress(IntPtr NTEContext);
   6:  
   7:  static IntPtr ptrNteContext = new IntPtr(0);
   8:  
   9: public static UInt32 AddIPAddressToInterface(string ipAddress, string subnetMask, int ifIndex)
  10: {
  11:   System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(ipAddress);
  12:   System.Net.IPAddress subNet = System.Net.IPAddress.Parse(subnetMask);
  13:   unsafe
  14:   {
  15:       int nteContext = 0;
  16:       int nteInstance = 0;
  17:       ptrNteContext = new IntPtr(nteContext);
  18:       IntPtr ptrNteInstance = new IntPtr(nteInstance);
  19:       return AddIPAddress(IpAddressToUInt32(ipAdd), IpAddressToUInt32(subNet), ifIndex, out ptrNteContext, out ptrNteInstance);
  20:   }
  21: }
  22:  
  23: public static void  DeletePreviouslyAddedIP()
  24: {
  25:   DeleteIPAddress(ptrNteContext);
  26: }
Posted: 04-24-2009 1:19 PM by Razan | with no comments
Filed under: , ,
Testing whether two IP addresses are in the same network using c#.

IPv4 address has two basic parts:  the network part and the host part. As we know, if network potions of two IPs are same, they are in the same network. By performing and operation between subnet mask and IP address, we can get the network portion of an IP. By this way, we have found the network portions of two IPs. Then just check whether the network portions are equal or not. For this the following code is written:

   1: private static bool CheckWhetherInSameNetwork(string firstIP, string subNet, string secondIP )
   2:    {
   3:        uint subnetmaskInInt = ConvertIPToUint(subNet);
   4:        uint firstIPInInt = ConvertIPToUint(firstIP);
   5:        uint secondIPInInt = ConvertIPToUint(secondIP);
   6:        uint networkPortionofFirstIP = firstIPInInt & subnetmaskInInt;
   7:        uint networkPortionofSecondIP = secondIPInInt & subnetmaskInInt;
   8:        if (networkPortionofFirstIP == networkPortionofSecondIP)
   9:            return true;
  10:        else
  11:            return false;
  12:    }
  13:  
  14:    static public uint ConvertIPToUint(string ipAddress)
  15:    {
  16:        System.Net.IPAddress iPAddress = System.Net.IPAddress.Parse(ipAddress);
  17:        byte[] byteIP = iPAddress.GetAddressBytes();
  18:        uint ipInUint = (uint)byteIP[3] << 24;
  19:        ipInUint += (uint)byteIP[2] << 16;
  20:        ipInUint += (uint)byteIP[1] << 8;
  21:        ipInUint += (uint)byteIP[0];
  22:        return ipInUint;
  23:    }

Hope this will save some of your time.

Posted: 04-22-2009 2:14 PM by Razan | with no comments
Filed under: ,
Finding subnet mask from IP4 address using c#.

IP4 addresses are categorized into 5 classes. For the  first three classes we have predefined subnet mask. So if we can detect the class of an IP address , we can determine the corresponding subnet mask. The address ranges used for each class are given in the following table (Taken from wiki):

Class

Leading bits

Start

End

CIDR
suffix

Default
subnet mask

Class A

    0

    0.0.0.0

127.255.255.255

   /8

255.0.0.0

Class B

    10

128.0.0.0

191.255.255.255

   /16

255.255.0.0

Class C

    110

192.0.0.0

223.255.255.255

   /24

255.255.255.0

Class D

    1110

224.0.0.0

239.255.255.255

   /4

not defined

Class E

    1111

240.0.0.0

255.255.255.255

   /4

not defined

To implement so, a class named IPClassTester has been written. The class has two methods: ReturnSubnetmask, ReturnFirtsOctet. The first one takes an IP address and return its corresponding subnet mask. For this it first extracts the first octet of the IP address using the method named ReturnFirtsOctet and then checks the first octet value with the IP4 class information and returns the corresponding subnet mask on match.

   1: class IPClassTester
   2: {
   3:    static public string ReturnSubnetmask(String ipaddress)
   4:    {
   5:       uint firstOctet =  ReturnFirtsOctet(ipaddress);
   6:       if (firstOctet >= 0 && firstOctet <= 127)
   7:           return "255.0.0.0";
   8:       else if (firstOctet >= 128 && firstOctet <= 191)
   9:           return "255.255.0.0";
  10:       else if (firstOctet >= 192 && firstOctet <= 223)
  11:           return "255.255.255.0";
  12:       else return "0.0.0.0";
  13:    }
  14:  
  15:    static public uint  ReturnFirtsOctet(string ipAddress)
  16:    {
  17:        System.Net.IPAddress iPAddress = System.Net.IPAddress.Parse(ipAddress);
  18:        byte[] byteIP = iPAddress.GetAddressBytes();
  19:        uint ipInUint = (uint)byteIP[0];     
  20:        return ipInUint;
  21:    }
  22: }

Hope this will save some of your time.

Posted: 04-22-2009 2:07 PM by Razan | with no comments
Filed under: ,
Some thoughts about how we can make a thread safe class library

What is Thread safety?

Thread safety is making sure that shared  data (Global/static) of a program  is modified by only one thread at a time without any deadlock, starvation, race condition so that program behaves correctly when its methods are called from multiple threads.

What is thread safe class library?

A class library consists of classes with some other stuff. Each class has one or more methods which can be called form different threads concurrently. A class library is called thread safe if every class of it is tread-safe. To be a class thread-safe it has to behave correctly when its methods are called from multiple threads.

To make a class library thread safe, you have to ensure the following two things for every class:

  1. Make sure that shared data (Global/static) is not modified by more than one thread concurrently.
  2. Ensure that there is no possibility of deadlock, Inconsistency, starvation, race condition.

Implementation Strategy 1(synchronized mechanism):

To implement requirement 1, every concurrent thread has to use some synchronized mechanism like locking when they are executing critical section of code. To ensure requirement 2, you have to make the design carefully. Implementation in this way still has problem because you have to ensure that there is no possibility of deadlock, Inconsistency, starvation, race condition.

Implementation Strategy 2(TLS):

If shared data (Global/static) doesn't need to be share between threads, you can use this strategy. In this strategy you don’t need to worry about deadlock, starvation, race condition. Thread-local storage (TLS) is a concurrent  design pattern which ensures shared data (Global/static) are allocated such that there is one instance of shared data (Global/static) per thread.

Using System.Threading namespace one can use TLS to store data that is unique to each thread in multi-threaded applications. According to MSDN the common language runtime allocates a multi-slot data store array to each process when it is created. Thread’s local storage is unique per thread and one’s thread local storage is not available to other threads. Multiple threads can use same named slot (TLS) to store their data without any conflict. Use the AllocateNamedDataSlot method to allocate a named data slot. A static variable tagged with ThreadStaticAttribute is not shared between threads .Thread static members has per-thread storage rather than per AppDomain like normal static members. Thread-relative static fields provide much better performance than data slots, and enable compile-time type checking.    

Posted: 04-04-2009 1:04 AM by Razan | with no comments |
Filed under: ,