0% found this document useful (0 votes)
10 views3 pages

Java Practical No 23

The document contains Java code examples for retrieving hostnames and IP addresses using the InetAddress class. It includes a program to get the local hostname and IP address, as well as a user-input version to retrieve an IP address based on a provided hostname. Additionally, it prompts for output from the executed code and includes practical questions related to the code examples.

Uploaded by

dipya2121
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views3 pages

Java Practical No 23

The document contains Java code examples for retrieving hostnames and IP addresses using the InetAddress class. It includes a program to get the local hostname and IP address, as well as a user-input version to retrieve an IP address based on a provided hostname. Additionally, it prompts for output from the executed code and includes practical questions related to the code examples.

Uploaded by

dipya2121
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Practical No 23

Title Code:
import java.net.InetAddress;
public class HostnameIPRetriever {
public static void main(String[] args) {
try {
InetAddress address = InetAddress.getLocalHost();
System.out.println("Hostname: " + address.getHostName());
System.out.println("IP Address: " + address.getHostAddress());
} catch (Exception e) {
System.out.println("Error retrieving hostname and IP address: " +
e.getMessage());
}
}
}

O/P:

Practical Related Questions:


4. Execute the following code and write the
output
import java.net. *;
public class InetDemo
{
public static void main (String [] args)
{
try
{
InetAddress ip=InetAddress.getByName("localhost");
System.out.println("Host Name: "+ip.getHostName());
System.out.println("IP Address: "+ip.getHostAddress());
}
catch (Exception e) {System.out.println(e);}
}
}

O/P:

5. Develop a program using InetAddress class to


retrieve IP address of computer when hostname is
entered by the user.
Ans:
import java.net.InetAddress;
import java.util.Scanner;
public class HostnameIPRetriever {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter hostname: ");
String hostname = scanner.nextLine();
try {
InetAddress address = InetAddress.getByName(hostname);
System.out.println("IP Address: " + address.getHostAddress());
} catch (Exception e) {
System.out.println("Error retrieving IP address: " + e.getMessage());
}
scanner.close();
}
}

O/P:

You might also like