Here you can find the source of getIPV4MainAddress(NetworkInterface ni)
Parameter | Description |
---|---|
ni | network interface we are looking for |
Parameter | Description |
---|---|
IOException | an exception |
public static Inet4Address getIPV4MainAddress(NetworkInterface ni) throws IOException
//package com.java2s; /*//from w w w. j a v a 2 s . c o m * Copyright (c) 2012-2017 ZoxWeb.com LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ import java.io.IOException; import java.net.Inet4Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.util.ArrayList; import java.util.Enumeration; public class Main { /** * Return the main ip V4 address associated with the ni * * @param ni * network interface we are looking for * @return the ip address, null if no ip address is associated with the * current network interface. * @throws IOException */ public static Inet4Address getIPV4MainAddress(String ni) throws IOException { return getIPV4MainAddress(NetworkInterface.getByName(ni)); } /** * Return the main ip V4 address associated with the ni * * @param ni * network interface we are looking for * @return the ip address, null if no ip address is associated with the * current network interface. * @throws IOException */ public static Inet4Address getIPV4MainAddress(NetworkInterface ni) throws IOException { Inet4Address[] addresses = getIPV4AllAddresses(ni); if (addresses != null && addresses.length > 0) { return addresses[addresses.length - 1]; } return null; } /** * Return all the ip V4 addresses associated with the ni * * @param ni * network interface we are looking for * @return the ip addresses, empty array of no ips * @throws IOException */ public static Inet4Address[] getIPV4AllAddresses(String ni) throws IOException { return getIPV4AllAddresses(NetworkInterface.getByName(ni)); } /** * Return all the ip V4 addresses associated with the ni * * @param ni * network interface we are looking for * @return the ip addresses, empty array of no ips * @throws IOException */ public static Inet4Address[] getIPV4AllAddresses(NetworkInterface ni) throws IOException { ArrayList<Inet4Address> v = new ArrayList<Inet4Address>(); for (Enumeration<InetAddress> e = ni.getInetAddresses(); e.hasMoreElements();) { InetAddress addr = e.nextElement(); if (addr instanceof Inet4Address) v.add((Inet4Address) addr); } return (Inet4Address[]) v.toArray(new Inet4Address[v.size()]); } }