In a JSP app, in Tomcat, the following code used to produce the whole address of the page (from this answer):
String myUrl = "no network";
try {
Socket s = new Socket("www", 80);
myUrl = "http://"+s.getLocalAddress().getHostAddress()+":"+request.getLocalPort()+request.getRequestURI();
s.close();
} catch (Exception ex) {
} finally {
}
After that miUrl
would have the folowing value (not the real IP addr): http://111.101.101.2:8080/mypage.jsp
It has been working for several years.
A week ago miUrl
began having "no network" as value, indicating that an exception happened.
I issued ex.printStackTrace()
and is says: java.net.UnknownHostException: www
Creating a socked with the literal "www" used to work, now out of a sudden it stopped working.
Question:
EDIT: It's a file-sharing app, running in the users's workstation, I want users to be able to copy the address to share links with others, and http://localhost:8080/downloadpage.jsp
(as shown in address field of browser) is no good for sharing. It would help if you show me how to get that same info without the socket hack.
Solved the IP addr part without using a socket.
public String getIP(){
String ip="no network";
try {
Enumeration<NetworkInterface> n = NetworkInterface.getNetworkInterfaces();
outmost:
for (; n.hasMoreElements();)
{
NetworkInterface e = n.nextElement();
Enumeration<InetAddress> a = e.getInetAddresses();
for (; a.hasMoreElements();)
{
InetAddress addr = a.nextElement();
if (addr instanceof Inet4Address){ // return the first IPv4 addr (127.0.1.1 is always last)
if (addr.isSiteLocalAddress()){
ip=addr.getHostAddress();
break outmost;
}
}
}
}
} catch (UnknownHostException e1) {
} catch (SocketException e) {
}
return ip;
}
Then
String miUrl = "http://"+getIP()+":"+request.getLocalPort()+request.getRequestURI();