Issue
I have a userspace C++ application (could be a library) processing packets.
I have a second application (written in C) which obtains bytes via calling ::recv()
.
- Is it possible to "deliver" the processed packet bytes to the second application, without changing the code calling
::recv()
? - I'd also like to "divert" calls from
::send()
to the first application. I think I can do this using a dynamic library andLD_PRELOAD
, but is it possible to do via a static technique?
Solution
As I understand, you want to be able to run any unmodified program in a special mode where all its sockets get connected to your own program which emulates the network, instead of the actual network. This is to help develop some custom networking code.
Perhaps the simplest way to do this is with LD_PRELOAD - a mechanism that is often used for overriding standard library functions.
You can make a shared library with function names like recv
and send
, and anything else you need to override, and then set the environment variable LD_PRELOAD=my_socket_library.so
(change it to the actual filename) when running the second program. The loader will link recv
and send
calls to your functions instead of the ones in libc, because LD_PRELOAD libraries take priority. If you want to call the original functions you can use dlsym
iwth RTLD_NEXT
to get pointers to them (out of scope; Google for more information).
Alternatively, you might prefer to make it a real socket, connected to your networking program. Your networking program would listen on some port (using the kernel networking system) and your shared library would override the connect
function so it connects to the port where the networking program was listening, then tells the networking program the address. Unless the program uses getpeername
to see the address it's connected to (and most programs don't, because they already know which address they connected to) it won't know the difference, but since it's a real socket it would work no matter what socket stuff the the program did.
Answered By - user253751 Answer Checked By - Mildred Charles (WPSolving Admin)