Showing posts with label Java Network Programming. Show all posts
Showing posts with label Java Network Programming. Show all posts

Wednesday, July 20, 2016

Java example of SSL Server and Client, and how to generate keystore

Here are examples of Java SSL Server and Client.



JavaSSLServer.java
package javasslserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLServerSocketFactory;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaSSLServer {
    
    static final int port = 8000;

    public static void main(String[] args) {
        
        
        SSLServerSocketFactory sslServerSocketFactory = 
                (SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
        
        try {
            ServerSocket sslServerSocket = 
                    sslServerSocketFactory.createServerSocket(port);
            System.out.println("SSL ServerSocket started");
            System.out.println(sslServerSocket.toString());
            
            Socket socket = sslServerSocket.accept();
            System.out.println("ServerSocket accepted");
            
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            try (BufferedReader bufferedReader = 
                    new BufferedReader(
                            new InputStreamReader(socket.getInputStream()))) {
                String line;
                while((line = bufferedReader.readLine()) != null){
                    System.out.println(line);
                    out.println(line);
                }
            }
            System.out.println("Closed");
            
        } catch (IOException ex) {
            Logger.getLogger(JavaSSLServer.class.getName())
                    .log(Level.SEVERE, null, ex);
        }
    }
    
}


JavaSSLClient.java
package javasslclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLSocketFactory;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaSSLClient {
    
    static final int port = 8000;

    public static void main(String[] args) {
        
        SSLSocketFactory sslSocketFactory = 
                (SSLSocketFactory)SSLSocketFactory.getDefault();
        try {
            Socket socket = sslSocketFactory.createSocket("localhost", port);
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            try (BufferedReader bufferedReader = 
                    new BufferedReader(
                            new InputStreamReader(socket.getInputStream()))) {
                Scanner scanner = new Scanner(System.in);
                while(true){
                    System.out.println("Enter something:");
                    String inputLine = scanner.nextLine();
                    if(inputLine.equals("q")){
                        break;
                    }
                    
                    out.println(inputLine);
                    System.out.println(bufferedReader.readLine());
                }
            }
            
        } catch (IOException ex) {
            Logger.getLogger(JavaSSLClient.class.getName())
                    .log(Level.SEVERE, null, ex);
        }
         
    }
    
}



Without keystore, both the server and client will fail. This video show how to generate keystore using keytool program. Then run server and client with keystore and password.


Type the following command in your command window to create a keystore named examplestore and to generate keys:

$ keytool -genkey -alias signFiles -keystore examplestore

You will be prompted to enter passwords for the key and keystore. The password in this example is "password".

(reference: https://docs.oracle.com/javase/tutorial/security/toolsign/step3.html)

Run SSL server and client by entering the commands:
$ java -jar -Djavax.net.ssl.keyStore=keystore -Djavax.net.ssl.keyStorePassword=password "...JavaSSLServer.jar"
$ java -jar -Djavax.net.ssl.trustStore=keystore -Djavax.net.ssl.trustStorePassword=password "...JavaSSLClient.jar"


Sunday, April 17, 2016

Get my MAC address using NetworkInterface

Java example to get MAC address using NetworkInterface:



package javamyip;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaMyIP {

    public static void main(String[] args) {
        displayMyIP();
    }
    
    static void displayMyIP(){
        Enumeration<NetworkInterface> nets;
        try {
            nets = NetworkInterface.getNetworkInterfaces();
            for (NetworkInterface netint : Collections.list(nets)){
                System.out.printf(netint.getDisplayName() +"\n");
                Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
                for (InetAddress inetAddress : Collections.list(inetAddresses)) {
                    System.out.printf("InetAddress: %s\n", inetAddress);
                }
                
                byte[] mac = netint.getHardwareAddress();
                if(mac != null){
                    StringBuilder macAddr = new StringBuilder();
                    for (int i = 0; i < mac.length; i++) {
                        macAddr.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? ":" : "")); 
                    }
                    System.out.printf("Hardware address (MAC): [%s]\n", macAddr.toString());
                }
                
                System.out.printf("\n");
            }
        } catch (SocketException ex) {
            Logger.getLogger(JavaMyIP.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Friday, April 15, 2016

List my IP (inetAddress)


Java example to list Network Interface Addresses and IP:

package javamyip;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaMyIP {

    public static void main(String[] args) {
        displayMyIP();
    }
    
    static void displayMyIP(){
        Enumeration<NetworkInterface> nets;
        try {
            nets = NetworkInterface.getNetworkInterfaces();
            for (NetworkInterface netint : Collections.list(nets)){
                System.out.printf(netint.getDisplayName() +"\n");
                Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
                for (InetAddress inetAddress : Collections.list(inetAddresses)) {
                    System.out.printf("InetAddress: %s\n", inetAddress);
                }
                System.out.printf("\n");
            }
        } catch (SocketException ex) {
            Logger.getLogger(JavaMyIP.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}



Can use functional operations in Java 8 (auto suggested by Netbeans):
package javamyip;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaMyIP {

    public static void main(String[] args) {
        displayMyIP();
    }
    
    static void displayMyIP(){
        Enumeration<NetworkInterface> nets;
        try {
            nets = NetworkInterface.getNetworkInterfaces();
            Collections.list(nets).stream().map((netint) -> {
                System.out.printf(netint.getDisplayName() +"\n");
                return netint;
            }).map((netint) -> netint.getInetAddresses()).map((inetAddresses) -> {
                Collections.list(inetAddresses).stream().forEach((inetAddress) -> {
                    System.out.printf("InetAddress: %s\n", inetAddress);
                });
                return inetAddresses;
            }).forEach((_item) -> {
                System.out.printf("\n");
            });
        } catch (SocketException ex) {
            Logger.getLogger(JavaMyIP.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}


Wednesday, April 13, 2016

Create ServerSocket with automatically allocated port

Create ServerSocket by calling constructor ServerSocket(int port) with port = 0,  the port number is automatically allocated, typically from an ephemeral port range. This port number can then be retrieved by calling getLocalPort.

Example:
package javaechoserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaEchoServer {

    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        try {
            //Get a available port by passing 0 
            serverSocket = new ServerSocket(0);
            int port = serverSocket.getLocalPort();
            System.out.println("Port : " + port);
            
        } catch (IOException ex) {
            Logger.getLogger(JavaEchoServer.class.getName())
                    .log(Level.SEVERE, null, ex);
        } finally {
            if (serverSocket != null){
                try {
                    serverSocket.close();
                } catch (IOException ex) {
                    Logger.getLogger(JavaEchoServer.class.getName())
                            .log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
}



Sunday, March 6, 2016

Read from Internet using URLConnection and BufferedReader

Java example to read from Internet using URLConnection and BufferedReader. Thanks for Tomtom's comment in my last post "Read from Internet using URLConnection and ReadableByteChannel".



package javaurlconnection;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaURLConnection {

    public static void main(String[] args) {
        try {
            URL url = new URL("http://java-buddy.blogspot.com");
            URLConnection urlConnection = url.openConnection();
            
            /*
            InputStream inputStream = urlConnection.getInputStream();
            try (ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream)) {
                ByteBuffer buffer = ByteBuffer.allocate(1024);
 
                while (readableByteChannel.read(buffer) > 0)
                {
                    String bufferString = new String(buffer.array());
                    System.out.println(bufferString);
                    buffer.clear();
                }
            }
            */
            
            //using BufferedReader
            InputStream inputStream = urlConnection.getInputStream();
            InputStreamReader inputStreamReader = 
                    new InputStreamReader(inputStream);
            BufferedReader buffReader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = buffReader.readLine()) != null) {
                System.out.println(line);
            }
            
        } catch (MalformedURLException ex) {
            Logger.getLogger(JavaURLConnection.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(JavaURLConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
}

Thursday, March 3, 2016

Read from Internet using URLConnection and ReadableByteChannel

Java example to read from Internet, "http://java-buddy.blogspot.com", using URLConnection and ReadableByteChannel.


Example:
package javaurlconnection;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaURLConnection {

    public static void main(String[] args) {
        try {
            URL url = new URL("http://java-buddy.blogspot.com");
            URLConnection urlConnection = url.openConnection();
            InputStream inputStream = urlConnection.getInputStream();
            try (ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream)) {
                ByteBuffer buffer = ByteBuffer.allocate(1024);

                while (readableByteChannel.read(buffer) > 0)
                {
                    String bufferString = new String(buffer.array());
                    System.out.println(bufferString);
                    buffer.clear();
                }
            }
        } catch (MalformedURLException ex) {
            Logger.getLogger(JavaURLConnection.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(JavaURLConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
}



Related:
- Read from Internet using URLConnection and BufferedReader (Thanks Tomtom comment)

Tuesday, March 1, 2016

Get IP address of Website using InetAddress

Java example to get IP address of Website using InetAddress:

package javainetaddress;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaInetAddress {

    public static void main(String[] args) {
        try {
            InetAddress inetAddress = InetAddress.getByName("www.google.com");
            System.out.println(inetAddress);
            System.out.println(inetAddress.getHostName());
            System.out.println(inetAddress.getHostAddress());
        } catch (UnknownHostException ex) {
            Logger.getLogger(JavaInetAddress.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
}




Wednesday, November 11, 2015

Query InterNIC server's whois

Last example show Java example using WhoisClient class to query whois. Alternatively, we can query InterNIC server's whois without WhoisClient class.


package javawhois;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaWhoIs {
    
    private final static String WHO ="google.com";

    private final static String WHOIS_HOST = "whois.internic.net";
    private final static int WHOIS_PORT = 43;

    public static void main(String[] args) {
        int c;
        Socket socket = null; 

        String query = "=" + WHO + "\r\n";
        byte buf[] = query.getBytes();
        
        try {
            socket = new Socket(WHOIS_HOST, WHOIS_PORT);
            InputStream in = socket.getInputStream();
            OutputStream out = socket.getOutputStream(); 

            out.write(buf); 
            out.flush();
            while ((c = in.read()) != -1) { 
                System.out.print((char) c); 
            } 
            System.out.print("\nDone\n");
        } catch (IOException ex) {
            Logger.getLogger(JavaWhoIs.class.getName()).log(Level.SEVERE, null, ex);
            System.out.print(ex.getMessage());
        } finally {
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException ex) {
                    Logger.getLogger(JavaWhoIs.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
}


Sunday, November 8, 2015

Java example using WhoisClient class

The WhoisClient class implements the client side of the Internet Whois Protocol defined in RFC 954. To query a host you create a WhoisClient instance, connect to the host, query the host, and finally disconnect from the host. If the whois service you want to query is on a non-standard port, connect to the host at that port.
org.apache.commons.net.whois.WhoisClient

Example:
package javawhoisclient;

import java.io.IOException;
import org.apache.commons.net.whois.WhoisClient;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaWhoisClient {

    public static void main(String[] args) {
        WhoisClient whois;

        whois = new WhoisClient();

        try {
            whois.connect(WhoisClient.DEFAULT_HOST);
            System.out.println(whois.query("=google.com"));
            whois.disconnect();
        } catch (IOException e) {
            System.err.println("Error I/O exception: " + e.getMessage());
            return;
        }
    }

}




To use WhoisClient class in your program, you have to include library commons-net-3.3 in your code, it can be download here: https://commons.apache.org/proper/commons-net/index.html

This video show how to download and add library commons-net-3.3 to NetBeans IDE.


Next:
query InterNIC server's whois without WhoisClient class.

Tuesday, January 27, 2015

Java HttpServer to download image

The example implement HttpServer to download image.


package java_httpserver;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class Java_HttpServer {
    
    static final int responseCode_OK = 200;

    public static void main(String[] args) {
        try {
            HttpServer httpServer = HttpServer.create(new InetSocketAddress(8000), 0);
            httpServer.createContext("/", new MyHttpHandler());
            httpServer.createContext("/image", new GetHttpHandler());
            httpServer.setExecutor(null);
            httpServer.start();
        } catch (IOException ex) {
            Logger.getLogger(Java_HttpServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    static class MyHttpHandler implements HttpHandler{

        @Override
        public void handle(HttpExchange he) throws IOException {
            
            String response = "Hello from java-buddy";
            he.sendResponseHeaders(responseCode_OK, response.length());
            
            OutputStream outputStream = he.getResponseBody();
            outputStream.write(response.getBytes());
            outputStream.close();
        }
    }
    
    static class GetHttpHandler implements HttpHandler{

        @Override
        public void handle(HttpExchange he) throws IOException {

            Headers headers = he.getResponseHeaders();
            headers.add("Content-Type", "image/png");
            
            File file = new File ("duke.png");
            byte[] bytes  = new byte [(int)file.length()];
            System.out.println(file.getAbsolutePath());
            System.out.println("length:" + file.length());
            
            FileInputStream fileInputStream = new FileInputStream(file);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
            bufferedInputStream.read(bytes, 0, bytes.length);

            he.sendResponseHeaders(responseCode_OK, file.length());
            OutputStream outputStream = he.getResponseBody();
            outputStream.write(bytes, 0, bytes.length);
            outputStream.close();
        }
    }
    
}

Simple example of Java HttpServer

com.sun.net.httpserver.HttpServer  implements a simple HTTP server. A HttpServer is bound to an IP address and port number and listens for incoming TCP connections from clients on this address.


It's a simple example of using HttpServer.
package java_httpserver;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class Java_HttpServer {

    public static void main(String[] args) {
        try {
            HttpServer httpServer = HttpServer.create(new InetSocketAddress(8000), 0);
            httpServer.createContext("/", new MyHttpHandler());
            httpServer.setExecutor(null);
            httpServer.start();
        } catch (IOException ex) {
            Logger.getLogger(Java_HttpServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    static class MyHttpHandler implements HttpHandler{

        @Override
        public void handle(HttpExchange he) throws IOException {
            int responseCode_OK = 200;
            String response = "Hello from java-buddy";
            he.sendResponseHeaders(responseCode_OK, response.length());
            
            OutputStream outputStream = he.getResponseBody();
            outputStream.write(response.getBytes());
            outputStream.close();
            
            //try-with-resources form
            /*
            try (OutputStream outputStream = he.getResponseBody()) {
                outputStream.write(response.getBytes());
            }
            */

        }
        
    }
    
}

To access the server, open a browser and visit: http://localhost:8000/



Next example show how to implement HttpServer to download image.

Saturday, December 13, 2014

get NetworkInterface and my IP address

Example to display name and ip address of NetworkInterface.

reference: https://docs.oracle.com/javase/tutorial/networking/nifs/listing.html


package javamyipaddress;

import static java.lang.System.out;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;

/**
 *
 * @web http://java-buddy.blogspot.com/
 * ref: https://docs.oracle.com/javase/tutorial/networking/nifs/listing.html
 */
public class JavaMyIpAddress {

    public static void main(String args[]) throws SocketException {
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netint : Collections.list(nets))
            displayInterfaceInformation(netint);
    }

    static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
        out.printf("Display name: %s\n", netint.getDisplayName());
        out.printf("Name: %s\n", netint.getName());
        Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
        for (InetAddress inetAddress : Collections.list(inetAddresses)) {
            out.printf("InetAddress: %s\n", inetAddress);
        }
        out.printf("\n");
     }

}

Friday, October 17, 2014

Get various parts from URL

package javaurlget;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;

public class JavaURLget {

    public static void main(String[] args) {
        String src = "http://java-buddy.blogspot.com/search/label/java8";
        try {
            URL srcURL = new URL(src);
            
            System.out.println(srcURL.toString());
            System.out.println("Host: " + srcURL.getHost());
            System.out.println("Path: " + srcURL.getPath());
            System.out.println("Port: " + srcURL.getPort());
            System.out.println("Protocol: " + srcURL.getProtocol());
            System.out.println("Authority: " + srcURL.getAuthority());
            System.out.println("File: " + srcURL.getFile());
            
        } catch (MalformedURLException ex) {
            Logger.getLogger(JavaURLget.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }
    
}



Tuesday, November 12, 2013

Java Network Programming, 4th Edition

Java Network Programming, 4th Edition

This practical guide provides a complete introduction to developing network programs with Java. You’ll learn how to use Java’s network class library to quickly and easily accomplish common networking tasks such as writing multithreaded servers, encrypting communications, broadcasting to the local network, and posting data to server-side programs.
Author Elliotte Rusty Harold provides complete working programs to illustrate the methods and classes he describes. This thoroughly revised fourth edition covers REST, SPDY, asynchronous I/O, and many other recent technologies.
  • Explore protocols that underlie the Internet, such as TCP/IP and UDP/IP
  • Learn how Java’s core I/O API handles network input and output
  • Discover how the InetAddress class helps Java programs interact with DNS
  • Locate, identify, and download network resources with Java’s URI and URL classes
  • Dive deep into the HTTP protocol, including REST, HTTP headers, and cookies
  • Write servers and network clients, using Java’s low-level socket classes
  • Manage many connections at the same time with the nonblocking I/O
October 14, 2013  1449357679  978-1449357672 Fourth Edition