Name: jn10789 Date: 02/16/99
I am writing a java app that communicates with other apps on other computers via sockets. These apps are often run on PCs that are connected to the internet via a dial-up connection. Disconnections can be expected and a giving computer will often reconnect with a new IP address. I would like my app to handle these problems gracefully.
The problem is that I use InetAddress.getLocalHost() to determine the IP address of the local machine and this appears to be cached for the entire session of the app. i.e. when I run my app and read from InetAddress.getLocalHost() I always get the same value even if the user is diconnecting and reconnecting their dial-up connection and thus changing their local host address.
I've found several bugs which seem to deal with some aspects of this issue (4173986, 406228, 4026938) and I've gathered that I can disable InetAddress cacheing by changing a system property as follows:
System.setProperty("sun.net.inetaddr.ttl", "0");
Unfortunately this does not appear to fix the problem.
What am I doing wrong? Does the property fix not work on Win32?
Here is a simple program that displays the output from InetAddress.getLocalHost() Run the program from a machine that has a dial-up connection, check the ip value, then disconnect, reconnect, refresh and check the value. It should be incorrectly set at the same value it was at originally. You can run winipcfg to verify that the ip address has changed.
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
class test1 {
JLabel ip;
private test1() {
// this is supposed to disable InetAddress ip caching
System.setProperty("sun.net.inetaddr.ttl", "0");
JFrame frame = new JFrame();
frame.setSize(200, 200);
Container contentPane = frame.getContentPane();
ip = new JLabel();
contentPane.add(ip, BorderLayout.CENTER);
updateIP();
JButton refresh = new JButton("Refresh");
refresh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateIP(); }
});
contentPane.add(refresh, BorderLayout.SOUTH);
// allow the user to close the window
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0); }
});
frame.setVisible(true);
}
private void updateIP() {
String localHost;
try {
localHost = InetAddress.getLocalHost().toString();
} catch (UnknownHostException e) {
localHost = "unknown host";
}
ip.setText("IP: "+localHost);
}
public static void main(String[] args) {
new test1();
}
}
(Review ID: 54214)
======================================================================