title: Socket KeepAlive Units
body: <p>Based on some posts here, I have written the following simple method for setting my Socket KeepAlive, and it seems to work. After I unplug my ethernet cable to break connectivity between two services, my network library can handle the 0-bytes-transferred on the SocketAsyncEventArgs Completed event and fire up a Disconnected event.</p>
  
  <p>But for some reason, I need to use hundredths of a second instead of milliseconds. All the documentation I can find on this seems to indicate I should use milliseconds.</p>
  
  <p>(edit) I have now verified that the bytes returned match with these other two methods:</p>
  
  <p><a href="http://www.codeproject.com/Articles/117557/Set-Keep-Alive-Values" rel="nofollow">http://www.codeproject.com/Articles/117557/Set-Keep-Alive-Values</a></p>
  
  <p><a href="http://social.msdn.microsoft.com/Forums/en-US/35dfb50e-1e14-40c1-af01-f359be4d6a02/how-to-set-socket-keep-alive-timeinterval-values" rel="nofollow">http://social.msdn.microsoft.com/Forums/en-US/35dfb50e-1e14-40c1-af01-f359be4d6a02/how-to-set-socket-keep-alive-timeinterval-values</a></p>
  
  <p>(edit) I have also WireSharked this and can verify that the KeepAlives are going out every 5 seconds when the interval is set to 500.</p>
  
  <p>What gives??? Did something break in the latest version of .NET?</p>
  
  <pre><code>private static byte[] GetKeepAliveOption(bool isEnabled, int keepAliveTime, int keepAliveInterval)
  {
      //time and interval are in hundredths of a second to work properly
      //12 keepalive bytes, 1st 4 for enabled, next 4 for time, next 4 for interval
      byte[] bytes = new byte[12];
  
      if (isEnabled)
      {
          bytes[0] = 1;
      }
  
      byte[] keepAliveTimeBytes = BitConverter.GetBytes(KeepAliveTime);
      Buffer.BlockCopy(keepAliveTimeBytes, 0, bytes, 4, 4);
  
      byte[] keepAliveIntervalBytes = BitConverter.GetBytes(KeepAliveInterval);
      Buffer.BlockCopy(keepAliveIntervalBytes, 0, bytes, 8, 4);
  
      return bytes;
  }
  </code></pre>