Based on my question C# IVI VISA (e.g.: NI VISA) TCP Keep Alive I tried to use EasyHook to patch how NI VISA is opening a SOCKET connection. Finally I would like to modify the keep alive settings in the ConnectHook method (not in there yet).
I've the following code:
[UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)]
delegate int ConnectDelegate(IntPtr socket, IntPtr sockaddr, int namelen);
[DllImport("ws2_32.dll", SetLastError = true, EntryPoint = "connect")]
static extern int Connect(IntPtr socket, IntPtr sockaddr, int namelen);
static int ConnectHook(IntPtr socket, IntPtr sockaddr, int namelen)
{
Console.WriteLine("SOCKET Connect");
int s = Connect(socket, sockaddr, namelen);
return s;
}
and
static void Main(string[] args)
{
string rn = "TCPIP::10.0.0.2::hislip0::INSTR";
//string rn = "TCPIP::10.0.0.2::inst0::INSTR"; // VXI-11
// Make sure ws2_32.dll is loaded
var vi = GlobalResourceManager.Open(rn) as IMessageBasedSession;
vi.Dispose();
LocalHook hook = LocalHook.Create(LocalHook.GetProcAddress("ws2_32.dll", "connect"),
new ConnectDelegate(ConnectHook),
null);
hook.ThreadACL.SetInclusiveACL(new int[] { 0 });
// Connect
vi = GlobalResourceManager.Open(rn) as IMessageBasedSession;
// IDN query
vi.RawIO.Write("*IDN?");
Console.WriteLine(vi.RawIO.ReadString());
// Sleep to monitor keep alive traffic using Wireshark
Thread.Sleep(10 * 1000);
// IDN query
vi.RawIO.Write("*IDN?");
Console.WriteLine(vi.RawIO.ReadString());
// Disconnect
vi.Dispose();
hook.Dispose();
}
The above source code is all in the same assembly (Console application). But my ConnectHook method is newer called when GlobalResourceManager.Open(rn) is running.
I'm able to run and hook the MessageBeep example from https://easyhook.github.io/tutorials/createlocalhook.html.
var client = new TcpClient(); client.Connect("10.0.0.2", 80)which loads as well the ws2_32.dll. But as well here myConnectHookmethod is never called.WSAConnectfunction instead. If that doesn't work you'll probably have to look into hooking into syscalls and seeing which is used.TcpClientis usingWSAConnectand I can hook it. But NI VISAGlobalResourceManager.Open(rn)is not usingWSAConnectand notconnect.ws2_32!WSASendI can see that this is been called by NI VISA.