Programming Tutorials

(追記) (追記ここまで)

InetAddress get local and remote IP in Java

By: Grenfel in Java Tutorials on 2022年09月15日 [フレーム]

Here's an example program that uses InetAddress class to retrieve and display information about the local and remote IP addresses:

import java.net.InetAddress;
import java.net.UnknownHostException;
public class InetAddressExample {
 public static void main(String[] args) {
 try {
 // Get the local host address
 InetAddress localAddress = InetAddress.getLocalHost();
 System.out.println("Local Host:");
 System.out.println("Host Name: " + localAddress.getHostName());
 System.out.println("IP Address: " + localAddress.getHostAddress());
 // Get the remote host address
 InetAddress remoteAddress = InetAddress.getByName("www.google.com");
 System.out.println("\nRemote Host (www.google.com):");
 System.out.println("Host Name: " + remoteAddress.getHostName());
 System.out.println("IP Address: " + remoteAddress.getHostAddress());
 } catch (UnknownHostException e) {
 System.out.println("Error: " + e.getMessage());
 }
 }
}

Here is a sample output

Local Host:
Host Name: My-PC 
IP Address: 172.24.96.1
Remote Host (www.google.com):
Host Name: www.google.com
IP Address: 64.233.170.147

This program first retrieves the IP address of the local host using the getLocalHost() method of InetAddress. It then displays the host name and IP address of the local host using the getHostName() and getHostAddress() methods respectively.

Next, it retrieves the IP address of a remote host (in this case, www.google.com) using the getByName() method of InetAddress. It then displays the host name and IP address of the remote host using the same methods.

If the specified host is not found, the UnknownHostException is thrown, and the program prints an error message.




(追記) (追記ここまで)


Add Comment

JavaScript must be enabled for certain features to work
* Required information
1000

Comments

No comments yet. Be the first!
(追記) (追記ここまで)
(追記) (追記ここまで)

AltStyle によって変換されたページ (->オリジナル) /