Code
Package Test;
ImportJava.net. inetaddress;
ImportJava.net. networkinterface;
ImportJava.net. socketexception;
ImportJava.net. unknownhostexception;
ImportJava. util. enumeration;
Public ClassIPhone per {
Public Static Void Main (string [] ARGs) Throws Unknownhostexception, socketexception {
// Applicable only to Windows
Inetaddress inet = Inetaddress. getlocalhost ();
System. Out. println ( " The IP address of the local machine is: " + Inet. gethostaddress ());
// Obtains the IP address configured on the local machine based on the network card, applicable to Windows and Linux
Enumeration netinterfaces = Networkinterface. getnetworkinterfaces ();
Inetaddress IP = Null ;
String IPaddress = "" ;
While (Netinterfaces. hasmoreelements ()){
Networkinterface Ni = (Networkinterface) netinterfaces. nextelement ();
// System. Out. println ("--------------" + Ni. getdisplayname ());
Enumeration inetaddress = Ni. getinetaddresses ();
While (Inetaddress ! = Null && Inetaddress. hasmoreelements ()){
Object OBJ = Inetaddress. nextelement ();
If (OBJ ! = Null ){
// System. Out. println (Ni. getdisplayname ());
// System. Out. println (obj. getclass (). getname ());
IP = (Inetaddress) OBJ;
// System. Out. println ("local IP =" + IP. gethostaddress ());
// If (! IP. issitelocaladdress ()&&! IP. isloopbackaddress () & IP. gethostaddress (). indexof (":") =-1 ){
// Issitelocaladdress Method
// Returns true if the IP address is a local IP address (sitelocaladdress); otherwise, returns false. IPv4 address local
// The address is divided into three segments: 10.0.0.0 ~ 10.20.255.255, 172.16.0.0 ~ 172.31.255.255, 192.168.0.0
// ~ 192.168.255.255. The first 12 bits of the local address in IPv6 region are FEC, and other bits can be any value,
// For example, fed0: And fef1: Are all local regional addresses.
// Isloopbackaddress Method
// If the IP address is a loopback address, true is returned. Otherwise, false is returned. The loopback address is the IP address of the local machine.
// The range of IPv4 loopback addresses is 127.0.0.0 ~ 127.20.255, that is, as long as the first byte is 127,
// Is the lookback address. For example, 127.1.2.3 and 127.0.200.200 are loopback addresses. The IPv6 loopback address is
// 0: 0: 0: 0: 0: 0: 0: 1, can also be abbreviated as: 1.
System. Out. println (IP. gethostaddress ());
If ( ! IP. isloopbackaddress () && IP. gethostaddress (). indexof ( " : " ) = - 1 ){
IPaddress = IP. gethostaddress ();
Break ;
} Else {
IP = Null ;
}
}
}
}
System. Out. println ( " IP address of the Local Machine = " + IPaddress );
}
}