Showing posts with label Socket. Show all posts
Showing posts with label Socket. Show all posts

Wednesday, February 7, 2018

Configure Windows firewall to allow a connection

When you need to connect your computer to a server through a network connection, both the firewalls on the server and your computer need to be configured to allow the connection to go through. Otherwise, it will throw a java.net.ConnectException.

To configure the firewall on your computer which has Windows 10 as its operating system:

1. Open the Windows Defender Firewall. Click on the Window icon in the left-bottom corner of your computer, type "firewall" and select the Windows Defender Firewall.

2. Click on the Advanced Settings on the left side of the window.

3. Click the Outbound Rules in the left pane. Then, click the New Rules in the right pane.

4. Select Custom and click the Next button.

5. Select the This program path if you know which program you are using. Otherwise select All programs. Click the Next button

6. Select UDP from the Protocol type drop-down list if you use DatagramSocket, otherwise select TCP if you use ServerSocket / Socket.

7. Select Specific Ports from the Remote port drop-down list and enter the port. Click the Next button.

8. Under Which remote IP addresses does this rule apply to, select These IP addresses.

9. Click the Add button and enter the IP address of your remote server and click the OK button. Click the Next button.

10. Select the Allow the connection and click the Next button. And click the Next button again.

11. Check all the check boxes: Domain, Private, and Public. Click the Next button.

12. Enter a name for this rule. Click the Finish button.

-----------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.



Friday, January 20, 2017

javax.net.ssl.SSLHandshakeException: no cipher suites in common

When you are trying to connect your SSL client to your SSL server through SSL Socket connection, the following exception occurs.

javax.net.ssl.SSLHandshakeException: no cipher suites in common
        at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
        at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1884)
        at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:276)
        at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:266)
        at sun.security.ssl.ServerHandshaker.chooseCipherSuite(ServerHandshaker.java:894)
        at sun.security.ssl.ServerHandshaker.clientHello(ServerHandshaker.java:622)
        at sun.security.ssl.ServerHandshaker.processMessage(ServerHandshaker.java:167)
        at sun.security.ssl.Handshaker.processLoop(Handshaker.java:878)
        at sun.security.ssl.Handshaker.process_record(Handshaker.java:814)
        at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1016)
        at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312)
        at sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:882)
        at sun.security.ssl.AppInputStream.read(AppInputStream.java:102)
        at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:283)
        at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325)
        at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177)
        at java.io.InputStreamReader.read(InputStreamReader.java:184)
        at java.io.BufferedReader.fill(BufferedReader.java:154)
        at java.io.BufferedReader.readLine(BufferedReader.java:317)
        at java.io.BufferedReader.readLine(BufferedReader.java:382)

The exception is thrown because the SSL server socket could not find the private key to use.

1. Ensure your keystore (the jks file used by the server) has the private key
    >keytool -list -keystore <path>/<keystore name>

2. Ensure the algorithm such as RSA used to generate the certificate is supported by your system.

3. Ensure the SSLContext is initialized correctly to use the keystore
3.1 Create a TrustManager that trust the certificate
    TrustManager[] trustManagers = new TrustManager[]{new X509TrustManager() {
           public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {}
           public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {}
           public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                 return null;
           }
     }};

3.2 Load the key store.
     KeyStore ks = KeyStore.getInstance("JKS");
     InputStream readCert = new FileInputStream("<path>/<keystore name>");
     try {
           ks.load(readCert, "<keystore password>".toCharArray());                  
      } finally {
           readCert.close();
      }

3.3 Initialize the KeyManagerFactory with the key store
      KeyManagerFactory kmf = KeyManagerFactory.getInstance(
             KeyManagerFactory.getDefaultAlgorithm());
      kmf.init(ks, "<keystore password>".toCharArray());

3.4 Initialize the SSLContext
     SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
     sslContext.init(kmf.getKeyManagers(), trustManagers, new SecureRandom());

-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live




If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.

Thursday, January 12, 2017

Windows: java SSL socket connections sample code

1. The SSL server socket

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.math.BigInteger;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;

public class SSLServer {

    public static void main(String args[]) {
        //set which keystore to use
        System.setProperty("javax.net.ssl.keyStore", "<path>/<keystore file name>");
        System.setProperty("javax.net.ssl.keyStorePassword", "<keystore password>");

        try {
            SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
            //create a server socket listening on a specified port.
            ServerSocket ss = ssf.createServerSocket(<port>);
            while (true) {
                //accept connections from client
                Socket s = ss.accept();
                //SSLSession session = ((SSLSocket) s).getSession();
                //Certificate[] cchain2 = session.getLocalCertificates();
               // for (int i = 0; i < cchain2.length; i++) {
                 //   System.out.println(((X509Certificate) cchain2[i]).getSubjectDN());
              //  }
               // System.out.println("Peer host is " + session.getPeerHost());
              //  System.out.println("Cipher is " + session.getCipherSuite());
               // System.out.println("Protocol is " + session.getProtocol());
               // System.out.println("ID is " + new BigInteger(session.getId()));
              //  System.out.println("Session created in " + session.getCreationTime());
              //  System.out.println("Session accessed in " + session.getLastAccessedTime());

                //the reader
                BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
                //the wirter
                PrintStream out = new PrintStream(s.getOutputStream());
                String message;
                while (!(message = in.readLine()).equals("end")) {
                      if (message.equals("Got it?")){
                            out.println("Yes, received.");
                      } else if (message.equals("Hello")) {
                            out.println("Hi");
                      } else if (message.equals("Thanks")){
                            out.println("end");
                      }
                }
                out.close();
                s.close();
            }
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
    }
}

2. SSL client socket

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.math.BigInteger;
import java.net.Socket;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

public class SSLClient {
    public static void main(String args[]) throws Exception {
          System.setProperty("javax.net.ssl.trustStore", "<path>/<truststore file name>");
          System.setProperty("javax.net.ssl.keyStorePassword", "<truststore password>");

          SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory.getDefault();
          Socket s = ssf.createSocket("<server IP address>", <port>);

         // SSLSession session = ((SSLSocket) s).getSession();
         // Certificate[] cchain = session.getPeerCertificates();
          //System.out.println("The Certificates used by peer");
          //for (int i = 0; i < cchain.length; i++) {
                //  System.out.println(((X509Certificate) cchain[i]).getSubjectDN());
         // }
         // System.out.println("Peer host is " + session.getPeerHost());
         // System.out.println("Cipher is " + session.getCipherSuite());
         // System.out.println("Protocol is " + session.getProtocol());
         // System.out.println("ID is " + new BigInteger(session.getId()));
          //System.out.println("Session created in " + session.getCreationTime());
        // System.out.println("Session accessed in " + session.getLastAccessedTime());

         PrintStream out = new PrintStream(s.getOutputStream());
         out.println("Hello");
         BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
         String x;
         while(!(x = in.readLine()).equals("end")){
               System.out.println(x);
               if (x.equals("Hi")){
                     out.println("Got it?");
               } else if (x.equals("Yes, received.")){
                     out.println("Thanks");
                }
          }
         out.println("end");
         in.close();
         out.close();
         s.close();
     }
}

---------------------------------------------------------------------------------------------------

                        


If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Reference:
1. Use SSLServerSocketFactory to create a SSL Server

Wednesday, April 16, 2014

Java communications over network

TCP: Transmission Control Protocol, is a connection-based protocol which guarantees that data reaches its destination successfully and in the same order the data was sent.

UDP: User Datagram Protocol, sends packets of data, datagrams, from one application to another, without guarantee that the data will arrive their destination, and the datagrams may reach their destination in any order. UDP is not connection-based.

Java classes which use TCP or UDP to communicate over network are located in the java.net package. Classes such as URL, URLConnection, Socket, and ServerSocket use the TCP; and classes such as DatagramPacket, DatagramSocket, and MulticastSocket use the UDP.

A. Sample code using TCP to communicate over the Internet

1. Through URL and URLConnection

import java.net.*;
import java.io.*;

public class TCPWorker {
    public static void main(String[] args) throws Exception {
        //Read the www.google.com web site line by line
        URL gUrl = new URL("http://www.google.com/");
        BufferedReader in = new BufferedReader(
                    new InputStreamReader(gUrl.openStream()));

        //Or use URLConnection to read from the URL
//        URLConnection guCon = gUrl.openConnection();
//        BufferedReader in = new BufferedReader (
//                    new InputStreamReader(
//                    guCon.getInputStream()));

        String inputLine;
        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();
    }

      //Save the content of www.google.com web site to a file
      //URL gUrl = new URL("http://www.google.com/");
      InputStream is = gUrl.openStream();
     Files.copy(is, FileSystems.getDefault().getPath("<dirctory>", "<file name>"), StandardCopyOption.REPLACE_EXISTING);
}

2. Through Socket

//The server
import java.net.*;
import java.io.*;

public class TCPServer {
       public static void main(String[] args) {
             int connectionCount = 0;
              try {
                    ServerSocket serverSocket = new ServerSocket(<port number>);
                    while (connectionCount < 20) {
                           Socket clientSocket = serverSocket.accept();
                           connectionCount++;
                           new Thread() {
                                 public void run() {
                                        BufferedReader reader = new BufferedReader(
                                                                 new InputStreamReader(
                                                                 clientSocket.getInputStream()));
                                        PrintWriter writer = new PrintWriter(
                                                                 clientSocket.getOutputStream());

                                        String request = "";
                                        while ((request = reader.readLine()) != null) {
                                                writer.println("Keep searching, you will get the answer eventually!");
                                        }

                                       public void join() {
                                 }.start();
                          }
                   }
             } catch (Exception e) {
                   e.printStackTrace();
             }
       }
}


//The client
import java.net.*;
import java.io.*;

public class TCPClient {
      public static void main(String[] args) {
            try {
                  Socket clientSocket = new Socket(<host name>, <port number>);
                  PrintWriter writer = new PrintWriter(
                                                                 clientSocket.getOutputStream(), true);
                  BufferedReader reader = new BufferedReader(
                                                                 new InputStreamReader(
                                                                 clientSocket.getInputStream()));

                  writer.println("What is the status?");
               
                   String answer = "";
                   while ((answer = reader.readLine()) != null) {
                            if (answer.length() > 0) {
                                  writer.println("Got it, thanks");
                                  System.out.println("The answer is: "+answer);
                             }
                             writer.println("What is the status now?");
                   }

                   //Send the content of a file to the server
                   OutputStream os = clientSocket.getOutputStream();
               Files.copy(FileSystems.getDefault().getPath("<dirctory>", "<file name>"), os);
            }
      }
}

B. Sample code using UDP to communicate over the network

//The server
import java.net.*;
import java.io.*;

public class UDPServer extends Thread {
      private boolean keepRunning = true;

      public void run() {
            //create the socket
            DatagramSocket serverSocket = new DatagramSocket(<port number>);
            while (keepRunning) {
                  try {                  
                        //receive data
                        byte[] inData = new byte[serverSocket.getReceiveBufferSize()];
                        DatagramPacket packet = new DatagramPacket(inData, inData.length);
                        serverSocket.receive(packet);

                       byte[] dataReceived = packet.getData();
                       System.out.println("The request is: "+new String(dataReceived, 0, serverSocket.getLength()));

                       //send data
                       SocketAddress address = packet.getSocketAddress();
                       String answer = "Keep searching, you will get the answer eventually";
                       byte[] outData = answer.getBytes();

                       packet = new DatagramPacket(outData, outData.length, address);
                       serverSocket.send(packet);
             } catch (Exception e) {
                    e.printStackTrace();
                    keepRunning = false;
             }
             serverSocket.close();
      }

      public static void main(String[] args) {
              new UDPServer().start();
       }
}

//The client
import java.net.*;
import java.io.*;

public class UDPClient {
      public static void main(String[] args)  throws Exception {
             //create the socket
             DatagramSocket clientSocket = new DatagramSocket();

             //send request
             String request = "What is the status?";
             byte[] outData = request.getBytes();
           
             SocketAddress serverAddress = new InetSocketAddress(<host name>, <port number>);
             DatagramPacket packet = new DatagramPacket(outData, outData.length, serverAddress);
             clientSocket.send(packet);

             //receive response
             byte[] inData = new byte[serverSocket.getReceiveBufferSize()];
             packet = new DatagramPacket(inData, inData.length);
             clientSocket.receive(packet);

             byte[] dataReceived = packet.getData();
             System.out.println("The response is: "+new String(dataReceived, 0, clientSocket.getLength()));
      }
}

References:

1. Reading from and writing to a URLConnection
2. Writing a datagram client and server

-----------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.