Gethostname

hi,all.....i've just created an application,i want to ask how to get the computer name / get host name of the client computer ? but i dont user java servlet....
thanxxss

ok...........it works......i understood now....
import java.net.InetAddress;
import java.net.UnknownHostException;
public class testh {
     * @param args
     public static void main(String[] args) {
          // TODO Auto-generated method stub
          try {
               String test = InetAddress.getLocalHost().getHostName();
               System.out.println(test);
          } catch (UnknownHostException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
thanxxss...
then i want to ask..........is there a way to make a session without using servlet ?

Similar Messages

  • Problem in Getting host name by using request.getHostName() on solaris 9

    Hi there,
    I'm trying to get the machine name of the system from which the request was initiated by using request.getHostName() on Solaris 9 but it is giving me the IP Address of the machine which har sent the request to the server and the same thing is running on Windows and AIX platform. Can anyone tell me any solution to this problem.
    Thanks in advance.
    Nitin Jain

    Hi Nitin,
    Following is the specification for getRemoteHost()
    "Returns the fully qualified name of the client that sent the request, or the IP address of the client if the name cannot be determined. For HTTP servlets, same as the value of the CGI variable REMOTE_HOST." I think the same would be true for getHostName().....
    So, this can be one possiblity why ur given IP.

  • Help - InetAddress.getHostName() returns the ip address

    Hi,
    After updating two windows XP computers witht the latest windows updates the InetAddress.getHostName() stoped returning the remote computers name and instead returns the ip address. This is how it worked :
    rx = a custom DataPacket class
    public InetAddress from;
    System.out.println("From: "+ (rx.from.getHostName() + "/" + rx.from.getHostAddress()) + " " + receivedMessage + "\r\n");
    printed - From: AUTOTEST1/192.1.3.60 test message
    now it prints this - From: 192.1.3.223/192.1.3.223 test message
    Is there an alternate way of getting a computers host name or is there a work around i could implement?
    I need the computers host names as this is a fault logging program and without the computer name the users will not know who they are sending the mesage to as it displays ip addresses and not the computer name
    Thanks,
    sjs1985

    getCanonicalHostName() still returns the ip address instead of the host name, thanx 4 trying to help me.
    It seems like it is not possible to receive the host name on a fully updated Windows XP computer using the InetAddress class anymore.
    I will have to do it the long way and send a message containing the computer name on start up which would then be added to a list of computernames/ip addresses

  • [Solved] Finding gethostname function in gcc

    I've started to program some in C after reading dussins of tutorials manuals etc.
    But now i want to be able to find out how the functions i use was written in gcc, granted mostly out of nerdy curiosity. As i've understood it the complier is written in C and as such it should somewhere in the source have a function written that's called gethostname() right? The declaration is in a header, sure...  But when i try to grep out the source of gcc4.4.3 i only find a gethostname() function written for fortran, not C.
    What am i missing? is all these functions written somewhere else?
    Last edited by jumzi (2010-03-19 14:02:13)

    GCC is *just* the compiler. It translates human-readable code (well, for a given value of 'readable' ) to object (binary) code. gethostname() is in the glibc source.
    glibc is the library that provides pretty much everything you'd commonly do in C, hence the name 'GNU C Library'.

  • Problem with InetAddress.getByName ("......" ).getHostName(); Help !

    basic problem is that IP does not get resolved under Jdk 1.4 SuSE 7.3
    the following code resolves IP under jdk 1.3 on the same machine, BUT doesn't resolve under Jdk 1.4 on the same machine.
    public class MyTest
         public static void main( String []argv )
              try{
              InetAddress addr = InetAddress.getByName ("64.68.82.30" );               
              String hostName = addr.getHostName();
              System.out.println( hostName );
              }catch( Exception e ){
                   e.printStackTrace();
    hovewer we found that it's not a problem of JDK 1.4 as we have ANOTHER machine with 1.3 and 1.4 running on it where ip gets resolved with the above code.
    maybe some configuration problem ... if so - where and what to configure ...

    more info:
    does not resolve under jdk 1.4 means: it returns the same IP which was passed as a parameter to InetAddress.getByName(). NO exception is thrown.
    reminding: same code on same machine resolves that IP under jdk 1.3

  • InetAddress - getHostName()

    I am using getHostName method of InetAddress class to get the host name of an ip address
    but it returns me the same ip address as hostname(for some addresses it is working fine)
    Following is my code
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    class GetIP extends Frame implements ActionListener{
    TextField t = new TextField("yahoo.com",20);
    TextArea ta = new TextArea("",10,50);
    Button b1 = new Button("Get IP Addresses");
    public GetIP(){
    add(t);
    add(ta);
    add(b1);
    b1.addActionListener(this);
    setLayout(new FlowLayout());
    setSize(400, 300);
    setTitle("Getip");
    setVisible(true);
    public void actionPerformed(ActionEvent ae){
    try{
    ta.setText("");
    InetAddress[] address = InetAddress.getAllByName(t.getText());
    for(int i=0;i<address.length;i++)
    ta.append(address.getHostName()+" : "+address[i].getHostAddress()+"\n");
    catch(Exception e){ta.setText(e.toString());}
    public static void main(String args[]){
    GetIP mainFrame = new GetIP();
    Thank you
    Manu

    Some times for security purpose, the applet security prevents the host name to be known to others.
    Regards
    Deepa Datar

  • Gethostname on 2.5.1 implicit error

    Hi There,
    When I use the "cc" compiler with a program using the function call "gethostname()" it compiles/links fine.
    When I use the "c++" compiler with a program using the function call "gethostname()" I get the following error:
    "implicit declaration of function 'int gethostname()'
    I get the same errors for "ftime" and "setpriority".
    Any ideas how I can rectify this? This works on 2.6 and greater but I have to have this piece of code working on 2.5.1. (or 5.5.1).
    Thanks!

    gethostbyname() function is not defined for 2.5.1 ..it seems the way u are describing it.
    perhaps they have a different version or a little different spelling of it
    good luck

  • Address.getHostName help needed

    Every computer has a Name when connected to the Web via the Internet. The name of my computer when connected is blahblahblah.
    Now when I use address.getHostName(), the name of my computer is displayed, blahblahblah.
    How and is it possible to use this or perhaps something else to get the Name of any computer connected to the web via the Internet?
    Before I get flamed into oblivion, I am not a script kiddie nor a hacker just a developer of Internet related applications.

    You may not be a scriptkitten, but you are in err.
    Not every computer has a name (DNS-name to be precise) when it connects to the internet. DNS is pure for human readability, DNS is also linked to someone's IP, THAT everyone has.
    For example, you have 1 pc connecting to internet using the name mycomputer.tld and another one using 192.168.0.123 (although, that C-Class range is reserverd for internal network).
    You could look into DNS and if there are API's for Java for using (talking to) DNS servers. Still you will need to have the ip of the name you are trying to resolve (resolving = getting the DNS-name linked to an IP if any).
    Hope this helps you in the right direction,
    Greets
    Barre

  • InetAddress.getHostname() takes a lot of time

    hi,
    When i am trying to get the hostname of a solaris machine by passing its ip address, it returns its hostname. If the dnsname of this machine is removed from the dns server, then it will it return its ip address. But it will take 6 seconds whereas in previous case it will take 10 millisecond. This is happening only when i am trying to get the hostname of solaris machine from a windows machine.
    Is there any way to reduce the time delay?
    Please help in this regard.
    Thanks and regards,
    P. Shivaprakash
    code snippet :
    System.out.println("Time before processing : " + new Date(System.currentTimeMillis()));
    try
    hostaddress = (InetAddress.getByName(ipaddress)).getHostName();
    catch(UnknownHostException uhe)
    System.out.println("Exception occured " + uhe);
    System.out.println("Ip address : " + ipaddress);
    System.out.println("Host name : " + hostaddress);
    System.out.println("Time after processing : " + new Date(System.currentTimeMillis()));

    If you have multiple DNS servers, if the first one fails then it moves on to the next until eventually it either finds a result or it gives up.
    When the name exists in your nearest DNS server it responds quickly because it finds the result and comes back. When the name does not exist it travels all round the world until eventually it gives up - not bad through round the world in 10 seconds.
    I seem to recall that there is a TTL setting on the DNS server that restricts how far it will go to get your answer - you may want to try that.

  • Using InetAddress.getHostName() method doesn't return DNS of the machine.

    Hi,
    I have the following simple code:
    String sIP = "SOME_IP";
    InetAddress inet = InetAddress.getByName(sIP);
    sRemoteTerminalID = inet.getHostName();
    The problem is that the output I get for the 'getHostName' method is the same as the IP, while in the DNS, I have an actual name for the machine & not an IP; this happens in one of our clients environements.
    I tried also to use the 'InetAddress.getAllByName' method and analyzing all its output, but got the same results.
    - Is anyone familiar with this issue?
    - Is the 'getHostName' method requires some setting in the underlying environement so using the DNS system is actually allowed?
    I'll appreciate any hint on this.
    Thanks,
    Asaf.

    Below is the code
    I didn't see any bugs
    import java.util.*;
    //Part 1 using the  Random class print out an ArrayList of 10 random numbers
    // - use an iterator object
    public class TryArrayList
       public static void main(String[] args)
       ArrayList myNumberList = new ArrayList();
       Random intRandom = new Random();
       for (int j = 0; j < 11; j++) {
         myNumberList.add(Integer.toString(intRandom.nextInt(10)));
       System.out.println("The random values in the ArrayList are: ");
       Iterator it = myNumberList.iterator();
       while (it.hasNext()) {
         System.out.println(it.next());
         System.out.println();
         //Part 2
         //Use the Collections sort() to order the elements
         Collections.sort(myNumberList);
          System.out.println("The ordered values in the ArrayList are: ");
          Iterator i = myNumberList.iterator();
          while(i.hasNext())
             System.out.println(i.next());
          System.out.println();
          //Part 3
    //Use the Collections reverse() to reverse order the elements
    Collections.reverse(myNumberList);
    System.out.println("The reverse ordered values in the ArrayList are: ");
      Iterator iter = myNumberList.iterator();
      while(iter.hasNext())
         System.out.println(iter.next());
            System.out.println();
            //Part 5 print out the maximum and minimum values
            System.out.println("The maximum value in the ArrayList is: ");
            System.out.println( Collections.max( myNumberList));
            System.out.println();
           System.out.println("The minimum value in the ArrayList is: ");
           System.out.println( Collections.min( myNumberList));
           System.out.println();
           System.out.println("The frequency of the value 5 was");
         System.out.println ( Collections.frequency(myNumberList, (Integer)5));
    } //end of main()
    } //end of class

  • InetAddress.getHostName under Linux

    Hello,
    anyone here know why InetAddress.getHostName sometimes returns <Computer-Name> only and sometimes <Computer-Name>.<Domain-Name>? I just migrated a java project to linux, and on my computer InetAddress.getHostName returns <Computer-Name>.<Domain-Name>. A colleague of mine is already running under Linux and he gets <Computer-Name>. We both have the same Domain-Name, and we have compared network settings and haven't found any differences.
    I have tried to google, but I haven't found anything. Any know the reason for this behaviour?

    After juggling around a bit with the network settings, turning IPv6 on and off, switching between static IP and DHCP (computer-name and domain name remained untouched), the InetAddress.getHostName suddenly returned <computer-name> only. I tried to retrace my configuration changes, and tested InetAddress.getHostName and it only returned <computer-name> without the <domain-name> extension. Did I miss something? Do anyone know when InetAddress.getHostName returns <computer-name> and when it returns <computer-name>.<domain-name>?

  • GetHostName() Help

    I'm having a problem using this method in a JSP page. When I set it to a string, then call it in the page (to see the output) I get an error. Here's the code:
    <%@page contentType="text/html; charset=iso-8859-1" language="java" import="java.io.*,java.util.*,java.sql.*,javax.servlet.*,javax.servlet.http.*,java.text.SimpleDateFormat,java.text.*,java.net.*"%>
    <%
         String url = request.getHostName();
         String addr = request.getRemoteAddr();
    %>
    <%=url%>
    <%=addr%>
    I'm getting an error 500: Method getHostName() not found in interface javax.servlet.http.HttpServletRequest.
    String url = request.getHostName();
    Any suggestions?

    getHostName() is not part of the HttpServletRequest object. If you need this information look at the InetAddress class.

  • InetAddress.getLocalHost().getHostName()  throwing unknownHostException

    When i am executing this statement from a simple java program its working fine. But when I call the statement from JSP or servlet, its throwing UnknownhostException.
    I am using tomcat3.3.1 as web server running on Sun Solaris.
    Is there problem with setting of tomcat ???
    Please help me out.

    I tried nslookup at the shell prompt. It was showing unknown host for the ip address. I contacted our network people and came to know that the server is on internet and thats why it was not showing the local ip address host name in nslookup. Then I tried the internet ip address and host name of the server in the stetement and it worked out. Hope i am clear to u. Now the statement is running fine.
    Actually I was trying to send mail using Smtp class and while dong that it was throwing UnknownHostException. Then i found out the Intaddress.getLocalHost() was the stmt throwing this error. Now as I am giving the internet address for constructor of new SmtpClient() method, it is not giving this error and my mail is getting delivered. But it processis taking lot of time. It takes @ 15 minutes to send a mail.
    Can u help me out in this????
    Thanx for help.......

  • How to get InetAddress.getHostName() to skip non valid ips.

    im trying to build a network mapper that will scan all ip addresses up to 192.168.0.256 indexing the last 3 digits from 0 to 257. It takes less than a second to grab the host name of ip addresses that are alive, but for the rest that are down, it takes 10-20 seconds before returning the ip addresses. How can I send a packet to see if the host is up before asking for the hostName. I tried creating a socket to connect to various ports but even that takes 10-20 seconds for downed hosts. Thanks in advance.

    You want to do it fast?
    You can't, that isn't how sockets work. Sometimes it takes minutes to connect.
    If you are scanning local addresses and it takes that long, then something is wrong with your intranet and you need to talk to your sys admin.
    If you are scanning internet addresses then that is how long they take (assuming that something is not wrong with your internal network.)
    You can use a tentative approval process and threads to allow some processing to proceed. That, of course, depends on what you are doing.

  • Problem with threads running javaw

    Hi,
    Having a problem with multi thread programming using client server sockets. The program works find when starting the the application in a console using java muti.java , but when using javaw multi.java the program doesnt die and have to kill it in the task manager. The program doesnt display any of my gui error messages either when the server disconnect the client. all works find in a console. any advice on this as I havent been able to understand why this is happening? any comment would be appreciated.
    troy.

    troy,
    Try and post a minimum code sample of your app which
    does not work.
    When using javaw, make sure you redirect the standard
    error and standard output streams to file.
    Graeme.Hi Graeme,
    I dont understand what you mean by redirection to file? some of my code below.
    The code works fine under a console, code is supposed to exit when the client (the other server )disconnects. the problem is that but the clientworker side of the code still works. which under console it doesnt.
    public class Server{
    ServerSocket aServerSocket;
    Socket dianosticsSocket;
    Socket nPortExpress;
    ClientListener aClientListener;
    LinkedList queue = new LinkedList();
    int port = 0;
    int clientPort = 0;
    String clientName = null;
    boolean serverAlive = true;
    * Server constructor generates a server
    * Socket and then starts a client threads.
    * @param aPort      socket port of local machine.
    public Server(int aPort, String aClientName, int aClientPort){
    port = aPort;
    clientName = aClientName;
    clientPort = aClientPort;
    try{
    // create a new thread
    aServerSocket = new ServerSocket(port) ;
    // connect to the nPortExpress
    aClientListener = new ClientListener(InetAddress.getByName(clientName), clientPort, queue,this);
    // aClientListener.setDaemon(true);
    aClientListener.start();
    // start a dianostic port
    DiagnosticsServer aDiagnosticsServer = new DiagnosticsServer(port,queue,aClientListener);
    // System.out.println("Server is running on port " + port + "...");
    // System.out.println("Connect to nPort");
    catch(Exception e)
    // System.out.println("ERROR: Server port " + port + " not available");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Server port " + port + " not available", JOptionPane.ERROR_MESSAGE);
    serverAlive = false;
    System.exit(1);
    while(serverAlive&&aClientListener.hostSocket.isConnected()){
    try{
    // connect the client
    Socket aClient = aServerSocket.accept();
    //System.out.println("open client connection");
    //System.out.println("client local: "+ aClient.getLocalAddress().toString());
    // System.out.println("client localport: "+ aClient.getLocalPort());
    // System.out.println("client : "+ aClient.getInetAddress().toString());
    // System.out.println("client port: "+ aClient.getLocalPort());
    // make a new client thread
    ClientWorker clientThread = new ClientWorker(aClient, queue, aClientListener, false);
    // start thread
    clientThread.start();
    catch(Exception e)
    //System.out.println("ERROR: Client connection failure");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Client connection failure", JOptionPane.ERROR_MESSAGE);
    }// end while
    } // end constructor Server
    void serverExit(){
         JOptionPane.showMessageDialog(null, "Server ","ERROR: nPort Failure", JOptionPane.ERROR_MESSAGE);
         System.exit(1);
    }// end class Server
    *** connect to another server
    public class ClientListener extends Thread{
    InetAddress hostName;
    int hostPort;
    Socket hostSocket;
    BufferedReader in;
    PrintWriter out;
    boolean loggedIn;
    LinkedList queue;      // reference to Server queue
    Server serverRef; // reference to main server
    * ClientListener connects to the host server.
    * @param aHostName is the name of the host eg server name or IP address.
    * @param aHostPort is a port number of the host.
    * @param aLoginName is the users login name.
    public ClientListener(InetAddress aHostName, int aHostPort,LinkedList aQueue,Server aServer)      // reference to Server queue)
    hostName = aHostName;
    hostPort = aHostPort;
    queue = aQueue;
    serverRef = aServer;      
    // connect to the server
    try{
    hostSocket = new Socket(hostName, hostPort);
    catch(IOException e){
    //System.out.println("ERROR: Connection Host Failed");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Connection to nPort Failed", JOptionPane.ERROR_MESSAGE);     
    System.exit(0);
    } // end constructor ClientListener
    ** multi client connection server
    ClientWorker(Socket aSocket,LinkedList aQueue, ClientListener aClientListener, boolean diagnostics){
    queue = aQueue;
    addToQueue(this);
    client = aSocket;
    clientRef = aClientListener;
    aDiagnostic = diagnostics;
    } // end constructor ClientWorker
    * run method is the main loop of the server program
    * in change of handle new client connection as well
    * as handle all messages and errors.
    public void run(){
    boolean alive = true;
    String aSubString = "";
    in = null;
    out = null;
    loginName = "";
    loggedIn = false;
    while (alive && client.isConnected()&& clientRef.hostSocket.isConnected()){
    try{
    in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    out = new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
    if(aDiagnostic){
    out.println("WELCOME to diagnostics");
    broadCastDia("Connect : diagnostics "+client.getInetAddress().toString());
    out.flush();
    else {       
    out.println("WELCOME to Troy's Server");
    broadCastDia("Connect : client "+client.getInetAddress().toString());
         out.flush();
    String line;
    while(((line = in.readLine())!= null)){
    StringTokenizer aStringToken = new StringTokenizer(line, " ");
    if(!aDiagnostic){
    broadCastDia(line);
    clientRef.sendMessage(line); // send mesage out to netExpress
    out.println(line);
    out.flush();
    else{
    if(line.equals("GETIPS"))
    getIPs();
    else{
    clientRef.sendMessage(line); // send mesage out to netExpress
    out.println(line);
    out.flush();
    } // end while
    catch(Exception e){
    // System.out.println("ERROR:Client Connection reset");
                             JOptionPane.showMessageDialog(null, (e.toString()),"ERROR:Client Connection reset", JOptionPane.ERROR_MESSAGE);     
    try{
    if(aDiagnostic){
    broadCastDia("Disconnect : diagnostics "+client.getInetAddress().toString());
    out.flush();
    else {       
    broadCastDia("Disconnect : client "+client.getInetAddress().toString());
         out.flush();
    // close the buffers and connection;
    in.close();
    out.close();
    client.close();
    // System.out.println("out");
    // remove from list
    removeThreadQueue(this);
    alive = false;
    catch(Exception e){
    // System.out.println("ERROR: Client Connection reset failure");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Client Connection reset failure", JOptionPane.ERROR_MESSAGE);     
    }// end while
    } // end method run
    * method run - Generates io stream for communicating with the server and
    * starts the client gui. Run also parses the input commands from the server.
    public void run(){
    boolean alive = true;
    try{
    // begin to life the gui
    // aGuiClient = new ClientGui(hostName.getHostName(), hostPort, loginName, this);
    // aGuiClient.show();
    in = new BufferedReader(new InputStreamReader(hostSocket.getInputStream()));
    out = new PrintWriter(new OutputStreamWriter(hostSocket.getOutputStream()));
    while (alive && hostSocket.isConnected()){
    String line;
    while(((line = in.readLine())!= null)){
    System.out.println(line);
    broadCast(line);
    } // end while
    } // end while
    catch(Exception e){
    //     System.out.println("ERRORa Connection to host reset");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Connection to nPort reset", JOptionPane.ERROR_MESSAGE);
    try{
    hostSocket.close();
         }catch(Exception a){
         JOptionPane.showMessageDialog(null, (a.toString()),"ERROR: Exception", JOptionPane.ERROR_MESSAGE);
    alive = false;
    System.exit(1);
    } // end method run

Maybe you are looking for