How to get MAC address in Java

Since JDK 1.6, Java developers are able to access network card detail via NetworkInterface class. In this example, we show you how to get the localhost MAC address in Java.

Example : Get MAC Address via NetworkInterface.getByInetAddress()

package br.com.ziben;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

public class app{

   public static void main(String[] args){

	InetAddress ip;
	try {

		ip = InetAddress.getLocalHost();
		System.out.println("Current IP address : " + ip.getHostAddress());

		NetworkInterface network = NetworkInterface.getByInetAddress(ip);

		byte[] mac = network.getHardwareAddress();

		System.out.print("Current MAC address : ");

		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < mac.length; i++) {
			sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
		}
		System.out.println(sb.toString());

	} catch (UnknownHostException e) {

		e.printStackTrace();

	} catch (SocketException e){

		e.printStackTrace();
 	}
    }
 }

Output

Current IP address : 192.168.1.22
Current MAC address : 00-26-B9-9B-61-BF
Note
This NetworkInterface.getHardwareAddress() method is only allow to access localhost MAC address, not remote host MAC address.

Old day…

Before JDK1.6 is released, many are using command and pattern to get the MAC address in Windows, minor code changes will enable it to get the MAC address in *nux as well.

Example : Get MAC Address via command & pattern

package br.com.ziben;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class app{

   public static void main(String[] args) throws IOException{

       String command = "ipconfig /all";
       Process p = Runtime.getRuntime().exec(command);

       BufferedReader inn = new BufferedReader(new InputStreamReader(p.getInputStream()));
       Pattern pattern = Pattern.compile(".*Physical Addres.*: (.*)");

       while (true) {
            String line = inn.readLine();

	    if (line == null)
	        break;

	    Matcher mm = pattern.matcher(line);
	    if (mm.matches()) {
	        System.out.println(mm.group(1));
	    }
	}
   }
}

Output

02-00-4E-43-50-49
90-4C-E5-44-B9-8F
00-26-B9-9B-61-BF
00-00-00-00-00-00-00-E0
00-00-00-00-00-00-00-E0
00-00-00-00-00-00-00-E0
00-00-00-00-00-00-00-E0
00-00-00-00-00-00-00-E0

This obsolete method is not really efficient, because it does not display which MAC address is using now, what it did is just print out all the available MAC address currently attached. However, it’s nice to share here.

How to get IP address in Java

To get IP address of the current computer that’s running the Java application, uses InetAddress.getLocalHost() to initialize the InetAddress object and InetAddress.getHostAddress() to get the current IP address.

Full example.

package br.com.ziben;
 
import java.net.InetAddress;
import java.net.UnknownHostException;
 
public class app{
 
	public static void main(String[] args){
 
		InetAddress ip;
		try {
 			ip = InetAddress.getLocalHost();
			System.out.println("Current IP address : " + ip.getHostAddress());
 
		} catch (UnknownHostException e) {
 			e.printStackTrace();
 		}
 	}
 }

Output

Current IP address : 192.168.0.185

IP 192.168.0.185 is my computer’s IP address to run this example, let compare with Ubuntu’s ifconfig

ifconfig output…

eth0      Link encap:Ethernet  Endereço de HW b8:ac:6f:74:b7:51  
          inet end.: 192.168.0.185  Bcast:192.168.0.255  Masc:255.255.255.0
          endereço inet6: fe80::baac:6fff:fe74:b751/64 Escopo:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Métrica:1
          pacotes RX:19403 erros:0 descartados:0 excesso:0 quadro:0
          Pacotes TX:14705 erros:0 descartados:0 excesso:0 portadora:0
          colisões:0 txqueuelen:1000 
          RX bytes:10498710 (10.4 MB) TX bytes:2187781 (2.1 MB)
          IRQ:45 Endereço de E/S:0x2000  

Same, InetAddress.getHostAddress() is working as expected.

Application Authentication with JAX-WS

One of the common way to handle authentication in JAX-WS is client provides “username” and “password”, attached it in SOAP request header and send to server, server parse the SOAP document and retrieve the provided “username” and “password” from request header and do validation from database, or whatever method prefer.

In this article, we show you how to implement the above “application level authentication in JAX-WS”.

Ideas…

On the web service client site, just put your “username” and “password” into request header.

    Map<String, Object> req_ctx = ((BindingProvider)port).getRequestContext();
    req_ctx.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, WS_URL);
 
    Map<String, List<String>> headers = new HashMap<String, List<String>>();
    headers.put("Username", Collections.singletonList("cazo"));
    headers.put("Password", Collections.singletonList("password"));
    req_ctx.put(MessageContext.HTTP_REQUEST_HEADERS, headers);

On the web service server site, get the request header parameters via WebServiceContext.

    @Resource
    WebServiceContext wsctx;
 
    @Override
    public String method() {
 
        MessageContext mctx = wsctx.getMessageContext();
 
	//get detail from request headers
        Map http_headers = (Map) mctx.get(MessageContext.HTTP_REQUEST_HEADERS);
        List userList = (List) http_headers.get("Username");
        List passList = (List) http_headers.get("Password");
 
    //...

That’s all, now, your deployed JAX-WS is supported application level authentication.

Authentication with JAX-WS Example

See a complete example.

1. WebService Server

Create a simple JAX-WS hello world example to handle the authentication in application level.

File : HelloWorld.java

package br.com.ziben.ws;
 
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
 
//Service Endpoint Interface
@WebService
@SOAPBinding(style = Style.RPC)
public interface HelloWorld{
 
	@WebMethod String getHelloWorldAsString();
 
}

HelloWorldImpl.java

package br.com.ziben.ws;
 
import java.util.List;
import java.util.Map;
 
import javax.annotation.Resource;
import javax.jws.WebService;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
 
//Service Implementation Bean
@WebService(endpointInterface = "br.com.ziben.ws.HelloWorld")
public class HelloWorldImpl implements HelloWorld{
 
    @Resource
    WebServiceContext wsctx;
 
    @Override
    public String getHelloWorldAsString() {
 
	MessageContext mctx = wsctx.getMessageContext();
 
	//get detail from request headers
        Map http_headers = (Map) mctx.get(MessageContext.HTTP_REQUEST_HEADERS);
        List userList = (List) http_headers.get("Username");
        List passList = (List) http_headers.get("Password");
 
        String username = "";
        String password = "";
 
        if(userList!=null){
        	//get username
        	username = userList.get(0).toString();
        }
 
        if(passList!=null){
        	//get password
        	password = passList.get(0).toString();
        }
 
        //Should validate username and password with database
        if (username.equals("cazo") && password.equals("password")){
        	return "Hello World JAX-WS - Valid User!";
        }else{
        	return "Unknown User!";
        }
 
    }
}

2. EndPoint Publisher

Create an endpoint publisher to deploy above web service at this URL : “http://localhost:9999/ws/hello”

File : HelloWorldPublisher.java

package br.com.ziben.endpoint;
 
import javax.xml.ws.Endpoint;
import br.com.ziben.ws.HelloWorldImpl;
 
//Endpoint publisher
public class HelloWorldPublisher{
 
    public static void main(String[] args) {
	   Endpoint.publish("http://localhost:9999/ws/hello", new HelloWorldImpl());
    }
 
}

3. WebService Client

Create a web service client to send “username” and “password” for authentication.

File : HelloWorldClient.java

package br.com.ziben.client;
 
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Service;
import javax.xml.ws.handler.MessageContext;
 
import br.com.ziben.ws.HelloWorld;
 
public class HelloWorldClient{
 
	private static final String WS_URL = "http://localhost:9999/ws/hello?wsdl";
 
	public static void main(String[] args) throws Exception {
 
	URL url = new URL(WS_URL);
        QName qname = new QName("http://ws.ziben.com.br/", "HelloWorldImplService");
 
        Service service = Service.create(url, qname);
        HelloWorld hello = service.getPort(HelloWorld.class);
 
        /*******************UserName & Password ******************************/
        Map<String, Object> req_ctx = ((BindingProvider)hello).getRequestContext();
        req_ctx.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, WS_URL);
 
        Map<String, List<String>> headers = new HashMap<String, List<String>>();
        headers.put("Username", Collections.singletonList("cazo"));
        headers.put("Password", Collections.singletonList("password"));
        req_ctx.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
        /**********************************************************************/
 
        System.out.println(hello.getHelloWorldAsString());
 
    }
}

Output

Hello World JAX-WS - Valid User!

4. Tracing SOAP Traffic

From top to bottom, showing how SOAP envelope flows between client and server.

1. Client send request, the username “cazo” and password “password” are included in the SOAP envelope.

POST /ws/hello?wsdl HTTP/1.1
Password: password
Username: cazo
SOAPAction: ""
Accept: text/xml, multipart/related, text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Content-Type: text/xml; charset=utf-8
User-Agent: Java/1.6.0_13
Host: localhost:8888
Connection: keep-alive
Content-Length: 178
 
<?xml version="1.0" ?>
	<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
		<S:Body>
			<ns2:getHelloWorldAsString xmlns:ns2="http://ws.ziben.com.br/"/>
		</S:Body>
	</S:Envelope>

2. Server send back a normal response.

HTTP/1.1 200 OK
Transfer-encoding: chunked
Content-type: text/xml; charset=utf-8
 
<?xml version="1.0" ?>
	<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
		<S:Body>
			<ns2:getHelloWorldAsStringResponse xmlns:ns2="http://ws.ziben.com.br/">
				<return>Hello World JAX-WS - Valid User!</return>
			</ns2:getHelloWorldAsStringResponse>
		</S:Body>
	</S:Envelope>

Done.

Java HTTPS client – HttpsURLConnection example

Here’s a simple Java HTTPS client to demonstrate the use of HttpsURLConnection class to print a https URL content and certificate detail.

Access https URL : https://www.google.com/

package br.com.ziben.client;
 
import java.net.MalformedURLException;
import java.net.URL;
import java.security.cert.Certificate;
import java.io.*;
 
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLPeerUnverifiedException;
 
public class HttpsClient{
 
   public static void main(String[] args)
   {
        new HttpsClient().testIt();
   }
 
   private void testIt(){
 
      String https_url = "https://www.google.com/";
      URL url;
      try {
	     url = new URL(https_url);
	     HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
 
	     //dump all cert info
	     print_https_cert(con);
 
	     //dump all the content
	     print_content(con);
 
      } catch (MalformedURLException e) {
	     e.printStackTrace();
      } catch (IOException e) {
	     e.printStackTrace();
      }
 
   }
 
   private void print_https_cert(HttpsURLConnection con){
 
    if(con!=null){
 
      try {
 
	System.out.println("Response Code : " + con.getResponseCode());
	System.out.println("Cipher Suite : " + con.getCipherSuite());
	System.out.println("\n");
 
	Certificate[] certs = con.getServerCertificates();
	for(Certificate cert : certs){
	   System.out.println("Cert Type : " + cert.getType());
	   System.out.println("Cert Hash Code : " + cert.hashCode());
	   System.out.println("Cert Public Key Algorithm : " + cert.getPublicKey().getAlgorithm());
	   System.out.println("Cert Public Key Format : " + cert.getPublicKey().getFormat());
	   System.out.println("\n");
	}
 
	} catch (SSLPeerUnverifiedException e) {
		e.printStackTrace();
	} catch (IOException e){
		e.printStackTrace();
	}
     }
   }
 
   private void print_content(HttpsURLConnection con){
	if(con!=null){
 
	try {
 
	   System.out.println("****** Content of the URL ********");			
	   BufferedReader br = 
		new BufferedReader(
			new InputStreamReader(con.getInputStream()));
	   String input;
 
	   while ((input = br.readLine()) != null){
	      System.out.println(input);
	   }
	   br.close();
 
	} catch (IOException e) {
	   e.printStackTrace();
	}
       }
   }
}

Output…

Response Code : 200
Cipher Suite : SSL_RSA_WITH_RC4_128_SHA
 
Cert Type : X.509
Cert Hash Code : 7810131
Cert Public Key Algorithm : RSA
Cert Public Key Format : X.509
 
Cert Type : X.509
Cert Hash Code : 6042770
Cert Public Key Algorithm : RSA
Cert Public Key Format : X.509
 
****** Content of the URL ********
<!doctype html><html><head><meta http-equiv="content-type" ......

That’s it!

Como o Java recebeu esse nome?

De: James Gosling
Data: 24 de Agosto de 2007 – 20:16:58
Para: Jonathan Schwartz
Assunto: Como o Java recebeu esse nome?
A história é a seguinte:
Nós precisávamos de um nome. Estávamos usando “oak” (que eu escolhi randomicamente), e embora o time tenha se apegado e ele, os advogados responsáveis pelo registro de marcas o descartaram. Tivemos muitos debates por email sobre nomes, mas nada era resolvido. Acabamos na estranha posição em que a única coisa que nos impedia de fazer o lançamento era o nome. Nosso líder de marketing conhecia alguém que era um “consultor de nomes” (eu não lembro o nome dele, mas ele era ótimo). Nós não podíamos pagar o preço nem tínhamos tempo para fazer um processo completo de criação de nome de produto. Ele concordou em fazer algo bem atípico, mas efetivo e rápido: ele atuou como um facilitador em uma reunião onde uma dúzia de nós nos trancamos em uma sala por uma tarde. Neste momento ele começou perguntando questões como “Como esta coisa faz vocês se sentirem?” (Animados!) “O que mais faz com que vocês se sintam assim?” (Café, Java!*). Chegamos a um quadro coberto de palavras aleatórias. Então, ele nos conduziu em um processo de ordenação onde finalizamos com um ranking de nomes. Acabamos com uma dúzia de nomes candidatos e os enviamos para os advogados: eles trabalharam na lista de cima para baixo até que chegaram a um nome que passou pela pesquisa deles. “Java” era o quarto nome na lista. O primeiro nome era “Silk”, que eu odiei, mas todos os outros gostaram. Meu favorito era “Lyric”, o terceiro na lista, mas ele não passou pelo teste dos advogados. Eu não lembro quais eram os outros candidatos.
Então, quem deu o nome Java? Uma reunião organizada pelo marketing, o consultor que a organizou, e um monte de nós gritando várias palavras aleatórias. Eu honestamente não tenho certeza absoluta de quem disse “Java” primeiro, mas acredito que tenha sido Mark Opperman.
Com certeza não foi nenhuma mente brilhante de marketing usando um processo coerente e bem pensado.
* “Java” é uma gíria norte-americana para café (NT).