Java.net.InterfaceAddress class in Java
This class represents a network interface address. Every device that has an IP address has an IP address on the network interface. In fact the ping command doesn’t ping a device but the devices interface address. Java provides certain methods to deal with interface addresses which can be used in places where there is a need to know the topology of the network, for fault detection in a network etc.
Methods :
- getAddress() : Returns an InetAddress for this address.
Syntax : public InetAddress getAddress()
- getBroadcast() : Returns the InetAddress for the broadcast address for this interface address. As only IPv4 addresses have broadcast addresses, null would be returned on using an IPv6 address.
Syntax :public InetAddress getBroadcast()
- getNetworkPrefixLength() : Returns the prefix length for this interface address, i.e. subnet mask for this address.
Syntax :public short getNetworkPrefixLength()
- equals() : Used for comparison of the specified object with this interface address. Returns true only if the given object is not null and represents same interface address as this object.
Syntax :public boolean equals(Object obj)
Parameters :
obj : obj to compare with
- hashCode() : Returns the hashcode for this interface address.
Syntax :public int hashCode()
- toString() : Returns a string representation of this interface address. The string is of the form : Interface Address/ prefix length.
Syntax :public String toString()
Java Implementation :
Java
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.List;
public class interfaceaddress
{
public static void main(String[] args) throws SocketException
{
NetworkInterface nif = NetworkInterface.getByIndex( 1 );
List<InterfaceAddress> list = nif.getInterfaceAddresses();
for (InterfaceAddress iaddr : list)
{
System.out.println( "getAddress() : " + iaddr.getAddress());
System.out.println( "getBroadcast() : " + iaddr.getBroadcast());
System.out.println( "PrefixLength : " + iaddr.getNetworkPrefixLength());
System.out.println( "Hashcode : " + iaddr.hashCode());
System.out.println( "toString() : " + iaddr.toString());
System.out.println( "--------------------\n" );
}
}
}
|
Output :
getAddress() : /127.0.0.1
getBroadcast() : /127.255.255.255
PrefixLength : 8
Hashcode : -16777208
toString() : /127.0.0.1/8 [/127.255.255.255]
--------------------
getAddress() : /0:0:0:0:0:0:0:1
getBroadcast() : null
PrefixLength : 128
Hashcode : 129
toString() : /0:0:0:0:0:0:0:1/128 [null]
--------------------
Please modify the index in getbyIndex() method in the above program as the network interface at index 1 might be null in your system. For more details about the this method, refer to- java.net.NetworkInterface class
References :
Official Java Documentation
Last Updated :
08 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...