Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Example – Get the local IP address and hostname

Java Examples - Getting the Local IP Address and Host Name

Java Examples Java Examples

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

Exception handling

The output of the above code is:



主机名: your-hostname

IP地址: 192.168.1.2

Java Examples Java Examples