title: Determing SNI within a TLS Handshake with JDK < 8
body: <p>I want to parse a TLS (1.1/2) Handshake and determine the SNI Information.</p>
  
  <p>JDK8 provides functionality for this. But I'd like a more straightforward and compatible version:</p>
  
  <p>I developed this chunk, but it doesn't work reliably (some browsers work, some not):</p>
  
  <pre><code>  def parseSNI(data: List[Int]): String = {
      if (data.head != 0x16) {
        println("Not TLS :-(")
        return "none"
      }
  
      if (data(1) &lt; 3 || (data(1) == 3 &amp;&amp; data(2) &lt; 1)) {
        println("SSL &lt; 3.1 so it's still not TLS")
        return "none"
      }
  
      val restLength = data(3) + data(4)
  
      val rest = data.slice(5, (4 + restLength))
  
      var current = 0
  
      var handshakeType = rest(0)
      current += 1
  
      // Check Handshake
      if (handshakeType != 0x1) {
        println("Not a ClientHello")
      }
  
      // Skip over another length
      current += 3
      // Skip over protocolversion
      current += 2
      // Skip over random number
      current += 4 + 28
      // Skip over session ID
      val sessionIDLength = rest(current)
      current += 1
      current += sessionIDLength
  
      val cipherSuiteLength = (rest(current) &lt;&lt; 8) + rest(current + 1)
      current += 2
      current += cipherSuiteLength
  
      val compressionMethodLength = (rest(current))
      current += 1
      current += compressionMethodLength
  
      if (current &gt; restLength) {
        println("no extensions")
      }
  
      var currentPos = 0
      // Skip over extensionsLength
      current += 2
  
      var hostname = ""
      while (current &lt; restLength &amp;&amp; hostname == "") {
        var extensionType = (rest(current) &lt;&lt; 8) + rest(current + 1)
        current += 2
  
        var extensionDataLength = (rest(current) &lt;&lt; 8) + rest(current + 1)
        current += 2
  
        if (extensionType == 0) {
  
          // Skip over number of names as we're assuming there's just one
          current += 2
  
          var nameType = rest(current)
          current += 1
          if (nameType != 0) {
            println("Not a hostname")
          }
          var nameLen = (rest(current) &lt;&lt; 8) + rest(current + 1)
          current += 2
  
          hostname = rest.slice(current, current + nameLen).map(x =&gt; x.toChar).mkString
        }
  
        current += extensionDataLength
      }
      hostname
  
    }
  </code></pre>
  
  <p>Anyone aware of better approach to this?</p>
  
  <p>Thank you!</p>