How can I get the serverName in a servlet?

A

argszero

Hi
I use "String ip =request.getLocalAddr();". When the servlet was
request using url "http://localhost/servlet/XXXServlet" or "http://
127.0.0.1/servlet/XXXServlet",I can only get "127.0.0.1" which is not
the server public IP.How can get the public IP?
Thanks
 
G

Guest

argszero said:
I use "String ip =request.getLocalAddr();". When the servlet was
request using url "http://localhost/servlet/XXXServlet" or "http://
127.0.0.1/servlet/XXXServlet",I can only get "127.0.0.1" which is not
the server public IP.How can get the public IP?

I believe that request.getLocalAddr() returns the IP address
use to connect with.

So if you connect to localhost you get localhost and if you connect to
the real host you get the real host.

This seems rather logical to me since the host may have no real
IP address or 10 real IP addresses

Assuming you have a newer Java version you can get all IP
addresses with:

Enumeration<NetworkInterface> e =
NetworkInterface.getNetworkInterfaces();
while(e.hasMoreElements()) {
NetworkInterface ni = e.nextElement();
Enumeration<InetAddress> e2 = ni.getInetAddresses();
while (e2.hasMoreElements()){
InetAddress ip = e2.nextElement();
// do something with ip.getHostAddress()
}
}

Arne
 
A

argszero

I believe that request.getLocalAddr() returns the IP address
use to connect with.

So if you connect to localhost you get localhost and if you connect to
the real host you get the real host.

This seems rather logical to me since the host may have no real
IP address or 10 real IP addresses

Assuming you have a newer Java version you can get all IP
addresses with:

Enumeration<NetworkInterface> e =
NetworkInterface.getNetworkInterfaces();
while(e.hasMoreElements()) {
NetworkInterface ni = e.nextElement();
Enumeration<InetAddress> e2 = ni.getInetAddresses();
while (e2.hasMoreElements()){
InetAddress ip = e2.nextElement();
// do something with ip.getHostAddress()
}
}

Arne

Thanks ,your solution works well when there is only one network card.
But if the server be reuested has multiple network card,how can I know
from which card did the client request?
 
?

=?ISO-8859-1?Q?Arne_Vajh=F8j?=

argszero said:
Thanks ,your solution works well when there is only one network card.
But if the server be reuested has multiple network card,how can I know
from which card did the client request?

The outer loop handles multiple cards.

ni.getName() contains the name of the card.

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,444
Messages
2,571,709
Members
48,796
Latest member
Greg L.
Top