title: client side socket security using ssl in android
body: <p>I am working on php socket server side using ssl security layer, It is working fine from php client side, now <strong>i want to connect my server with android client with ssl security layer</strong>. I am not getting any helpful solution which can connect with my php server through android client with ssl Authentication </p>
  
  <p><em>My PHP <strong>server.php</strong> side code is given below</em></p>
  
  <pre><code>&lt;?php
  
  $ip="000.000.00.00";               //Set the TCP IP Address to listen on
  $port="****";                      //Set the TCP Port to listen on
  $pem_passphrase = "password";      //Set a password here
  $pem_file = "filename.pem";        //Set a path/filename for the PEM SSL Certificate which will be created.
  
  $forkedSocket;
  
  //The following array of data is needed to generate the SSL Cert
  $pem_dn = array(
   "countryName" =&gt; "IN",                     //Set your country name
   "stateOrProvinceName" =&gt; "State",          //Set your state or province name
   "localityName" =&gt; "City",                 //Set your city name
   "organizationName" =&gt; "Orgnization",      //Set your company name
   "organizationalUnitName" =&gt; "unit",       //Set your department name
   "commonName" =&gt; "hostname",               //Set your full hostname.
   "emailAddress" =&gt; "email@email.com"       //Set your email address
  );
  
  //create ssl cert for this scripts life.
  
  echo "Creating SSL Cert\n";
  createSSLCert($pem_file, $pem_passphrase, $pem_dn);
  
  //setup and listen to a tcp IP/port, returning the socket stream
  
  echo "Listening to {$ip}:{$port} for connections\n";
  $socket = setupTcpStreamServer($pem_file, $pem_passphrase, $ip, $port);
  
  
  while(true){
  
  //Accept any new connections 
  
    $forkedSocket = stream_socket_accept($socket, "-1", $remoteIp);
  
   echo "New connection from $remoteIp\n";
  
   //start SSL on the connection
  
   stream_set_blocking ($forkedSocket, true);         // block the connection until SSL is done.
   stream_socket_enable_crypto($forkedSocket, true,     STREAM_CRYPTO_METHOD_SSLv3_SERVER);
  
  
  
  //enter a loop until an exit command is received.
  
  $exit=false;
   $i=1;
  
  while($exit==false) {
  
  
   //Read the command from the client. This will read 8192 bytes of data, If     you need to read more you may need to increase this. However some systems will fragment the command over 8192 anyway, so you would instead need to write a loop waiting for the command input to end before proceeding.
   $command = fread($forkedSocket, 8192);
  
   echo "f_read success--".$command;
  
   //unblock connection
   stream_set_blocking ($forkedSocket, false);
  
   //run a switch on the command to determine what we need to do
  
  switch($command) {
  
    CASE "exit";
  
  
     $exit=true;
     echo "exit command received \n";
  
     fwrite($forkedSocket, "exit.... {$remoteIp}. -- $i finished connection"     
   );
  
     //close the connection to the client  
  
   fclose($forkedSocket);
    break;
  
  
    default ;
  
     //write back to the client a response.
     fwrite($forkedSocket, "Hello {$remoteIp}. This is our $i command     run!".$command );
     $i++;
  
         if($i==25){
  
         $exit=true;
     }
  
     echo "command received \n";
  
    break;
   }
  
  
  }
  
  }
  
  
  
  function createSSLCert($pem_file, $pem_passphrase, $pem_dn) {
  
  //create ssl cert for this scripts life.
  
   //Create private key
   $privkey = openssl_pkey_new();
  
   //Create and sign CSR
   $cert    = openssl_csr_new($pem_dn, $privkey);
   $cert    = openssl_csr_sign($cert, null, $privkey, 365);
  
   //Generate PEM file
   $pem = array();
   openssl_x509_export($cert, $pem[0]);
   openssl_pkey_export($privkey, $pem[1], $pem_passphrase);
   $pem = implode($pem);
  
   //Save PEM file
   file_put_contents($pem_file, $pem);
   chmod($pem_file, 0600);
  }
  
  function setupTcpStreamServer($pem_file, $pem_passphrase, $ip, $port) {
  //setup and listen to a tcp IP/port, returning the socket stream
  
   //create a stream context for our SSL settings
   $context = stream_context_create();
  
   //Setup the SSL Options
   stream_context_set_option($context, 'ssl', 'local_cert', $pem_file);      // Our SSL Cert in PEM format
   stream_context_set_option($context, 'ssl', 'passphrase', $pem_passphrase);         // Private key Password
   stream_context_set_option($context, 'ssl', 'allow_self_signed', true);
   stream_context_set_option($context, 'ssl', 'verify_peer', false);
  
   //create a stream socket on IP:Port
   $socket = stream_socket_server("tcp://{$ip}:{$port}", $errno, $errstr,     STREAM_SERVER_BIND|STREAM_SERVER_LISTEN, $context);
   stream_socket_enable_crypto($socket, false);
  
   return $socket;
  }
  ?&gt;
  </code></pre>
  
  <p><em>and My <strong>Android CLient side</strong> code is</em></p>
  
  <pre><code>    SocketFactory sf = SSLSocketFactory.getDefault();
  
          SSLSocket socket = null;
          // socket = (SSLSocket) 
          socket = (SSLSocket) sf.createSocket("000.000.00.00", 0000);
  
          socket.addHandshakeCompletedListener(new HandshakeCompletedListener() {
              @Override
              public void handshakeCompleted(HandshakeCompletedEvent event) {
  
                  Log.e("logMessage", "handshake completed...");
  
              }
          });
          if (socket.getEnableSessionCreation()) {
  
              HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
              SSLSession s = socket.getSession();
  
  
              if (!hv.verify("000.000.00.00", s)) {
  
                  Log.e("logMessage", "Failed....");
  
           //                    throw new SSLHandshakeException("Expected mail.google.com, found " + s.getPeerPrincipal());
                  throw new SSLHandshakeException("Expected 000.000.00.00, found " + s.getPeerPrincipal());
  
              } else {
                  //Toast.makeText(context, "verified", Toast.LENGTH_SHORT).show();
  
                  Log.e("logMessage", "verified...");
  
              }
  
          }else
          {
              Log.e("logMessage", "socket.getEnableSessionCreation() -- failed...");
  
          }
  
    // At this point SSLSocket performed certificate verification and
    // we have performed hostname verification, so it is safe to proceed.
  
  
          socket.close();
      } catch (IOException e) {
          e.printStackTrace();
      }
  </code></pre>