get IP Address using InetAddress - Java Network

Java examples for Network:IP Address

Description

get IP Address using InetAddress

Demo Code


//package com.java2s;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class Main {
    public static void main(String[] argv) throws Exception {
        System.out.println(getIPAddress());
    }/*from www  .ja  v  a 2  s  .  c  o  m*/

    public static final String IPADDRESS = "0.0.0.0";

    public static String getIPAddress() {
        String ip = IPADDRESS;

        try {
            String ha = InetAddress.getLocalHost().getHostAddress();
            InetAddress[] a = InetAddress.getAllByName(ha);

            if (a.length == 1) {
                ip = a[0].getHostAddress();
            }
        } catch (UnknownHostException uhe) {
        }

        return ip;
    }
}

Related Tutorials