Search code examples
c#visual-studiosocketsdebuggingconditional-breakpoint

How to create a conditional breakpoint on a socket port?


I'm working on a C# application, working with TCP sockets. In order to do this, there are following lines of source code:

using System.Net.Sockets;
...
var sock = (Socket)ar.AsyncState;
...
if (sock.Connected)
...

I would like to have a conditional breakpoint on that last line, for the case where TCP port equals 123.
In order to achieve that, I have entered sock in the watch window, and went further in order to find the port. Once found, I do "Add watch", and the following appears in the watch window:

((System.Net.IPEndPoint)sock.RemoteEndPoint).Port

So, I've decided to use this as an entry for the conditional breakpoint:

Conditional Expression
Is true 
((System.Net.IPEndPoint)sock.RemoteEndPoint).Port == 123

However, this yields the following error message:

Breakpoint error: The condition for a breakpoint failed to execute. The condition was '((System.Net.IPEndPoint)sock.RemoteEndPoint).Port == 123'. The error returned was 'Evaluation of method System.Net.Sockets.Socket.get_RemoteEndPoint() calls into native method Interop+Sys.SetAddressFamily(byte*, int, int). Evaluation of native methods in this context is not supported.'. Click OK to stop at this breakpoint.

How can I create a conditional breakpoint for this value?


Solution

  • Have you tried int tmpPort=((System.Net.IPEndPoint)sock.RemoteEndPoint).Port;

    Then add:

    Conditional Expression
    Is true
    tmpPort == 123
    

    However, as canton7 said, we are more inclined to use an if, and then add a breakpoint in it, or use Debugger.Break() to achieve the effect.