Sign up to get Free Ebooks...

I hope you enjoy reading this article. If you are looking for such article ,Click here


WORKING | Bash script for java.net.InetAddress.getCanonicalHostName()

  • Home
  • /
  • Blog
  • /
  • WORKING | Bash script for java.net.InetAddress.getCanonicalHostName()
#!/bin/bash
java_code=$(cat <<EOF
import java.net.InetAddress;
public class Hostname {
public static void main(String[] args) {
try {
InetAddress address = InetAddress.getLocalHost();
String hostname = address.getCanonicalHostName();
System.out.println(hostname);
} catch (Exception e) {
e.printStackTrace();
}
}
}
EOF
)
echo "$java_code" > Hostname.java
javac Hostname.java
java Hostname
rm Hostname.java Hostname.class

More about script,

The script is a bash script that utilizes Java to retrieve and display the canonical hostname of the machine running the script.

  1. The script starts by assigning the Java code snippet to the java_code variable using a here-document. The Java code defines a class named Hostname with a main method.
  2. Within the main method, the script tries to obtain the local host’s InetAddress object by calling the getLocalHost() method of the InetAddress class.
  3. Inside a try-catch block, the script then retrieves the canonical hostname of the machine by calling the getCanonicalHostName() method on the InetAddress object.
  4. If an exception occurs during the execution, the script prints the stack trace for debugging purposes.
  5. The obtained hostname is printed to the standard output using System.out.println() .
  6. The script writes the Java code to a temporary file named Hostname.java .
  7. The script compiles the Java source file using the javac command, generating the corresponding Hostname.class file.
  8. Finally, the script executes the compiled Java program using the java command, which runs the main method of the Hostname class and displays the canonical hostname on the terminal.
  9. After execution, the script removes the temporary Java source file ( Hostname.java ) and the compiled class file ( Hostname.class ).

By running this script, you can retrieve and print the canonical hostname of the machine on which the script is executed.

To run the script, save it to a file (e.g., get_hostname.sh ), make it executable ( chmod +x get_hostname.sh ), and execute it ( ./get_hostname.sh ). It will display the canonical hostname of the machine running the script.

[root@machine4 ~]# chmod u+x get_hostname.sh
[root@machine4 ~]# ./get_hostname.sh
machine4.cscoop.net


November 11, 2024

November 11, 2024

November 11, 2024

June 19, 2023

May 9, 2023

April 25, 2023

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}
>