Linux Transparent proxy support (part of the firewalling stuff) is designed to do exactly this.|
There are basically two "halves" to transparent proxy:
If you're doing UDP, then you might want to do this with the sendto and recvfrom system calls, in which case the source address is specified in the second 8 bytes of the socket address for the destination address in sendto and vice-versa for the source address in recvfrom.
Put another way, when you do a sendto, you put the destination address in the "to" parameter as usual, but you also put the desired source address (which is not the "usual" one) in the "to" parameter + 8 bytes. Note that you must OR in MSG_PROXY to the flags parameter for sendto/recvfrom.
Note that in order to use any of the transparent proxy features you must be root. Generally this is most useful when the host doing transparent proxy is a gateway or router of some kind, because impersonating host A when connecting to host B will only work if host B will normally try to send packets to host A through your host.