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.

Ubuntu May Replace GDM with LightDM

Yet another possible change in Ubuntu’s core components: they’re mulling over replacing GDM with LightDM. Why? Well: “Faster – the greeter doesn’t require an entire GNOME session to run. More flexible – multiple greeters are supported through a well defined interface. This allows Ubuntu derivatives to use the same display manager (e.g. Kubuntu, Lubuntu etc.). Simpler codebase – similar feature set in ~5000 lines of code compared to 50000 in GDM. Supports more usecases – first class support for XDMCP and multihead.”

Linux: Executando comandos em looping no shell

Como fazer o seu shell ficar rodando um comando qualquer sempre?  Utilizando os laços while e until.

Exemplo:
Para o shell executar o comando “netstat -nat” a cada um segundo podemos fazer o seguinte:

$ while true; do netstat -nat; sleep 1; clear; done;

Esse comando executa “netstat -nat” enquanto a expressão true for verdadeira, como a expressão true SEMPRE será verdadeira, o laço se repetira infinitamente.
Com isto podemos executar qualquer comando, fica a critério do usuário e isto também não impede o uso de auxiliares como o “pipe” (|) ou “&&”.#

Também podemos fazer a mesma coisa com o comando until:

$ until false; do netstat -nat; sleep 1; clear; done;

Da mesma forma que o exemplo anterior, este laço repetirá o comando infinitamente enquanto a expressão false for falsa.