We would like to identify and display the server and port that a Java application is running on that is behind a proxy web server. This means that getServerName() and getServerPort() return the server name of the proxy and its port (80).
We have two application server instances running on a single physical box and therefore have two active ports per box i.e. 9080, 9081. What I'd like to have is <Application Server Name>:<Application Server Port> displayed.
Any ideas? I'm a complete Java noob, sorry if this is a basic question.
The server hostname is part of the request, as it depends on what URL the client used to reach your host. The value you get in this way is defined on the client and does not have to be what you expect.
If you are interested in the local hostname, you can try:
String hostname = InetAddress.getLocalHost().getHostName();
You can use ServletRequest#getLocalXXX() methods for this.
ServletRequest#getLocalName() returns local hostname.
ServletRequest#getLocalAddr() returns local IP.
ServletRequest#getLocalPort() returns local port.
Crunchify provides a nice example for this.
import java.net.InetAddress;
import java.net.UnknownHostException;
public class CrunchifyGetIPHostname {
public static void main(String[] args) {
InetAddress ip;
String hostname;
try {
ip = InetAddress.getLocalHost();
hostname = ip.getHostName();
System.out.println("Your current IP address : " + ip);
System.out.println("Your current Hostname : " + hostname);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
Related
I'm trying to connect to my localhost kafka server from java function saved into Oracle database 19.3.
The problem is that i cannot reach the server. In database trace files i see that kafka library is using java.nio package to connect to server. Any connection attempt is ending with "Connection refused". I admit also that I can send data to topics from command line tool.
To check if my requests from database are incoming to localhost server at port 9092 i have run Hercules TCP Server and setup it to listen on this port. Then when i'm using my java function it nothing happens.
I write some "test" functions to make only simple connection to my local server, to see if there is some network problem.
The function where i use java.net package is working and i can see that i receive connection requests from database, but the function where i use java.nio package is returning always "Connection refused"
I have granted java.net.SocketPermission to my database user:
exec dbms_java.grant_permission( 'KAFKA', 'SYS:java.net.SocketPermission', '*', 'connect,resolve' );
commit;
Are there needed some special permissions to use java.nio package into oracle database java functions or maybe i'm doing something wrong?
Here are my java "test" functions code:
CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED "testTCP" AS
import java.net.Socket;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
public class testTCP {
public static String conn_nio(){
String response;
try {
InetSocketAddress hostAddress = new InetSocketAddress("localhost", 9092);
SocketChannel client = SocketChannel.open(hostAddress);
client.close();
response = "OK";
}
catch(Exception e){
response = "Message: " + e.getMessage() + " Cause: " + e.getCause();
}
return response;
}
public static String conn_net() {
String response;
try
{
Socket socket = new Socket( "localhost", 9092 );
socket.close();
response = "OK";
}
catch( Exception e )
{
response = "Message: " + e.getMessage() + " Cause: " + e.getCause();
}
return response;
}
}
Cannot reproduce. I pointed it to port 8080 of a local HTTP server which I started with
python -m SimpleHTTPServer 8080
and both connection methods are ok:
CREATE OR REPLACE FUNCTION test_net RETURN VARCHAR2 AS
LANGUAGE JAVA NAME 'testTCP.conn_net() return java.lang.String';
/
CREATE OR REPLACE FUNCTION test_nio RETURN VARCHAR2 AS
LANGUAGE JAVA NAME 'testTCP.conn_nio() return java.lang.String';
/
SELECT test_net FROM DUAL;
OK
SELECT test_nio FROM DUAL;
OK
I am trying to get the name of computer from its local IP. This is what I've done so far, but nothing works it just returns the IP address as hostname
InetAddress addr = null;
String hostIP = "192.168.100.10";
try {
addr = InetAddress.getByName(hostIP);
} catch (UnknownHostException e) {
System.out.println("Host " + hostIP + " not found!");
}
String host = addr.getHostAddress();
String hostname= addr.getHostName();
String hostname2 = addr.getCanonicalHostName();
I am expecting to get DESKTOP-DWASDFW as hostname but instead i get 192.168.100.10
UPDATE:
I managed to "fix" it by adding my computer and its ip address manually into the router configuration
but this isn't what im looking for as it requires manually entering every name and IP address. I want something like this app WakeOnLan, it can scan the whole network and get IP address, MAC address and hostname. This app uses arp requests, i researched a lot about how to accomplish something like that in android but found nothing that worked for me (I'm using android 4.2.2)
I am using Windows 8 with JDK 1.7. My IP address is 192.168.1.108, when I am running:
System.out.println(InetAddress.getLocalHost().equals(InetAddress.getByName("localhost")));
OR
System.out.println(InetAddress.getLocalHost().equals(InetAddress.getByName("127.0.0.1")));
Output - It's all false.
InetAddress.getLocalHost() - Output: 192.168.1.108
InetAddress.getByName("localhost") - Output: 127.0.0.1
Further more, my UDP server is binded on InetAddress.getLocalHost() and it can't receive anything from the client if the client send packets to InetAddress.getByName("localhost"). However, it works well if the client send to InetAddress.getLocalHost(). Port is corrent.
Anyone know the difference? Thanks in advance.
From the JDK documentation for getLocalHost():
Returns the address of the local host. This is achieved by retrieving the name of the host from the system, then resolving that name into an InetAddress.
In my GNU/Linux box, my host name is "laptop", which is mapped to an address different than 127.0.0.1 in /etc/hosts. There is an equivalent file in Windows at C:\Windows\System32\drivers\etc\hosts.
By default this hosts file is searched before DNS lookup.
The ad1 gives you your address in your LAN/WAN, it seems
(I mean local/private network IP addresses like e.g.
192.168.0.108 or like 10.3.6.55).
See also:
http://en.wikipedia.org/wiki/Private_network#Private_IPv4_address_spaces
http://download.java.net/jdk7/archive/b123/docs/api/java/net/InetAddress.html#getLocalHost%28%29
But note that ad2 and ad3 are equal in my example.
import java.net.InetAddress;
public class Test014 {
public static void main(String[] args) throws Exception {
InetAddress ad1 = InetAddress.getLocalHost();
InetAddress ad2 = InetAddress.getByName("localhost");
InetAddress ad3 = InetAddress.getByName("127.0.0.1");
printArr(ad1.getAddress());
printArr(ad2.getAddress());
printArr(ad3.getAddress());
System.out.println(ad1.equals(ad2));
System.out.println(ad1.equals(ad3));
System.out.println(ad2.equals(ad3));
}
static void printArr(byte[] arr){
for (int i=0; i<arr.length; i++){
System.out.print("[" + i + "] = " + arr[i] + "; ");
}
System.out.println();
System.out.println("---------");
}
}
Also, check the API docs about when the equals method returns true and when false.
http://download.java.net/jdk7/archive/b123/docs/api/java/net/InetAddress.html#equals%28java.lang.Object%29
With Tomcat setup behind Apache, how can an id (IP address ideally) of the server be easily determined?
The specific situation is that multiple servers are setup behind a load balancer, thus the incoming request host name is non-unique and insufficient to identify a particular server for logging purposes. Using HttpServletRequest.getLocalAddr() is unfortunately returning the same hostname instead of the IP address as would be expected (I am assuming this is related to this very old issue here: https://issues.apache.org/bugzilla/show_bug.cgi?id=46082).
Is there a way to make getLocalAddr() perform as documented, or are other methods required to query the IP address of the server?
On our project, we use JMX to get all the config information.
It takes a few steps, because it is like navigating down the server.xml file
This link has some info: http://oss.wxnet.org/mbeans.html
It is probably overkill if all you want is the IP, but I thought I'd throw it out there.
MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
Set<ObjectName> theConnectors = mbeanServer.queryNames(
new ObjectName("Catalina:type=Connector,*"),
null);
if (theConnectors != null)
{
for (ObjectName nextConnectorName : theConnectors)
{
InetAddress theInetAddress = (InetAddress) mbeanServer.getAttribute(
nextConnectorName,
"address");
if (theInetAddress != null)
{
ipAddress = theInetAddress.getHostAddress();
}
if (!StringUtil.isEmpty(ipAddress))
{
// found the IP address
break;
}
}
}
For my situation, the solution was to get the IP address of the server directly instead of attempting to get the local address via HttpServleRequest.
I cached the IP for use in my filter via:
private static final String serverIp;
static {
String addressString = null;
try
{
InetAddress address = InetAddress.getLocalHost();
addressString = address.getHostAddress();
} catch (Exception e)
{
logger.error("Exception while attempting to determine local ip address",e);
}
if (addressString != null) serverIp = addressString;
else serverIp = "unknown";
}
I had a similar issue recently (a few years after the original question) and found this question and answers. The issue in my case was that the ServletRequest#getLocalAddr() implementation was returning the remote address instead of the local address. The issue was caused by a regression in Tomcat v9.0.22. It was fixed in v9.0.23. See the question and answer here:
https://stackoverflow.com/a/57725039/9602527
I have written the two program
1st whois.java to find the ip address of the given hostname
import java.net.*;
import java.io.*;
public class whois{
public static void main(String args[]) throws IOException{
String hostName = args[0];
try{
InetAddress ipaddress = InetAddress.getByName(hostName);
System.out.println("IP address: " + ipaddress.getHostAddress());
}catch(UnknownHostException e){
System.out.println("Could not find IP address for: " + hostName);
}
}
}
and other whois2.java which finds hostname for given ip
import java.net.*;
import java.io.*;
class whois2{
public static void main(String args[]){
try{
String str[] = args[0].split("\\.");
byte btArr[] = new byte[]{(byte)Integer.parseInt(str[0]), (byte)Integer.parseInt(str[1]), (byte)Integer.parseInt(str[2]), (byte)Integer.parseInt(str[3])};
InetAddress ipAddr = InetAddress.getByAddress(btArr);
System.out.println("Host name for this is : " + ipAddr.getHostName());
}catch(UnknownHostException e){
System.out.println("Unable to find the host for ip specified " + args[0]);
}
}
}
and then i ran the program with jdk 1.6 and get following outputs:
$java whois google.com
IP address: 209.85.231.104
$java whois2 209.85.231.104
Host name for this is : maa03s01-in-f104.1e100.net
why the host name is different not google.com?
Thanks in advance
The server responsible, as defined by the DNS lookup, for handling requests to a particular hostname need not have the same hostname as that of the original lookup.
A more typical example would be that requests for foobar.com are handled by a server at an IP, with IP having hostname www.foobar.com.
Note also that the handling server may vary by region.
So I get the same using the linux host tool:
joel#bohr:~$ host google.com
google.com has address 173.194.37.104
... requests to google.com should be handled by the server at 173.194.37.104
joel#bohr:~$ host 173.194.37.104
104.37.194.173.in-addr.arpa domain name pointer lhr14s02-in-f104.1e100.net.
... the hostname of the server at 173.194.37.104 is lhr14s02-in-f104.1e100.net
joel#bohr:~$ host lhr14s02-in-f104.1e100.net
lhr14s02-in-f104.1e100.net has address 173.194.37.104
... and sanity check, the IP of lhr14s02-in-f104.1e100.net is indeed 173.194.37.104
whois(ip) resolves to the name of the registered server, not to an entry on a domain name server.
Same happens when we use whois services on the web:
http://whois.domaintools.com/google.com resolves to IP 74.125.155.99 (from my location!), http://whois.domaintools.com/74.125.155.99 resolves the host px-in-f99.1e100.net (which again is different from your results)