Getting the IP address of a host in Java

The InetAddress class is able to map between hostnames and IP addresses.
Following app demonstrates the use:

public class Main
   public static void main(String [] args) {
      if (args.length != 1) {
         System.out.println("Usage: java Main <URL>");
      try {
         InetAddress inet = InetAddress.getByName(args[0]);
         System.out.println ("IP of " + args[0] + ": " + inet.getHostAddress());
      catch(UnknownHostException e) {

Running it with

java Main


IP of

What does the setTcpNoDelay option do?

It allows you to enable or disable Nagle’s algorithm, which is used to conserve bandwidth by minimizing the number of data segments that are sent. When TcpNoDelay is enabled, data will not be sent immediately, instead it waits for more write calls and tries to squeeze in as much as possible into a packet before sending.

If you know your app should be using small packets anyway (eg. chat apps), and send them as soon as possible (no wait), at the cost of more bandwidth, then you
can disable nagle’s algorithm:


Nagle’s algorithm is described in RFC896.

When to use setSoLinger

It allows you to control a TCP socket close() method. eg.

socket.setSoLinger(true, 5000);

the socket.close() method will block until the the data that is still in the send-buffer is sent to the other end and acknowledged. If the linger delay has passed (5000 milliseconds in this case), the socket will be forced to be closed.

What is a digital certificate?

First read the question What is a digital signature? You’ll then understand what the problem is with those signatures. You can’t really proof that the public key that the sender owns to decrypt the message actually belongs to you. That’s where a digital certificate comes in. Those certificates are issued by a certificate authority (CA) which you would have to pay and give lots of information about your identity. You’d also have to send them your public key. The CA uses all this information to generate a certificate and send it back to you. The standard for digital certificates is X.509. It contains information about your identity, your public key and things like a validity period, etc. It’s important that you choose a well-known CA that other people will trust. The CA will have encrypted the certificate with their private key.

When party A now sends a message to party B, it will sign the message with his certificate. Party B will ensure this certificate is correct by decrypting it using the CA’s public key. Now party B has access to your public key and can decrypt the signature to verify the authentication.

BTW, you can also generate a certificate yourself (eg. using the tool keytool) and use that. But people are not likely to accept that certificate as there is no trusted third party involved.

The standard for digital certificates is X.509. This standard allows for certificate chaining. This allows certificates to be put in a hierarchy. Maybe party B doesn’t trust the first CA, but goes up in the hierarchy and finds one that he trusts. For example, an employee of a company might get a certificate from his company who is in turned signed by Thawte (the root CA). Now suppose that employee uses his certificate to try to get the receiver trust him. The receiver isn’t eager to trust the one that issued the certificate, but since that certificate is signed in turn by Thawte, he trust the original certificate.

Generating a MAC that uses MD5 in Java

The following example generates a random key of 128 bits (16 bytes) necessary for HmacMD5 and computes a hash using this key. The key would have to be shared between sender and receiver.

import javax.crypto.spec.*;
import javax.crypto.Mac;
import javax.crypto.*;
import sun.misc.*;
public class Main
   public static void main(String []args) throws Exception {
      String message = "the sun is green and the grass shines";
      byte[] b = generateMAC(message);
      System.out.println("HMAC-MD5 for message '" + message + "':");
      System.out.println("t" + new BASE64Encoder().encode(generateMAC(message)));
   public static byte[] generateMAC(String message) throws Exception {
      // generate key
      SecureRandom sr = new SecureRandom();
      byte[] b = new byte[20];
      SecretKey key = new SecretKeySpec(b, "HmacMD5");
      // generate message digest based on key
      Mac mac = Mac.getInstance("HmacMD5");
      return mac.doFinal(message.getBytes());


HMAC-MD5 for message 'the sun is green and the grass shines':

What is asymmetric cryptography?

The problem with symmetric cryptography is how to distribute the secret key to the involved parties. In assymetric cryptography (also: public key cryptography), algorithms use two different keys: a private and a public one. A message encrypted with a private key can be decrypted with its public key (and in some cases vice versa). The owner of the key pair holds the private key, and may distribute the public key to anyone. Someone who wants to send a secret message uses the public key of the intended receiver to encrypt it. Only the receiver holds the private key and can decrypt it.

Compared to secret key encryption, public key encryption is slow.

A popular assymetric cryptographic algorithm is RSA, used in PGP.

Aligning decimal numbers to the decimal fields

You can use the class FieldPosition and one of the Format classes. FieldPosition keeps track of where a certain part in the formatted string is located. Those parts are dependent on the type of Format class you use and are defined in constants. For example, the class DateFormat contains constants like DAY_OF_WEEK_FIELD or MONTH_FIELD. Likewise, the NumberFormat class contains two constants: INTEGER_FIELD and FRACTION_FIELD. When you invoke the method format, you can supply an instance of FieldPosition which will be filled in with information about the position of the field (beginIndex and endIndex).

import java.text.*;
public class Main {
   public static void main(String args[]) {
      double array[] = { 0, 0.1, 1.0, 213.034, 12.43, 12, 0.9832, 4567 };
      NumberFormat nf = NumberFormat.getInstance();
      StringBuffer buffer = new StringBuffer();
      for (int i=0; i<array.length; i++) {
         FieldPosition fp = new FieldPosition(NumberFormat.FRACTION_FIELD);
         nf.format(array[i], buffer, fp);
         alignInColumn(buffer, fp);
   public static void alignInColumn(StringBuffer sb, FieldPosition fp) {
      int col = 10-fp.getBeginIndex();
      if (fp.getBeginIndex() == fp.getEndIndex())
      for (int i=0; i<col; i++) { 
         System.out.print(' ');



Fetching today’s date in Java

Try this:

import java.util.*;
import java.text.*;
public class Main { 
   public static void main(String[] args) throws Exception {
      System.out.println(getDateTime("dd-MM-yyyy HH:mm:ss.SSS"));
   public static String getDateTime(String format) {
      Calendar calendar = Calendar.getInstance();
      SimpleDateFormat dateFormat = new SimpleDateFormat(format);
      Date date = calendar.getTime();
      return dateFormat.format(calendar.getTime());

Using java.util.logging to log to an XML file

Use the standard XMLFormatter class, already used by default by several standard handlers.

import java.util.logging.*;
public class Main
   public static void main(String argv[]) {
      Logger logger = Logger.getLogger("main");
      ConsoleHandler ch = new ConsoleHandler();
      ch.setFormatter(new XMLFormatter());

      LogRecord logRecord = new LogRecord(Level.SEVERE, "Something went seriously wrong");
      logRecord.setParameters(new Object[] { "param1", "param2" });



<? xml version="1.0" encoding="windows-1252" standalone="no"?>
<!DOCTYPE log SYSTEM "logger.dtd">
  <message>Something went seriously wrong</message>