If we have two host with same ip on the same switch and a packet comes for that IP, then how will the switch know where to send the packet. Will it send to both hosts or only one of them, if one then why?
bdonian's answer is correct about MAC addressing, however the real-world answer is
"Unless you're doing some form of link aggregation it is an incorrect network configuration - fix it."
Multiple hosts with the same IP on the same network without proper switch configuration are an incorrect network configuration and the results are inconsistent. Many things factor into "what will happen". Generally, expect problems from inconsistent behaviour to the point of no traffic.
If you want multiple hosts sharing a single IP for fail-over or load balancing that is known by many names; bonding, trunking, link-aggregation, etc., and usually needs a switch that supports one or more of these methods. http://en.wikipedia.org/wiki/Link_aggregation
Network switches don't examine the IP of the packet; they examine the destination MAC address. Things would go something like this:
- Sending host A wants to send a packet to IP X.
- Host A sends a broadcast ARP request for IP X.
- Switch takes note of Host A's MAC address and switch port.
- Both Hosts B and C respond to the broadcast ARP request with a unicast ARP reply containing their MAC address.
- Switch takes note of Host B and C's (distinct) MAC addresses and switch ports (but not their IPs!)
- One of the two replies arrives first - assume host B.
- Host A makes a note that IP X = Host B's MAC.
- Host A sends a packet to Host B's MAC and IP X
- The ARP reply from Host C arrives. Host A may or may not overwrite the entry for IP X.
- The switch matches Host B's MAC address and forwards the packet to Host B's port.
- Host B receives the packet.
In Unix/Linux land, one host will detect the other host with the same address and simply refuse to stay on the net.
But as someone previously pointed out: if you do this, your network is broken.