Java Examples - Getting the Local IP Address and Host Name
In Java, you can use the standard networking library to get the local IP address and host name.
The following example demonstrates how to use the getLocalHost and getLocalAddress() methods of the InetAddress class to get the local host name and IP address:
Main.java File
import
java
.
net
.
InetAddress
;
import
java
.
net
.
UnknownHostException
;
public
class
NetworkInfo
{
public
static
void
main
(
String
[
]
args
)
{
try
{
//
Get the local host object
InetAddress
localHost
=
InetAddress
.
getLocalHost
(
)
;
//
Get the host name
String
hostName
=
localHost
.
getHostName
(
)
;
System
.
out
.
println
(
"
Host name:
"
hostName
)
;
//
Get the IP address
String
hostAddress
=
localHost
.
getHostAddress
(
)
;
System
.
out
.
println
(
"
IP address:
"
hostAddress
)
;
}
catch
(
UnknownHostException
e
)
{
System
.
err
.
println
(
"
Unable to get the local IP address and host name:
"
e
.
getMessage
(
)
)
;
e
.
printStackTrace
(
)
;
}
}
}
Description
InetAddress.getLocalHost(): gets the InetAddress representing the local hostInetAddressobject.getHostName(): gets the host name of the local host.getHostAddress(): gets the IP address of the local host.
Exception handling
UnknownHostException: thrown when the local host name or IP address cannot be determined.
The output of the above code is:
主机名: your-hostname
IP地址: 192.168.1.2
Java Examples