Network coding improves transmission efficiency by combining packets at relay nodes and thus reduces the number of packets sent to the network. It is a network layer solution to improve network throughput and transmission efficiency. However, a coded packet must be decodable by the destination, otherwise it is a waste of resource to combine them together and to deliver the coded packet. This paper addresses how to find the coding solution that guarantees decodability at the destination. We first quantify the coding gain as the number of transmissions reduced, and then provide a method for runtime check whether a coding pair can be separated at the destination. The optimal coding solution is selected as the one that provides the maximum coding gain among all the decodable pairs. The algorithms can be applied to both unicast and multicast traffic. Simulation results show the number of transmissions can be reduced significantly, especially for multicast traffic where there are rich opportunities to apply network coding.