InetAddress Question

I have a small applet that I want to return
the local computer's hostname.
It works, but when I leave the page and return
I get the local loop back as my IP and an exception is throw.
Why is my computer's port being locked by my first call to InetAddress.getLocalHost(). Is there a way to free my broswer or applet ?

Its in the start() method.
I have two <object> tags in my html, that both call the same class file, one of them has a name attribute.
I do an OnLoad in Javascript using the 'name' of the second <object> to call a method (getvalue())to return the value of the IP to the broswer.
The Javacode is
public class GetClientIP extends Applet {
static public String mystring;
public String getvalue() {
return mystring;
public void start {
try { InetAddress getIP = InetAddress.getLocalHost();
mystring += InetAddress.getLocalHost();
catch (Exception e) {
e.printStacktace(); }
}

Similar Messages

  • More Questions about InetAddress

    Hello,
    I have an app that I am working on that resolves Hostnames to IP's for this app there are and returns a formatted file that interfaces with another application. I have a simplified version of the code below.
    String newline = "\n";
    for(int i=0;i<array.length;++i)
              try
                        Address = InetAddress.getByName(array);
    stringbuffer.append(Address + newline);
    catch(UnknownHostException e)
    stringbuffer.append("***Does Not Exist***" + newline);
    The code that I am currently using works however, it takes very large amounts of time to complete. The reason for this is not all of the hostnames are setup, so there's a fairly decent amount of UnknownHostExceptions. The valid addresses resolve in milliseconds however the UnknownHostExceptions "resolve" in quite a few seconds as opposed to the milliseconds. The results in a problem considering there are over 600 hostnames to resolve. So here's the question.
    Is there a way to decrease the amount of time that the UnknownHostExceptions take? I have spent days searching and have come up with not even a glimpse of hope.
    If that isn't possible would setting up multiple threads to handle different portions of the array at the same time be a wise venture?
    If not does anyone have any suggestions?
    They would be much appreciated                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    Can anyone suggest a decent book on Thread pooling or a book that has a descent section on thread pooling?
    I have been searching online for hours. I think I understand the concept of Thread pooling I'm just having some trouble applying it. I need something a little more thorough than the articles I've come across.

  • Simple Java Network Programming Question

    import java.io.*;
    import java.net.*;
    public class ConsumerClient
         private static InetAddress host;
         private static final int PORT = 1234;
         private static Socket link;
         private static Resource item;
         private static BufferedReader in;
         private static PrintWriter out;
         private static BufferedReader keyboard;
         public static void main(String[] args)     throws IOException
              try
                   host = InetAddress.getLocalHost();
                   link = new Socket(host, PORT);
                   in = new BufferedReader(new InputStreamReader(link.getInputStream()));
                   out = new PrintWriter(link.getOutputStream(),true);
                   keyboard = new BufferedReader(new InputStreamReader(System.in));
                   String message, response;
                   do
                        System.out.print("Enter 1 for resource or 0 to quit: ");
                        message = keyboard.readLine();
         if(message.equals("1")**
                             item.takeOne();**
                        //Send message to server on
                        //the socket's output stream...
                        out.println(message);
                        //Accept response from server on
                        //the socket's input stream...
                        response = in.readLine();
                        //Display server's response to user...
                        System.out.println(response);
                   }while (!message.equals("0"));
              catch(UnknownHostException uhEx)
                   System.out.println("\nHost ID not found!\n");
              catch(IOException ioEx)
                   ioEx.printStackTrace();
              finally
                   try
                        if (link!=null)
                             System.out.println("Closing down connection...");
                             link.close();
                   catch(IOException ioEx)
                        ioEx.printStackTrace();
    }

    georgemc wrote:
    BlueNo yel-- Auuuuuuuugh!
    But the real question is: What is the air-speed velocity of an unladen swallow?

  • Questions on Signed Applets -- Can't Get it to Work

    For some reason my applet doesn't do any of the JDBC stuff that it's supposed to do on the web, yet when I run it through my IDE (Eclipse) the JDBC stuff gets executed. I uploaded all of my .class files and the mysql-connector com and org packages. Anybody have an idea what's wrong? I know this may be vague, so please ask questions if you need more information.
    I got this error message when I changed things up a bit:
    Connecting to the url MySQL database on port [port]
    SQLException: Communications link failure due to underlying exception:
    ** BEGIN NESTED EXCEPTION **
    java.security.AccessControlException
    MESSAGE: access denied (java.net.SocketPermission [url] resolve)
    Message was edited by:
    ktm5124

    When I view my applet on my website I get the error message: The application's digital signature is invalid. All I did was follow the steps at the URL I mentioned. What could I have done wrong? =(
    Perhaps it's the policy file. Should I make the policy file myself? I uploaded the one that Eclipse made for me. It looks like this:
    /* AUTOMATICALLY GENERATED ON Tue Apr 16 17:20:59 EDT 2002*/
    /* DO NOT EDIT */
    grant {
    permission java.security.AllPermission;
    Oh, and this is what my Java Console says when I view the applet on the website:
    Connecting to the [database name] MySQL database on port 3306
    SQLException: Communications link failure due to underlying exception:
    ** BEGIN NESTED EXCEPTION **
    java.security.AccessControlException
    MESSAGE: access denied (java.net.SocketPermission [MySQL database URL] resolve)
    STACKTRACE:
    java.security.AccessControlException: access denied (java.net.SocketPermission [MySQL database URL] resolve)
         at java.security.AccessControlContext.checkPermission(Unknown Source)
         at java.security.AccessController.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkConnect(Unknown Source)
         at java.net.InetAddress.getAllByName0(Unknown Source)
         at java.net.InetAddress.getAllByName0(Unknown Source)
         at java.net.InetAddress.getAllByName(Unknown Source)
         at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:137)
         at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:284)
         at com.mysql.jdbc.Connection.createNewIO(Connection.java:2555)
         at com.mysql.jdbc.Connection.<init>(Connection.java:1485)
         at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266)
         at java.sql.DriverManager.getConnection(Unknown Source)
         at java.sql.DriverManager.getConnection(Unknown Source)
         at util.LoadDriver.load(LoadDriver.java:19)
         at main.RedButtonGame.init(RedButtonGame.java:77)
         at sun.applet.AppletPanel.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    ** END NESTED EXCEPTION **
    Last packet sent to the server was 751 ms ago.
    SQLState: 08S01
    VendorError: 0
    Exception in thread "Timer-0" java.lang.NullPointerException
         at main.ScoresUpdater.update(ScoresUpdater.java:76)
         at main.ScoresUpdater.access$0(ScoresUpdater.java:70)
         at main.ScoresUpdater$1.run(ScoresUpdater.java:55)
         at java.util.TimerThread.mainLoop(Unknown Source)
         at java.util.TimerThread.run(Unknown Source)
    Exception in thread "AWT-EventQueue-2" java.lang.NullPointerException
         at main.User.updateYourself(User.java:47)
         at main.RedButtonGame.actionPerformed(RedButtonGame.java:244)
         at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
         at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at javax.swing.JComponent.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    Exception in thread "AWT-EventQueue-2" java.lang.NullPointerException
         at main.ScoresUpdater.update(ScoresUpdater.java:76)
         at main.ScoresUpdater.refresh(ScoresUpdater.java:44)
         at main.RedButtonGame.actionPerformed(RedButtonGame.java:247)
         at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
         at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at javax.swing.JComponent.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    Exception in thread "AWT-EventQueue-2" java.lang.NullPointerException
         at main.ScoresUpdater.update(ScoresUpdater.java:76)
         at main.ScoresUpdater.refresh(ScoresUpdater.java:44)
         at main.RedButtonGame.actionPerformed(RedButtonGame.java:247)
         at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
         at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at javax.swing.JComponent.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)

  • A question about a piece of scan port program

    The program as the following:
    import java.net.*;
    import java.io.*;
    public class Scan
      public static void main(String[] args)
        String host;
        Socket theTCPsocket;
        InetAddress hostAddress;
        if (args.length < 1)
          host = "localhost";
        else
          host = args[0];
        try
          hostAddress=InetAddress.getByName(host);
       for (int i = 0; i < 65535; i++)
            try
              theTCPsocket = new Socket(hostAddress, i);
              System.out.print("TCP port " + i + " of " + host + " is open");
              switch(i)
                case 21:
                System.out.println("(maybe there is a FTP server is running)");
                break;
                case 23:
                System.out.println("(maybe there is a TELNET server is running)");
                break;
                case 25:
                System.out.println("(maybe there is a SMTP server is running)");
                break;
                case 80:
                System.out.println("(maybe there is a HTTP server is running)");
                break;
                case 110:
                System.out.println("(maybe there is a POP server is running)");
                break;
                case 139:
                System.out.println("(This server's netBIOS is reachable)");
                break;
              theTCPsocket.close();
            catch (IOException e)
         catch (UnknownHostException e)
          System.err.println("the hostname:"+host+"is unknown or can not be analysed!");
    }  The question is: I don't know why the System.out.print("TCP port " + i + " of " + host + " is open"); in for (int i = 0; i < 65535; i++)
    try
    theTCPsocket = new Socket(hostAddress, i);
    System.out.print("TCP port " + i + " of " + host + " is open"); is not run everytime when i equal from 0 to65535,but it just run when i=21 and etc?
    Please help me!
    Thanks!
    yours
    spark
    Message was edited by:
    spark077

    Don't run this program except on your own computer(s), but the answer is that if the port isn't being listened to, the Socket constructor throws an IOException which you are handling with the following code:
        {}and then continuing with the loop. So if the port isn't being listened to, nothing will be printed.

  • RMI uses incorrect InetAddress on machine with two nics

    Hello All,
    RMI registry and server run on the same host. Host has two nics, one assigned for private network (192.168.x.x) and another for global.
    For the sake of creating RMI registry I use the global one and specify it as four dot-delimited numbers instead of machine name:
    Registry registry = LocateRegistry.getRegistry("xxx.xxx.xxx.xxx", rmiPort); // "xxx.xxx.xxx.xxx" is global IP addressInvoking a method with just a port as a single parameter causes RMI to bind to the private address, so I avoided that trouble by using numeric IP.
    Remote client is able to locate the registry and extract the stub from it now, but ironically retrieved stub contains private address inside.
    Debugger shows that the proxy stub contains TCPEndpoint which resolves to 192.168.xxx.xxx:yyyy
    I am exporting the object on the server side by using UnicastRemoteObject.exportObject(myObj, 0) method.
    Unfortunately, there is no method which would allow to specify the InetAddress to bind the object on.
    I've seen the battle on page [Remote Method Invocation (RMI) - Why does RMI server sets its connection address?|http://forums.sun.com/thread.jspa?threadID=5366985].
    Close questions are discussed, but I haven't found answer on my question.
    Is there an ability to specify the address when exporting the object?
    Or any workaround to let the client retrieve the proper stub which can be used to send requests to the server?
    Thank,
    Alex.

    For the sake of creating RMI registry I use the global one and specify it as four dot-delimited numbers instead of machine name:
    Registry registry = LocateRegistry.getRegistry("xxx.xxx.xxx.xxx", rmiPort); // "xxx.xxx.xxx.xxx" is global IP address
    That doesn't create a registry. It just returns a stub to an existing registry.
    Invoking a method with just a port as a single parameter causes RMI to bind to the private address.No it doesn't. It causes RMI to construct a stub using "localhost" as the hostname. If this maps to the private address via your /etc/hosts file or DNS, so be it.
    Remote client is able to locate the registry and extract the stub from it now, but ironically retrieved stub contains private address inside.Nothing ironic about it. The stub doesn't know where you got it from. The address inside the stub is controlled by what "localhost" resolves to in the server JVM. If it resolves to something inconvenient, either change that or set the system property java.rmi.server.hostname to the desired IP address or hostname in the server JVM.
    Unfortunately, there is no method which would allow to specify the InetAddress to bind the object on.You don't normally need one, see above, although in pathological cases you could use an RMIServerSocketFactory, which does give you that ability.
    I haven't found answer on my question.See also the RMI FAQ, item A.1.
    Is there an ability to specify the address when exporting the object? See above.

  • Problem when used InetAddress class in Applet

    Hi all.
    I'DongPG from Vietnam.
    I have a question'How to get IP that different from IP default "127.0.0.1" address'.
    I've built an applet where i used InetAddress class to get browser'IP follow:
    InetAddress localIP = InetAddress.getLocalHost();
    String strIP=localIP.getHostAddress();
    I used JBuilder to build applet. It's gotten IP right. Ex:strIP='192.168.100.1'
    But when i used browser link to my Applet in WebServer, it only return strIP='127.0.0.1'
    Thank a lot!

    Wrong forum and cross posted as well.

  • Exception when querying java.lang.InetAddress

    Hi,
    When attempting to query an object based on its ipaddress, I ran into the following problem:
    [java] Exception in thread "main" <4|false|4.0.1> kodo.persistence.ArgumentException: The specified parameter of type "class java.net.Inet4Address" is not a valid query parameter.
    [java] at kodo.jdbc.sql.DBDictionary.setUnknown(DBDictionary.java:1347)
    [java] at kodo.jdbc.sql.SQLBuffer.setParameters(SQLBuffer.java:638)
    [java] at kodo.jdbc.sql.SQLBuffer.prepareStatement(SQLBuffer.java:539)
    [java] at kodo.jdbc.sql.SQLBuffer.prepareStatement(SQLBuffer.java:512)
    [java] at kodo.jdbc.sql.SelectImpl.execute(SelectImpl.java:332)
    [java] at kodo.jdbc.sql.SelectImpl.execute(SelectImpl.java:301)
    [java] at kodo.jdbc.sql.Union$UnionSelect.execute(Union.java:642)
    [java] at kodo.jdbc.sql.Union.execute(Union.java:326)
    [java] at kodo.jdbc.sql.Union.execute(Union.java:313)
    [java] at kodo.jdbc.kernel.SelectResultObjectProvider.open(SelectResultObjectProvider.java:98)
    [java] at com.solarmetric.rop.EagerResultList.<init>(EagerResultList.java:22)
    [java] at kodo.kernel.QueryImpl.toResult(QueryImpl.java:1445)
    [java] at kodo.kernel.QueryImpl.execute(QueryImpl.java:1167)
    [java] at kodo.kernel.QueryImpl.execute(QueryImpl.java:953)
    [java] at kodo.kernel.QueryImpl.execute(QueryImpl.java:871)
    [java] at kodo.kernel.DelegatingQuery.execute(DelegatingQuery.java:774)
    [java] at kodo.persistence.QueryImpl.execute(QueryImpl.java:241)
    [java] at kodo.persistence.QueryImpl.getResultList(QueryImpl.java:290)
    [java] at test.MainLine.main(MainLine.java:196)
    My query:
    ("select i from Interface i where i.testAddress = addr").setParameter("addr", InetAddress.getLocalHost())
    I have tried this using Inet4Address in the hope that Kodo was having some issues with polymorphism but the same problem occurs.
    The mapping is defined as follows:
    @Basic
    public InetAddress getTestAddress ()
    return _test;
    public void setTestAddress (InetAddress test)
    _test = test;
    I have tried using @Lob but this made no difference. Is it possible to create queries based on a LOB?

    java.sql.SQLException: Invalid state, the Connection object is closed
    It answers your question to an extent. Check if your connection or recordset object is closed
    cheers,
    Siddhs

  • AV3 question

    hi friends:
    I am been looking into AVTransmit2.java, AVReceive2.java and AVTransmit3, AVReceive3
    can your tell me what is the input and output of this function
    where can I change to transmit and receive my DataSource
    and Then presenting them
    AVTransmit2.java:
    * @(#)AVTransmit2.java     1.4 01/03/13
    * Copyright (c) 1999-2001 Sun Microsystems, Inc. All Rights Reserved.
    * Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
    * modify and redistribute this software in source and binary code form,
    * provided that i) this copyright notice and license appear on all copies of
    * the software; and ii) Licensee does not utilize the software in a manner
    * which is disparaging to Sun.
    * This software is provided "AS IS," without a warranty of any kind. ALL
    * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
    * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
    * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
    * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
    * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
    * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
    * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
    * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
    * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
    * POSSIBILITY OF SUCH DAMAGES.
    * This software is not designed or intended for use in on-line control of
    * aircraft, air traffic, aircraft navigation or aircraft communications; or in
    * the design, construction, operation or maintenance of any nuclear
    * facility. Licensee represents and warrants that it will not use or
    * redistribute the Software for such purposes.
    import java.awt.*;
    import java.io.*;
    import java.net.InetAddress;
    import javax.media.*;
    import javax.media.protocol.*;
    import javax.media.protocol.DataSource;
    import javax.media.format.*;
    import javax.media.control.TrackControl;
    import javax.media.control.QualityControl;
    import javax.media.rtp.*;
    import javax.media.rtp.rtcp.*;
    import com.sun.media.rtp.*;
    public class AVTransmit2 {
        // Input MediaLocator
        // Can be a file or http or capture source
        private MediaLocator locator;
        private String ipAddress;
        private int portBase;
        private Processor processor = null;
        private RTPManager rtpMgrs[];
        private DataSource dataOutput = null;
        public AVTransmit2(MediaLocator locator,
                    String ipAddress,
                    String pb,
                    Format format) {
         this.locator = locator;
         this.ipAddress = ipAddress;
         Integer integer = Integer.valueOf(pb);
         if (integer != null)
             this.portBase = integer.intValue();
         * Starts the transmission. Returns null if transmission started ok.
         * Otherwise it returns a string with the reason why the setup failed.
        public synchronized String start() {
         String result;
         // Create a processor for the specified media locator
         // and program it to output JPEG/RTP
         result = createProcessor();
         if (result != null)
             return result;
         // Create an RTP session to transmit the output of the
         // processor to the specified IP address and port no.
         result = createTransmitter();
         if (result != null) {
             processor.close();
             processor = null;
             return result;
         // Start the transmission
         processor.start();
         return null;
         * Stops the transmission if already started
        public void stop() {
         synchronized (this) {
             if (processor != null) {
              processor.stop();
              processor.close();
              processor = null;
              for (int i = 0; i < rtpMgrs.length; i++) {
                  rtpMgrs.removeTargets( "Session ended.");
              rtpMgrs[i].dispose();
    private String createProcessor() {
         if (locator == null)
         return "Locator is null";
         DataSource ds;
         DataSource clone;
         try {
         ds = javax.media.Manager.createDataSource(locator);
         } catch (Exception e) {
         return "Couldn't create DataSource";
         // Try to create a processor to handle the input media locator
         try {
         processor = javax.media.Manager.createProcessor(ds);
         } catch (NoProcessorException npe) {
         return "Couldn't create processor";
         } catch (IOException ioe) {
         return "IOException creating processor";
         // Wait for it to configure
         boolean result = waitForState(processor, Processor.Configured);
         if (result == false)
         return "Couldn't configure processor";
         // Get the tracks from the processor
         TrackControl [] tracks = processor.getTrackControls();
         // Do we have atleast one track?
         if (tracks == null || tracks.length < 1)
         return "Couldn't find tracks in processor";
         // Set the output content descriptor to RAW_RTP
         // This will limit the supported formats reported from
         // Track.getSupportedFormats to only valid RTP formats.
         ContentDescriptor cd = new ContentDescriptor(ContentDescriptor.RAW_RTP);
         processor.setContentDescriptor(cd);
         Format supported[];
         Format chosen;
         boolean atLeastOneTrack = false;
         // Program the tracks.
         for (int i = 0; i < tracks.length; i++) {
         Format format = tracks[i].getFormat();
         if (tracks[i].isEnabled()) {
              supported = tracks[i].getSupportedFormats();
              // We've set the output content to the RAW_RTP.
              // So all the supported formats should work with RTP.
              // We'll just pick the first one.
              if (supported.length > 0) {
              if (supported[0] instanceof VideoFormat) {
                   // For video formats, we should double check the
                   // sizes since not all formats work in all sizes.
                   chosen = checkForVideoSizes(tracks[i].getFormat(),
                                       supported[0]);
              } else
                   chosen = supported[0];
              tracks[i].setFormat(chosen);
              System.err.println("Track " + i + " is set to transmit as:");
              System.err.println(" " + chosen);
              atLeastOneTrack = true;
              } else
              tracks[i].setEnabled(false);
         } else
              tracks[i].setEnabled(false);
         if (!atLeastOneTrack)
         return "Couldn't set any of the tracks to a valid RTP format";
         // Realize the processor. This will internally create a flow
         // graph and attempt to create an output datasource for JPEG/RTP
         // audio frames.
         result = waitForState(processor, Controller.Realized);
         if (result == false)
         return "Couldn't realize processor";
         // Set the JPEG quality to .5.
         setJPEGQuality(processor, 0.5f);
         // Get the output data source of the processor
         dataOutput = processor.getDataOutput();
         return null;
    * Use the RTPManager API to create sessions for each media
    * track of the processor.
    private String createTransmitter() {
         // Cheated. Should have checked the type.
         PushBufferDataSource pbds = (PushBufferDataSource)dataOutput;
         PushBufferStream pbss[] = pbds.getStreams();
         rtpMgrs = new RTPManager[pbss.length];
         SessionAddress localAddr, destAddr;
         InetAddress ipAddr;
         SendStream sendStream;
         int port;
         SourceDescription srcDesList[];
         for (int i = 0; i < pbss.length; i++) {
         try {
              rtpMgrs[i] = RTPManager.newInstance();     
              // The local session address will be created on the
              // same port as the the target port. This is necessary
              // if you use AVTransmit2 in conjunction with JMStudio.
              // JMStudio assumes - in a unicast session - that the
              // transmitter transmits from the same port it is receiving
              // on and sends RTCP Receiver Reports back to this port of
              // the transmitting host.
              port = portBase + 2*i;
              ipAddr = InetAddress.getByName(ipAddress);
              localAddr = new SessionAddress( InetAddress.getLocalHost(),
                                  port);
              destAddr = new SessionAddress( ipAddr, port);
              rtpMgrs[i].initialize( localAddr);
              rtpMgrs[i].addTarget( destAddr);
              System.err.println( "Created RTP session: " + ipAddress + " " + port);
              sendStream = rtpMgrs[i].createSendStream(dataOutput, i);          
              sendStream.start();
         } catch (Exception e) {
              return e.getMessage();
         return null;
    * For JPEG and H263, we know that they only work for particular
    * sizes. So we'll perform extra checking here to make sure they
    * are of the right sizes.
    Format checkForVideoSizes(Format original, Format supported) {
         int width, height;
         Dimension size = ((VideoFormat)original).getSize();
         Format jpegFmt = new Format(VideoFormat.JPEG_RTP);
         Format h263Fmt = new Format(VideoFormat.H263_RTP);
         if (supported.matches(jpegFmt)) {
         // For JPEG, make sure width and height are divisible by 8.
         width = (size.width % 8 == 0 ? size.width :
                        (int)(size.width / 8) * 8);
         height = (size.height % 8 == 0 ? size.height :
                        (int)(size.height / 8) * 8);
         } else if (supported.matches(h263Fmt)) {
         // For H.263, we only support some specific sizes.
         if (size.width < 128) {
              width = 128;
              height = 96;
         } else if (size.width < 176) {
              width = 176;
              height = 144;
         } else {
              width = 352;
              height = 288;
         } else {
         // We don't know this particular format. We'll just
         // leave it alone then.
         return supported;
         return (new VideoFormat(null,
                        new Dimension(width, height),
                        Format.NOT_SPECIFIED,
                        null,
                        Format.NOT_SPECIFIED)).intersects(supported);
    * Setting the encoding quality to the specified value on the JPEG encoder.
    * 0.5 is a good default.
    void setJPEGQuality(Player p, float val) {
         Control cs[] = p.getControls();
         QualityControl qc = null;
         VideoFormat jpegFmt = new VideoFormat(VideoFormat.JPEG);
         // Loop through the controls to find the Quality control for
         // the JPEG encoder.
         for (int i = 0; i < cs.length; i++) {
         if (cs[i] instanceof QualityControl &&
              cs[i] instanceof Owned) {
              Object owner = ((Owned)cs[i]).getOwner();
              // Check to see if the owner is a Codec.
              // Then check for the output format.
              if (owner instanceof Codec) {
              Format fmts[] = ((Codec)owner).getSupportedOutputFormats(null);
              for (int j = 0; j < fmts.length; j++) {
                   if (fmts[j].matches(jpegFmt)) {
                   qc = (QualityControl)cs[i];
                   qc.setQuality(val);
                   System.err.println("- Setting quality to " +
                             val + " on " + qc);
                   break;
              if (qc != null)
              break;
    * Convenience methods to handle processor's state changes.
    private Integer stateLock = new Integer(0);
    private boolean failed = false;
    Integer getStateLock() {
         return stateLock;
    void setFailed() {
         failed = true;
    private synchronized boolean waitForState(Processor p, int state) {
         p.addControllerListener(new StateListener());
         failed = false;
         // Call the required method on the processor
         if (state == Processor.Configured) {
         p.configure();
         } else if (state == Processor.Realized) {
         p.realize();
         // Wait until we get an event that confirms the
         // success of the method, or a failure event.
         // See StateListener inner class
         while (p.getState() < state && !failed) {
         synchronized (getStateLock()) {
              try {
              getStateLock().wait();
              } catch (InterruptedException ie) {
              return false;
         if (failed)
         return false;
         else
         return true;
    * Inner Classes
    class StateListener implements ControllerListener {
         public void controllerUpdate(ControllerEvent ce) {
         // If there was an error during configure or
         // realize, the processor will be closed
         if (ce instanceof ControllerClosedEvent)
              setFailed();
         // All controller events, send a notification
         // to the waiting thread in waitForState method.
         if (ce instanceof ControllerEvent) {
              synchronized (getStateLock()) {
              getStateLock().notifyAll();
    * Sample Usage for AVTransmit2 class
    public static void main(String [] args) {
         // We need three parameters to do the transmission
         // For example,
         // java AVTransmit2 file:/C:/media/test.mov 129.130.131.132 42050
         /*if (args.length < 3) {
         prUsage();
         Format fmt = null;
         int i = 0;
         // Create a audio transmit object with the specified params.
         //AVTransmit2 at = new AVTransmit2(new MediaLocator(args[i]), args[i+1], args[i+2], fmt);
         AVTransmit2 at = new AVTransmit2(new MediaLocator("file:/C:/sample.mp3"), "172.24.30.58","8088",fmt);
         // Start the transmission
         String result = at.start();
         // result will be non-null if there was an error. The return
         // value is a String describing the possible error. Print it.
         if (result != null) {
         System.err.println("Error : " + result);
         System.exit(0);
         System.err.println("Start transmission for 60 seconds...");
         // Transmit for 60 seconds and then close the processor
         // This is a safeguard when using a capture data source
         // so that the capture device will be properly released
         // before quitting.
         // The right thing to do would be to have a GUI with a
         // "Stop" button that would call stop on AVTransmit2
         try {
         Thread.currentThread().sleep(60000);
         } catch (InterruptedException ie) {
         // Stop the transmission
         at.stop();
         System.err.println("...transmission ended.");
         System.exit(0);
    static void prUsage() {
         System.err.println("Usage: AVTransmit2 <sourceURL> <destIP> <destPortBase>");
         System.err.println(" <sourceURL>: input URL or file name");
         System.err.println(" <destIP>: multicast, broadcast or unicast IP address for the transmission");
         System.err.println(" <destPortBase>: network port numbers for the transmission.");
         System.err.println(" The first track will use the destPortBase.");
         System.err.println(" The next track will use destPortBase + 2 and so on.\n");
         System.exit(0);
    AVReceive2.java/*
    * @(#)AVReceive2.java     1.3 01/03/13
    * Copyright (c) 1999-2001 Sun Microsystems, Inc. All Rights Reserved.
    * Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
    * modify and redistribute this software in source and binary code form,
    * provided that i) this copyright notice and license appear on all copies of
    * the software; and ii) Licensee does not utilize the software in a manner
    * which is disparaging to Sun.
    * This software is provided "AS IS," without a warranty of any kind. ALL
    * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
    * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
    * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
    * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
    * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
    * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
    * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
    * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
    * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
    * POSSIBILITY OF SUCH DAMAGES.
    * This software is not designed or intended for use in on-line control of
    * aircraft, air traffic, aircraft navigation or aircraft communications; or in
    * the design, construction, operation or maintenance of any nuclear
    * facility. Licensee represents and warrants that it will not use or
    * redistribute the Software for such purposes.
    import java.io.*;
    import java.awt.*;
    import java.net.*;
    import java.awt.event.*;
    import java.util.Vector;
    import javax.media.*;
    import javax.media.rtp.*;
    import javax.media.rtp.event.*;
    import javax.media.rtp.rtcp.*;
    import javax.media.protocol.*;
    import javax.media.protocol.DataSource;
    import javax.media.format.AudioFormat;
    import javax.media.format.VideoFormat;
    import javax.media.Format;
    import javax.media.format.FormatChangeEvent;
    import javax.media.control.BufferControl;
    * AVReceive2 to receive RTP transmission using the new RTP API.
    public class AVReceive2 implements ReceiveStreamListener, SessionListener,
         ControllerListener
    String sessions[] = null;
    RTPManager mgrs[] = null;
    Vector playerWindows = null;
    boolean dataReceived = false;
    Object dataSync = new Object();
    public AVReceive2(String sessions[]) {
         this.sessions = sessions;
    protected boolean initialize() {
    try {
         InetAddress ipAddr;
         SessionAddress localAddr = new SessionAddress();
         SessionAddress destAddr;
         mgrs = new RTPManager[sessions.length];
         playerWindows = new Vector();
         SessionLabel session;
         // Open the RTP sessions.
         for (int i = 0; i < sessions.length; i++) {
              // Parse the session addresses.
              try {
              session = new SessionLabel(sessions[i]);
              } catch (IllegalArgumentException e) {
              System.err.println("Failed to parse the session address given: " + sessions[i]);
              return false;
              System.err.println(" - Open RTP session for: addr: " + session.addr + " port: " + session.port + " ttl: " + session.ttl);
              mgrs[i] = (RTPManager) RTPManager.newInstance();
              mgrs[i].addSessionListener(this);
              mgrs[i].addReceiveStreamListener(this);
              ipAddr = InetAddress.getByName(session.addr);
              if( ipAddr.isMulticastAddress()) {
              // local and remote address pairs are identical:
              localAddr= new SessionAddress( ipAddr,
                                  session.port,
                                  session.ttl);
              destAddr = new SessionAddress( ipAddr,
                                  session.port,
                                  session.ttl);
              } else {
              localAddr= new SessionAddress( InetAddress.getLocalHost(),
                             session.port);
    destAddr = new SessionAddress( ipAddr, session.port);
              mgrs[i].initialize( localAddr);
              // You can try out some other buffer size to see
              // if you can get better smoothness.
              BufferControl bc = (BufferControl)mgrs[i].getControl("javax.media.control.BufferControl");
              if (bc != null)
              bc.setBufferLength(350);
              mgrs[i].addTarget(destAddr);
    } catch (Exception e){
    System.err.println("Cannot create the RTP Session: " + e.getMessage());
    return false;
         // Wait for data to arrive before moving on.
         long then = System.currentTimeMillis();
         long waitingPeriod = 30000; // wait for a maximum of 30 secs.
         try{
         synchronized (dataSync) {
              while (!dataReceived &&
                   System.currentTimeMillis() - then < waitingPeriod) {
              if (!dataReceived)
                   System.err.println(" - Waiting for RTP data to arrive...");
              dataSync.wait(1000);
         } catch (Exception e) {}
         if (!dataReceived) {
         System.err.println("No RTP data was received.");
         close();
         return false;
    return true;
    public boolean isDone() {
         return playerWindows.size() == 0;
    * Close the players and the session managers.
    protected void close() {
         for (int i = 0; i < playerWindows.size(); i++) {
         try {
              ((PlayerWindow)playerWindows.elementAt(i)).close();
         } catch (Exception e) {}
         playerWindows.removeAllElements();
         // close the RTP session.
         for (int i = 0; i < mgrs.length; i++) {
         if (mgrs[i] != null) {
    mgrs[i].removeTargets( "Closing session from AVReceive2");
    mgrs[i].dispose();
              mgrs[i] = null;
    PlayerWindow find(Player p) {
         for (int i = 0; i < playerWindows.size(); i++) {
         PlayerWindow pw = (PlayerWindow)playerWindows.elementAt(i);
         if (pw.player == p)
              return pw;
         return null;
    PlayerWindow find(ReceiveStream strm) {
         for (int i = 0; i < playerWindows.size(); i++) {
         PlayerWindow pw = (PlayerWindow)playerWindows.elementAt(i);
         if (pw.stream == strm)
              return pw;
         return null;
    * SessionListener.
    public synchronized void update(SessionEvent evt) {
         if (evt instanceof NewParticipantEvent) {
         Participant p = ((NewParticipantEvent)evt).getParticipant();
         System.err.println(" - A new participant had just joined: " + p.getCNAME());
    * ReceiveStreamListener
    public synchronized void update( ReceiveStreamEvent evt) {
         RTPManager mgr = (RTPManager)evt.getSource();
         Participant participant = evt.getParticipant();     // could be null.
         ReceiveStream stream = evt.getReceiveStream(); // could be null.
         if (evt instanceof RemotePayloadChangeEvent) {
         System.err.println(" - Received an RTP PayloadChangeEvent.");
         System.err.println("Sorry, cannot handle payload change.");
         System.exit(0);
         else if (evt instanceof NewReceiveStreamEvent) {
         try {
              stream = ((NewReceiveStreamEvent)evt).getReceiveStream();
              DataSource ds = stream.getDataSource();
              // Find out the formats.
              RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
              if (ctl != null){
              System.err.println(" - Recevied new RTP stream: " + ctl.getFormat());
              } else
              System.err.println(" - Recevied new RTP stream");
              if (participant == null)
              System.err.println(" The sender of this stream had yet to be identified.");
              else {
              System.err.println(" The stream comes from: " + participant.getCNAME());
              // create a player by passing datasource to the Media Manager
              Player p = javax.media.Manager.createPlayer(ds);
              if (p == null)
              return;
              p.addControllerListener(this);
              p.realize();
              PlayerWindow pw = new PlayerWindow(p, stream);
              playerWindows.addElement(pw);
              // Notify intialize() that a new stream had arrived.
              synchronized (dataSync) {
              dataReceived = true;
              dataSync.notifyAll();
         } catch (Exception e) {
              System.err.println("NewReceiveStreamEvent exception " + e.getMessage());
              return;
         else if (evt instanceof StreamMappedEvent) {
         if (stream != null && stream.getDataSource() != null) {
              DataSource ds = stream.getDataSource();
              // Find out the formats.
              RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
              System.err.println(" - The previously unidentified stream ");
              if (ctl != null)
              System.err.println(" " + ctl.getFormat());
              System.err.println(" had now been identified as sent by: " + participant.getCNAME());
         else if (evt instanceof ByeEvent) {
         System.err.println(" - Got \"bye\" from: " + participant.getCNAME());
         PlayerWindow pw = find(stream);
         if (pw != null) {
              pw.close();
              playerWindows.removeElement(pw);
    * ControllerListener for the Players.
    public synchronized void controllerUpdate(ControllerEvent ce) {
         Player p = (Player)ce.getSourceController();
         if (p == null)
         return;
         // Get this when the internal players are realized.
         if (ce instanceof RealizeCompleteEvent) {
         PlayerWindow pw = find(p);
         if (pw == null) {
              // Some strange happened.
              System.err.println("Internal error!");
              System.exit(-1);
         pw.initialize();
         pw.setVisible(true);
         p.start();
         if (ce instanceof ControllerErrorEvent) {
         p.removeControllerListener(this);
         PlayerWindow pw = find(p);
         if (pw != null) {
              pw.close();     
              playerWindows.removeElement(pw);
         System.err.println("AVReceive2 internal error: " + ce);
    * A utility class to parse the session addresses.
    class SessionLabel {
         public String addr = null;
         public int port;
         public int ttl = 1;
         SessionLabel(String session) throws IllegalArgumentException {
         int off;
         String portStr = null, ttlStr = null;
         if (session != null && session.length() > 0) {
              while (session.length() > 1 && session.charAt(0) == '/')
              session = session.substring(1);
              // Now see if there's a addr specified.
              off = session.indexOf('/');
              if (off == -1) {
              if (!session.equals(""))
                   addr = session;
              } else {
              addr = session.substring(0, off);
              session = session.substring(off + 1);
              // Now see if there's a port specified
              off = session.indexOf('/');
              if (off == -1) {
                   if (!session.equals(""))
                   portStr = session;
              } else {
                   portStr = session.substring(0, off);
                   session = session.substring(off + 1);
                   // Now see if there's a ttl specified
                   off = session.indexOf('/');
                   if (off == -1) {
                   if (!session.equals(""))
                        ttlStr = session;
                   } else {
                   ttlStr = session.substring(0, off);
         if (addr == null)
              throw new IllegalArgumentException();
         if (portStr != null) {
              try {
              Integer integer = Integer.valueOf(portStr);
              if (integer != null)
                   port = integer.intValue();
              } catch (Throwable t) {
              throw new IllegalArgumentException();
         } else
              throw new IllegalArgumentException();
         if (ttlStr != null) {
              try {
              Integer integer = Integer.valueOf(ttlStr);
              if (integer != null)
                   ttl = integer.intValue();
              } catch (Throwable t) {
              throw new IllegalArgumentException();
    * GUI classes for the Player.
    class PlayerWindow extends Frame {
         Player player;
         ReceiveStream stream;
         PlayerWindow(Player p, ReceiveStream strm) {
         player = p;
         stream = strm;
         public void initialize() {
         add(new PlayerPanel(player));
         public void close() {
         player.close();
         setVisible(false);
         dispose();
         public void addNotify() {
         super.addNotify();
         pack();
    * GUI classes for the Player.
    class PlayerPanel extends Panel {
         Component vc, cc;
         PlayerPanel(Player p) {
         setLayout(new BorderLayout());
         if ((vc = p.getVisualComponent()) != null)
              add("Center", vc);
         if ((cc = p.getControlPanelComponent()) != null)
              add("South", cc);
         public Dimension getPreferredSize() {
         int w = 0, h = 0;
         if (vc != null) {
              Dimension size = vc.getPreferredSize();
              w = size.width;
              h = size.height;
         if (cc != null) {
              Dimension size = cc.getPreferredSize();
              if (w == 0)
              w = size.width;
              h += size.height;
         if (w < 160)
              w = 160;
         return new Dimension(w, h);
    public static void main(String argv[]) {
         // if (argv.length == 0)
         // prUsage();
         String[] sessions = {"172.24.30.58/8080/1"} ;
         AVReceive2 avReceive = new AVReceive2(sessions);
         if (!avReceive.initialize()) {
         System.err.println("Failed to initialize the sessions.");
         System.exit(-1);
         // Check to see if AVReceive2 is done.
         try {
         while (!avReceive.isDone())
              Thread.sleep(1000);
         } catch (Exception e) {}
         System.err.println("Exiting AVReceive2");
    static void prUsage() {
         System.err.println("Usage: AVReceive2 <session> <session> ...");
         System.err.println(" <session>: <address>/<port>/<ttl>");
         System.exit(0);
    }// end of AVReceive2
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             

    Question is ancient, and answered by experience.

  • Urgent question about Thread-safety

    Hi all,
    the new tiger release provides an "isReachable()" method for the "InetAddress" object.
    I've found, this method is not thread-safe (see the source and output below).
    It returns true for all threads, when multiple threads using this method with different adresses are running at a time and one of the addresses is reachable. This happens only on WinXp. Running on Linux, the output is like expected.
    I've tried to report this as a bug. But the gurus answered, taking care of thread safety would be a "programmers task".
    My question is, what can I do, to be thread-safe in my case?
    W.U.
    import java.util.*;
    import java.net.*;
    public class IsReachableTest_1 extends Thread{
        static volatile int inst=1;
        static final String NET_ADDR="192.168.111.";
        int instance=inst++;
        public void run(){
            for(int i=19;i<23;i++){
                try{
                    long start=System.nanoTime();
                    if(InetAddress.getByName(NET_ADDR+i).isReachable(1000))
                        System.out.println(""+instance+"--host found at:"+NET_ADDR+i+"--time:"+(System.nanoTime()-start)/1000000);
                    else
                        System.out.println(""+instance+"--no host at:"+NET_ADDR+i);
                }catch(Exception e){System.out.println(""+instance+"--ERROR "+e.toString());}
            System.out.println(""+instance+"--done.");
        public static void main(String[] args) {
            System.out.println(
                System.getProperty("java.vendor")+" "+
                System.getProperty("java.version")+" running on "+
                System.getProperty("os.name")+" "+
                System.getProperty("os.version"));
            Vector v=new Vector();
            System.out.println("\nTest 1: One after another:");
            for(int i=0;i<10;i++){
                IsReachableTest_1 t;
                t=new IsReachableTest_1();
                t.start();
                try{
                    t.join();
                }catch(Exception e){System.out.println("MAIN1: "+e.toString());}
            System.out.println("\nTest 2: All together:");
            inst=1;
            for(int i=0;i<10;i++){
                IsReachableTest_1 t;
                t=new IsReachableTest_1();
                t.start();
                v.addElement(t);
            for(Iterator i=v.iterator();i.hasNext();)
                try{
                    ((IsReachableTest_1)i.next()).join();
                }catch(Exception e){System.out.println("MAIN2: "+e.toString());}
                System.out.println("\nALL DONE");
    And here is the output, when running on WinXp:
    Sun Microsystems Inc. 1.5.0-beta running on Windows XP 5.1
    Test 1: One after another:
    1--no host at:192.168.111.19
    1--no host at:192.168.111.20
    1--host found at:192.168.111.21--time:2
    1--no host at:192.168.111.22
    1--done.
    2--no host at:192.168.111.19
    2--no host at:192.168.111.20
    2--host found at:192.168.111.21--time:4
    2--no host at:192.168.111.22
    2--done.
    3--no host at:192.168.111.19
    3--no host at:192.168.111.20
    3--host found at:192.168.111.21--time:1
    3--no host at:192.168.111.22
    3--done.
    4--no host at:192.168.111.19
    4--no host at:192.168.111.20
    4--host found at:192.168.111.21--time:1
    4--no host at:192.168.111.22
    4--done.
    5--no host at:192.168.111.19
    5--no host at:192.168.111.20
    5--host found at:192.168.111.21--time:3
    5--no host at:192.168.111.22
    5--done.
    6--no host at:192.168.111.19
    6--no host at:192.168.111.20
    6--host found at:192.168.111.21--time:1
    6--no host at:192.168.111.22
    6--done.
    7--no host at:192.168.111.19
    7--no host at:192.168.111.20
    7--host found at:192.168.111.21--time:1
    7--no host at:192.168.111.22
    7--done.
    8--no host at:192.168.111.19
    8--no host at:192.168.111.20
    8--host found at:192.168.111.21--time:1
    8--no host at:192.168.111.22
    8--done.
    9--no host at:192.168.111.19
    9--no host at:192.168.111.20
    9--host found at:192.168.111.21--time:1
    9--no host at:192.168.111.22
    9--done.
    10--no host at:192.168.111.19
    10--no host at:192.168.111.20
    10--host found at:192.168.111.21--time:1
    10--no host at:192.168.111.22
    10--done.
    Test 2: All together:
    1--no host at:192.168.111.19
    2--no host at:192.168.111.19
    3--no host at:192.168.111.19
    4--no host at:192.168.111.19
    5--no host at:192.168.111.19
    6--no host at:192.168.111.19
    7--no host at:192.168.111.19
    8--no host at:192.168.111.19
    9--no host at:192.168.111.19
    10--no host at:192.168.111.19
    2--no host at:192.168.111.20
    3--no host at:192.168.111.20
    6--host found at:192.168.111.20--time:924 <----- this host does not exist!!
    5--host found at:192.168.111.20--time:961 <----- this host does not exist!!
    10--host found at:192.168.111.20--time:778 <----- this host does not exist!!
    9--host found at:192.168.111.20--time:815 <----- this host does not exist!!
    2--host found at:192.168.111.21--time:37
    7--host found at:192.168.111.20--time:888 <----- this host does not exist!!
    8--host found at:192.168.111.20--time:852 <----- this host does not exist!!
    4--host found at:192.168.111.20--time:997 <----- this host does not exist!!
    1--host found at:192.168.111.20--time:1107 <----- this host does not exist!!
    3--host found at:192.168.111.21--time:38
    6--host found at:192.168.111.21--time:1
    5--host found at:192.168.111.21--time:1
    10--host found at:192.168.111.21--time:2
    2--host found at:192.168.111.22--time:3 <----- this host does not exist!!
    9--host found at:192.168.111.21--time:2
    7--host found at:192.168.111.21--time:1
    4--host found at:192.168.111.21--time:3
    1--host found at:192.168.111.21--time:39
    2--done.
    1--host found at:192.168.111.22--time:5 <----- this host does not exist!!
    1--done.
    10--host found at:192.168.111.22--time:40 <----- this host does not exist!!
    3--host found at:192.168.111.22--time:192 <----- this host does not exist!!
    6--host found at:192.168.111.22--time:75 <----- this host does not exist!!
    8--host found at:192.168.111.21--time:230
    5--host found at:192.168.111.22--time:155 <----- this host does not exist!!
    4--host found at:192.168.111.22--time:78 <----- this host does not exist!!
    9--host found at:192.168.111.22--time:77 <----- this host does not exist!!
    7--host found at:192.168.111.22--time:76 <----- this host does not exist!!
    10--done.
    6--done.
    4--done.
    5--done.
    3--done.
    7--done.
    9--done.
    8--no host at:192.168.111.22
    8--done.
    ALL DONE

    I created this test (it's basically the same as your class):
    import java.util.*;
    import java.net.*;
    public class IsReachableTest_2 implements Runnable {
        private final String[] addresses = new String[] {
             "www.sun.com",
             "129.42.16.99" // www.ibm.com which is not reachable
        public void run(){
            try {
                for (int i = 0; i < addresses.length; i++) {
                    final long start = System.nanoTime();
                    final String address = addresses;
         if (InetAddress.getByName(address).isReachable(5000)) {
         System.out.println(Thread.currentThread().getName() + ": Host found at: " + address +
              " --time: " + (System.nanoTime() - start) / 1000);
         } else System.out.println("no host at: " + address);
    } catch(Exception e){
    e.printStackTrace();
    System.out.println("Thread " + Thread.currentThread().getName() + " DONE");
    public static void main(String[] args) {
    System.out.println(
         System.getProperty("java.vendor") +
         " " +
         System.getProperty("java.version") +
         " running on " +
         System.getProperty("os.name") +
         " " +
         System.getProperty("os.version")
    for (int i = 0; i < 10; i++) {
         final Thread t = new Thread(new IsReachableTest_2(), "THREAD " + (i+1));
         t.start();
    And I get:
    Sun Microsystems Inc. 1.5.0-beta running on Windows 2000 5.0
    THREAD 1: Host found at: www.sun.com --time: 217653
    THREAD 3: Host found at: www.sun.com --time: 214404
    THREAD 6: Host found at: www.sun.com --time: 214900
    THREAD 4: Host found at: www.sun.com --time: 215901
    THREAD 5: Host found at: www.sun.com --time: 216666
    THREAD 10: Host found at: www.sun.com --time: 216620
    THREAD 9: Host found at: www.sun.com --time: 217405
    THREAD 2: Host found at: www.sun.com --time: 220705
    THREAD 7: Host found at: www.sun.com --time: 220845
    THREAD 8: Host found at: www.sun.com --time: 221384
    no host at: 129.42.16.99
    Thread THREAD 4 DONE
    no host at: 129.42.16.99
    Thread THREAD 6 DONE
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    Thread THREAD 5 DONE
    Thread THREAD 10 DONE
    Thread THREAD 9 DONE
    Thread THREAD 7 DONE
    Thread THREAD 3 DONE
    Thread THREAD 1 DONE
    Thread THREAD 2 DONE
    Thread THREAD 8 DONE
    HOWEVER: I was getting some strange results every so often. Results like:
    Sun Microsystems Inc. 1.5.0-beta running on Windows 2000 5.0
    THREAD 3: Host found at: www.sun.com --time: 261132
    THREAD 9: Host found at: www.sun.com --time: 264183
    THREAD 2: Host found at: www.sun.com --time: 266447
    THREAD 6: Host found at: www.sun.com --time: 266596
    THREAD 8: Host found at: www.sun.com --time: 267192
    THREAD 5: Host found at: www.sun.com --time: 268610
    THREAD 4: Host found at: www.sun.com --time: 269849
    THREAD 1: Host found at: www.sun.com --time: 280978
    THREAD 7: Host found at: www.sun.com --time: 272589
    THREAD 10: Host found at: www.sun.com --time: 273162
    THREAD 3: Host found at: 129.42.16.99 --time: 13657
    Thread THREAD 3 DONE
    THREAD 4: Host found at: 129.42.16.99 --time: 4123
    THREAD 2: Host found at: 129.42.16.99 --time: 9439
    THREAD 5: Host found at: 129.42.16.99 --time: 6681
    THREAD 8: Host found at: 129.42.16.99 --time: 7655
    THREAD 6: Host found at: 129.42.16.99 --time: 8627
    THREAD 9: Host found at: 129.42.16.99 --time: 10586
    Thread THREAD 4 DONE
    Thread THREAD 2 DONE
    Thread THREAD 5 DONE
    Thread THREAD 8 DONE
    Thread THREAD 6 DONE
    Thread THREAD 9 DONE
    no host at: 129.42.16.99
    Thread THREAD 7 DONE
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    Thread THREAD 10 DONE
    Thread THREAD 1 DONE
    Usually the first run after I had compiled the class (!?) This isn't a thread safety problem.

  • Question about opening sockets

    Hello I have some questions about using sockets.
    I made a program which works with sockets.
    I have a class which contains this
    static byte[] send(byte outbuf[], int len, byte recbyt[], long recip[])
            InetAddress dst = InetAddress.getByName(sendip);
            DatagramPacket request = new DatagramPacket(outbuf, len, dst, sendportint);
            DatagramSocket socket = new DatagramSocket();       
    socket.send(request);
      DatagramPacket packet = new DatagramPacket(inbuf, inbuf.length);
    socket.receive(packet);
      }In another class I call this method like this
    for(int i=0;i<rows;i++)
    send(byte outbuf[], int len, byte recbyt[], long recip[])
    }As you can see it opens a socket when sending something but never close. Does this mean that evrytime I call send it opens a new socket??
    So that if rows is 500 after this loop 500 socket are opened??
    When I place close.socket after socket.receive() it works the same. Is this better or not??

    What do you mean with this line
    Method ends, Socket gets GCed and closes on GCDo you mean when the method ends the socket closes??
    And what is GC?

  • Question about java-based server app frameworks

    Hello, I am working on a Java applet application and would like to choose a Java-based scalable server framework to use within my applcation. I have found a few like xsocket or QuickServer and have a question about other. And, also, which is the one You may advise? Yours sincerely, Slawek

    For online gaming server. I first heard of xsocket and started using this, but have the problem with NAT. I now know that I need to initiate connections from client behind NAT (server has a public IP) and send messages from server to client within the same connection. I am doing this the following way (as shown in examples- below), but it appears that server receives messages, but client doesnt. I dont listen on any ports in client application and just need to take advantage of the connection initiated (information go from client to server properly).
    Server-
    try{ nbc = pool.getNonBlockingConnection(inetAddress, 8090);
    try{ nbc.write("|01|______|02|______|03|______|04|______|05|______|06|______|07|______|08|______|09|______|10|______"); }catch(Exception ee){}
    }catch(java.io.IOException f){}
    Client-
    public boolean onData(INonBlockingConnection nbc) throws IOException,ClosedChannelException,BufferUnderflowException,MaxReadSizeExceededException{
    String x = nbc.readStringByLength(100);
    System.out.println("S >> C = "+x);

  • Design question on extending a class

    Hi all,
    I'm working on a team project where we've decided to customize many JComponents for our GUI. We're also extending the models for their respective JComponents. For example, a CustomJTextField (sublass of JTextField) has a CustomDocument (subclass of PlainDocument) as its model.
    My question is this: is it a preferred OO practice (or not) to delegate the methods of CustomDocument to CustomJTextField, given that it's already understood that a CustomJTextField has a CustomDocument as its model by default. An example:
    without delegation:
    CustomJTextField text = new CustomJTextField();
    // 1. get the model
    // 2. determine if it is the type you're expecting
    // 3. if so, cast it and use it
    if (text.getModel() instanceof CustomDocument)
      ((CustomDocument)text.getModel()).doSomeCustomThing();
    }with delegation:
    CustomJTextField text = new CustomJTextField();
    // 1. just ask the componet to do the work
    text.doSomeCustomThing();The second form seems much cleaner, but the argument is that it would be a lot of work to delegate every method of the model to the component, and then have to maintain the delegate methods as well as the model's methods.
    To me, it seems as if I'd rather have more work in one place (the subclassed JComponent) rather than having it spread all throughout the code. Also, isn't calling "getModel()" everywhere considered bad practice? Should a developer using a component even know (or care) what kind of model it has?
    Even though the delegation methods seems to me that is makes the custom components easier to use, I haven't found any written examples (in books or online) of this being done anywhere. All of the examples are directly accessing the model of the component.
    Any thoughts? I'm new to OO programming (as you might have guessed), so be gentle with me.
    Thanks.

    Precisely my intentions. So to reword the question -
    is this a bad practice? My feeling is that a
    developer using a CustomJTextField should expect some
    "extra" behavior (in this case, that of a
    CustomDocument) or else they'd just be using a plain
    old JTextField instead. Bad assumption?Well, I guess that would depend on the custom behaviour. If the customization is to limit the field to only accept certain characters (like numbers only or a limited amount of text), then, as a Swing user, I would expect this behaviour to be handled via a custom Document. I would just say, hey, I need to put a zip code field, so I'll just make a JTextField and give it a ZipCodeDocument. getText() is going to work the same no matter what.
    Another example would be if I have an IP address field. I would create an IPAddressDocument, which does validation of the data entered to prevent invalid octet values and maintain formatting. Now, getText() is going to return a string, but I might want to have a special method in the document class to return a java.net.InetAddress object as a convenience method. I suppose one could subclass JTextField as well to make IPAddressField and add a delegate method, but I'm not sure I would do that.
    But I'm not clear on what these customizations are, so it's hard to say what's best for your situation. I really don't see a problem with either, though, if that's the consensus between you and your associates.
    if you are writing Swing components and models,
    I would expect that it follows certain patterns thatthe
    rest of the Swing components useKnow of any good books, articles, etc. on this?
    Everything I've read talks about extending the
    JComponents, or extending the models, or extending
    the renderers, etc. but always as separate exercises
    and never where it's all going on at once. Even
    then, the examples are usually just that, a way to
    show how it works, not necessarily what the best way
    to do it is.No, I don't know of any good books. They talk about extending JComponent mostly in reference to creating specialized components that are generally different from those provided. The extending models and renderers has to do with the general assumption that if you want a tree component, then JTree already gives you all you need... The customizations will be things like how do the nodes display (renderer) and where do the nodes come from (model). There's not really any link between those, though. The renderer can just be assume to be independant. Here's a node, how do I want to display it? Text, and icon, different color when selected?
    >
    Also, the more I read about MVC, the more confused I
    am about it. Everyone seems to have different
    interpretations as to the roles of each part, how each
    part should interact with each other, etc. I haven't
    seen anything on MVC "patterns" (as it applies to
    Swing).If you haven't read this, maybe it'll shed some light...
    http://java.sun.com/products/jfc/tsc/articles/getting_started/index.html

  • Multithreads and InetAddress

    My goal is to find out what ip addresses are reachable. I want to find out all ip address 192.168.1.1 ~ 192.168.1.255
    The timeout for each ip address is 2 seconds.
    In order to speed up the code I decided to execute each query in its own thread. That way it will only be 2 seconds to find out if all of them are reachable or not.
    I believe it is checking the 192.168.1.1 address correct. It prints out as -64 which is the two's complement. As you can see from the output below it prints out the results of the first one five times instead of all of them.
    Help please.
    import java.net.InetAddress;
    * @author name
    public class IpValidationImpl extends Thread {
        byte[] ipAddr;
        boolean validAddress;
        public IpValidationImpl(byte[] ip){
            ipAddr = ip;
            //System.out.println ((int)ip[0]);
        public void run(){
            int myTimeout = 2000;
            //byte[] address = { 127, 0, 0, 1 };
            try {
                InetAddress addr = InetAddress.getByAddress(ipAddr);
                validAddress = (addr.isReachable( myTimeout ));
                if (validAddress)
                    System.out.println ("Good: " + (int)ipAddr[0] + "." + (int)ipAddr[1] + "." + (int)ipAddr[2]+ "." + (int)ipAddr[3]);
            catch (Exception e){
                System.err.println("Error " + e);
        //public boolean isValid(){
          /// if (ip.get(i).isReachable(2000))
             //      System.out.println("Ip: " + i);
              // else
                //   System.out.println("No Ip: " + i);
    }and this next part is part of my class.
    private void jButtonFindIpActionPerformed(java.awt.event.ActionEvent evt) {                                             
           byte[] address = { (byte)192, (byte)168, 1, 1 };
           byte[] ada = { 127, 0, 0, 1 };
           byte[] abc = { 127, 0, 0, 1 };
           List<IpValidationImpl> ip = new ArrayList<IpValidationImpl>();
           int j;
           for (int i = 0; i < 5; i++){
              j = i + 1;
               abc[3] = (byte)j;
               ip.add(new IpValidationImpl(address));
               ip.get(i).start();
    }output:
    Good: -64.-88.1.1
    Good: -64.-88.1.1
    Good: -64.-88.1.1
    Good: -64.-88.1.1
    Good: -64.-88.1.1
    Edited by: inspiron630 on Mar 23, 2009 10:34 PM
    Edited by: inspiron630 on Mar 23, 2009 10:36 PM

    awesome! last question.
    for some reason its not finding 192.168.1.5. I can successfully ping it but the program doesn't find it. It finds all other ip address on the network though, 192.168.1.1 and 192.168.1.4 and 192.168.1.6.
    is there more that is required for .isReachable then just ping able to ping the address?
    private void jButtonFindIpActionPerformed(java.awt.event.ActionEvent evt) {                                             
           List<IpValidationImpl> ip = new ArrayList<IpValidationImpl>();
           int j = 1;
           for (int i = 0; i < 255; i++, j++){
               byte[] address = { (byte)192, (byte)168, 1, (byte)j };
               ip.add(new IpValidationImpl(address));
               ip.get(i).start();
    import java.net.InetAddress;
    * @author name
    public class IpValidationImpl extends Thread {
        byte[] ipAddr;
        boolean validAddress;
        public IpValidationImpl(byte[] ip){
            ipAddr = ip;
            //System.out.println ((int)ip[0]);
        public void run(){
            int myTimeout = 2000;
            //byte[] address = { 127, 0, 0, 1 };
            try {
                InetAddress addr = InetAddress.getByAddress(ipAddr);
                validAddress = (addr.isReachable( myTimeout ));
                if (validAddress)
                    System.out.println (InetAddress.getByAddress(ipAddr).getHostAddress() );
            catch (Exception e){
                System.err.println("Error " + e);
        //public boolean isValid(){
          /// if (ip.get(i).isReachable(2000))
             //      System.out.println("Ip: " + i);
              // else
                //   System.out.println("No Ip: " + i);
    }

  • Updating InetAddress Cache in the case of changing a live WebSite's IP addr

    Hi all,
    According to Java API documentation for InetAddress Class "The InetAddress class has a cache to store successful as well as unsuccessful host name resolutions. ". I want to be make sure, if I change the IP address of an already live website, this cache is updated immediately after finding the wrong cached IP address in the request to website's URL.
    It would be much more helpful if you explain more about "unsuccessful host name resolutions".
    Regards
    Mehdi.
    Edited by: user9205046 on Oct 6, 2011 3:46 AM

    Thank you for providing the reference. However, I know what should I do with "Time to Live" to modify default behavior of Java security on refreshing negative and positive IP address caches. What I really want to know is when JVM decides one IP must go to negative cache.
    EJP wrote:
    It would be much more helpful if you explain more about "unsuccessful host name resolutions". Err, this is a forum, not a documentation problem report centre. There is no 'you' here that can act on that suggestion, just other Java users like yourself.The "you" in here means someone who wants to answer my question nothing more. Could you please let me know where should I ask this question. You mentioned "documentation report center".

Maybe you are looking for

  • Malfunctio​n in generating word report out of an app (using the report generation toolkit)

    I placed in my program some features that generate a word report with some graphics and text using the report generation toolkit. When I'm in the developing system everything works. But the point is that I have to create an exe for a user and in test

  • Code Break for WEBI report

    Could someone help me in the following code which is in Custom SQL. In the code in the From Clause there is a code which acts as Table. How can I achieve this in WEBI as a single code. SELECT DISTINCT   PENDETAIL.TRADE,   PENDETAIL.PRODUCT,   PENTRAN

  • Operation level costing (OLC)

    We are looking for a way to activate CU-OLC for existing open orders in a production environment. Our business challenge is that we have 8000 existing work orders in the production system not using CU-OLC. Once we promote our SPRO transport to activa

  • ADS: com.adobe.ProcessingException: Problem accessing d(200101)

    Dear Expert, Please resolve my Problem.... I Have made one Form, while testing I am getting Given Above Error, Whereas i have tested So many Standard Adobe Form and z adobe form but They are not giving any error, Please tell me where should i check F

  • Captivate 8 - Runtime Error R6025 - Pure Virtual Function Call

    My teammates and I have Captivate 8 installed recently and while working on a big project for a client, some of our files got corrupted. We couldn't open them and we'd get a Runtime Error R6025 - Pure Virtual Function Call. Some members of the team c