Ajp Exp 14 Op
Ajp Exp 14 Op
Practical Code:
1. Execute the following code and write the output (Refer Manual pg. no.
76)
import java.io.*;
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);
}
}
}
XIII. Exercise:
1. Develop a program using InetAddress class to retrieve the IP address of
a computer when hostname is entered by the user.
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import javax.swing.*;
import java.util.*;
public class Sample extends JFrame {
private JTextField hostnameField;
private JButton retrieveButton;
private JLabel resultLabel;
public Sample() {
setTitle("IP Address Retriever");
setSize(400, 150);
setLayout(new FlowLayout());
hostnameField = new JTextField(20);
retrieveButton = new JButton("Retrieve IP Address");
resultLabel = new JLabel("Enter hostname and press the button.");
add(new JLabel("Hostname:"));
add(hostnameField);
add(retrieveButton);
add(resultLabel);
retrieveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
retrieveIPAddress();
}
});
}
private void retrieveIPAddress() {
String hostname = hostnameField.getText();
try {
InetAddress inetAddress = InetAddress.getByName(hostname);
String ipAddress = inetAddress.getHostAddress();
resultLabel.setText("IP Address of " + hostname + " is: " +
ipAddress);
} catch (UnknownHostException e) {
resultLabel.setText("Could not resolve IP address for hostname: " +
hostname);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Sample().setVisible(true);
}
});
}
}