| Home > Core Java FAQ
> Networking FAQ |
| Networking |
| URL
Connections(16) * Internet
Addresses(14) * Sockets(23)
* Security(01) * Miscellaneous
(14) |
| |
|
Q . The API doesn't list any constructors for InetAddress how do I create an InetAddress instance?
|
Ans :
Use InetAddress's
getByName(String) class method.
The
InetAddress class's getByName method
translates from host names to InetAddress instances.
By delivering InetAddress instances with a method
rather than a constructor, the InetAddress class
gains in flexibility and efficiency. It can create new InetAddress
instances if it needs to, but it also has the option of returning
a reference to an InetAddress instance it has already
created and saved. This kind of caching is hidden from you as an
implementation detail, but it is important for efficiency and
performance.
getByName is a class
method, which means you invoke it on the InetAddress
class. You provide a String argument that represents
either the symbolic name of the host or its numeric address. This
method can throw an UnknownHostException, so your
code must either handle or declare that exception. The following
code fragment illustrates:
I netAddress address1;
InetAddress address2;
try {
address1 = InetAddress.getByName("java.sun.com");
address2 = InetAddress.getByName("192.9.9.100");
} catch (UnknownHostException e) { /* ... */ }
|
|
Q .
Is it possible to get the real local host IP?
|
Ans
:
Yes; use InetAddress's
getLocalHost method.
InetAddress's
getLocalHost method returns the address of the local
host, if the method can find it; if not, the method throws an UnknownHostException.
The following code fragment obtains an InetAddress
instance representing the local host, from which it then gets the
local host's name and IP address:
InetAddress localHost = null;
String localHostName;
byte[] byteAddress;
try {
localHost = InetAddress.getLocalHost();
} catch (UnknownHostException e) { /* ... */ }
localHostName = localHost.getHostName();
byteAddress = localHost.getAddress();
|
|
Q . How can I create an InetAddress instance from an IP address that has no DNS entry?
|
Ans
:
A bug in
the JDK 1.0.2 implementation prevents this from working, but in
the JDK 1.1 you can use InetAddress's
getByName method (using a number.number.
number.number address) even if no DNS entry exists for the
address.
|
|
Q . How do I embed an anchor in a URL? Just putting it as part of the string in the constructor doesn't work.
|
Ans
:
Like this:
URL url = new URL("http://www.my_domain.com/my_page.html");
URL anchor = new URL(url, "#section2");
this.getAppletContext().showDocument(anchor);
|
|
Q . How do I POST to a CGI script from an applet?
|
Ans
:
Let's start by noting that this is more troublesome than it might
seem at first, and that GET is preferred. For an untrusted applet, the
CGI script can only be on the server that served the applet. POSTing to
the server involves sending key/value pairs, not just a message. Also values must be encoded. To send "words to the server" you might try:
StringBuffer sb = new StringBuffer();
String str="words to the server";
sb.append("message=");
sb.append(java.net.URLEncoder.encode(str));
URLConnection cn = url.openConnection();
// set properties
cn.setDoOutput(true);
cn.setUseCaches(false);
cn.setAllowUserInteraction(false);
cn.setRequestProperty("content-type","application/x-www-form-urlencoded");
// send parameters
PrintWriter out = new PrintWriter(cn.getOutputStream());
out.print(sb.toString());
out.close();
// read stuff
BufferedReader in = new BufferedReader(
new InputStreamReader(
cn.getInputStream()));
sb = new StringBuffer();
String inputLine;
while ((inputLine = in.readLine()) != null){
sb.append(inputLine);
sb.append("\n");
}
in.close();
uresp = new URL(getDocumentBase(),"respond.html");
getAppletContext().showDocument(uresp); }
The CGI has to write its output to respond.html so that it can be displayed by the browser. But it may still fail, because respond.html
could be overwritten by a subsequent request to the same CGI before the
results of the first POST are read back.
To get an acceptable solution takes quite a lot of effort. In general you should prefer GET to POST for CGI access from Java. As it says on
the Javaworld page, the answers to the question are really: you can't,
don't POST (use GET), use a bean, or cheat.
Note, if you request a URL via the URLConnection/HttpURLConnection, the server sets the content type, and your applet can use
URLConnection.getContentType() to get the type. Alternatively, use
setRequestProperty to set it, like this:
url = new URL(cgiUrl);
urlc = url.openConnection();
urlc.setRequestProperty(
"Content-type",
"application/x-www-form-urlencoded");
Other sites:
There's a pretty good explanation at
http://www.javaworld.com/javaworld/javatips/jw-javatip41.html
See also the Marty Hall book Core Web Programming (Prentice Hall ISBN: 0-13-625666-X). It has comprehensive coverage of writing Java programs
that interface to CGI scripts. Better still, use servlets, write everything in Java, and discard your CGI code.
|
|
Q . How can I write CGI programs in Java?
|
Ans :
CGI (the Common Gateway
Interface for web servers) is an API for writing programs that use
the web as its user interface. By far, the most popular language for
this task is Perl, because of its powerful text handling
capabilities, and excellent resources available for making the
jobs of CGI programmers easier. CGI programs can be written in any
language, including Java. Unfortunately, the interface between the
web server and the CGI program uses environment variables
extensively. Use of environment variables has always been
deprecated in Java, because of portability issues (not all systems
have environment variables). The way to get around this is to write
a "wrapper" for the Java program in a language that
supports environment variables, and can then invoke the Java program
with the appropriate environment data passed in as Java
properties. Because the Java runtime environment is not a
lightweight process, it might take a moment for the CGI program to
get started before anything happens. This is
particularly true on operating systems, like NT, that have a
large overhead to spawning new processes. In preference to
using Java for CGI on the server, you might consider using the Java
servlet API in Netscape's Enterprise Server. This allows you
to develop server-side programs in Java without suffering the same
performance restrictions and other limitations of the CGI API.
Other sites:
See http://search.netscape.com/comprod/server_central/query/eval_guide/enterprise/advantage.html
for more details.
|
|
Q . How do I map between IP address and hostname?
|
Ans
:
In Java 1.1 (earlier releases were buggy) use:
String host = InetAddress.getByName("211.10.2.119").getHostName();
|
Q .
If I call the InetAddress.getByName() method with an
IP-address-string argument, like "192.168.0.1", get an UnknownHostException on some platforms, but not others. Code like
Socket sock = new Socket("155.152.5.1", 23);
triggers the exception. Why?
|
Ans
:
This is a platform difference that arises out of different
semantics in the underlying network libraries, and is [said to be, but
subject to confirmation] fixed in JDK 1.1. On Solaris and Windows NT,
the IP address string only works for IP addresses that have an associated hostname. On Linux and Windows 95, the IP address string
works in all cases.
When InetAddress is instantiated with an IP address, a reverse DNS lookup is done. If the IP address is not associated with a valid
hostname, the instantiation will fail. This is part of anti DNS-spoofing, and in JDK 1.1 works because the reverse lookup will not
occur until the hostname is asked for. So in JDK 1.1,
InetAddress in = InetAddress.getByName("155.152.5.1");
[Note: this info is still to be confirmed. Net gurus?]
Other sites: Microsoft has several network-related patches at its site http://www.microsoft.com/
|
|
Q . How can I find out the current IP address for my machine?
|
Ans
:
The InetAddress has a static method called getLocalHost() which will return the current address of the local machine. You can then use the getHostAddress() method to get the IP address.
InetAddress local = InetAddress.getLocalHost();
// Print address
System.out.println ("Local IP : " + local.getHostAddress());
|
|
Q . Is there a Java class for SSL?
|
Ans
:
There is an SSL class available from http://www.phaos.com/ Netscape says they'll include an SSL class in Netscape 4.0. JavaSoft has one too, which ships with HotJava and the JavaWebServer.
|
|
Q .
Why can't I write ping in Java?
|
Ans
:
Ping requires ICMP packets. These packets can only be created via a socket of the SOCK_RAW type. Currently, Java only allows SOCK_STREAM (TCP) and SOCK_DGRAM (UDP) sockets. It seems unlikely that this will be added very soon, since many Unix versions only allow SOCK_RAW sockets to be created by root, and winsock does not address ICMP packets (win32 includes an unsupported and undocumented ICMP.DLL).
|
|
Q . InetAddress.getLocalHost().getHostName() returns just the local part of the host name. I need the domain name too, what should I do?
|
Ans
:
Returning the fully qualified hostname is not guarenteed. Currently, whether this series of calls does or not is platform dependant. On Solaris, it will return only the unqualified host name. On Windows, it may return the fully qualified name, or it may not. It will depend on the version of Winsock in use. If you are using the Microsoft Winsock, you will get the fully qualified name. The 1.1 FCS JDK should have a fix for the Solaris part of this problem, anyway.
|
|
Q . How do I convert a numeric IP address like 199.1.32.90 into a hostname like star.blackstar.com?
|
Ans
:
Unfortunately due to an unintended side effect (i.e. a bug) in Java's caching of IP addresses and hostnames, Java 1.0 can't convert numeric IP addresses into hostnames. However this is straightforward in Java 1.1. For example,
String hostname = InetAddress.getByName("199.1.32.90").getHostName()
|
|
Q .
How do I get the IP address of a machine from its hostname?
|
Ans
:
The InetAddress class is able to resolve IP addresses for you. Obtain an instance of InetAddress for the machine, and call the getHostAddress() method, which returns a string in the xxx.xxx.xxx.xxx address form.
InetAddress inet = InetAddress.getByName("www.davidreilly.com");
System.out.println ("IP : " + inet.getHostAddress());
|