#!/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.
- The script starts by assigning the Java code snippet to the
java_codevariable using a here-document. The Java code defines a class namedHostnamewith amainmethod. - Within the
mainmethod, the script tries to obtain the local host’sInetAddressobject by calling thegetLocalHost()method of theInetAddressclass. - Inside a try-catch block, the script then retrieves the canonical hostname of the machine by calling the
getCanonicalHostName()method on theInetAddressobject. - If an exception occurs during the execution, the script prints the stack trace for debugging purposes.
- The obtained hostname is printed to the standard output using
System.out.println(). - The script writes the Java code to a temporary file named
Hostname.java. - The script compiles the Java source file using the
javaccommand, generating the correspondingHostname.classfile. - Finally, the script executes the compiled Java program using the
javacommand, which runs themainmethod of theHostnameclass and displays the canonical hostname on the terminal. - 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
