Problem in getHostAddress() method in java

Manish Goyal

Manish Goyal

@manish-r2Hoep • Oct 22, 2024

I am trying to create a simple program that will return the address of host ie my computer

but it gives me exception null

I don't understand why?

here is my code

import java.net.*;
class Myserver
{
public static void main(String args[])
{
InetAddress is=null;
try
{
String st=is.getHostName();
System.out.println("Host address is "+st);
}
catch(Exception e)
{
System.out.println(e.getMessage());}
}
}

Replies

Welcome, guest

Join CrazyEngineers to reply, ask questions, and participate in conversations.

CrazyEngineers powered by Jatra Community Platform

  • bharathpb

    bharathpb

    @bharathpb-FtEhYi Jun 7, 2010

    Not sure wats going wrong in ur code..

    InetAddress is=null; is setting the address to null...finally u get null.


    I tried a new code..try this one...

    import java.net.*;
    class Myserver1
    {
    public static void main(String args[])
    {

    try
    { InetAddress addr = InetAddress.getLocalHost();

    System.out.println("Host address is " +addr);
    } catch (UnknownHostException e) {
    System.out.println(e.getMessage());}
    }
    }

  • Manish Goyal

    Manish Goyal

    @manish-r2Hoep Jun 7, 2010

    Thanks for your response

    but still i am not getting same exception

    one thing is it possible to retrieve ip address that is allocated to me by my isp through this method ?

  • bharathpb

    bharathpb

    @bharathpb-FtEhYi Jun 7, 2010

    hi Goyal,

    from my above code..you will get both the system hostname and ip address allotted to u.

    Also post the exact exception so that i can debug...

  • Manish Goyal

    Manish Goyal

    @manish-r2Hoep Jun 8, 2010

    nothing it just print null on console

    I don't understand what is the problem ?

    should i need to change my network settings?

    Do you use broadband?if yes then you program gives which ip address ?I mean that which was allocated by isp or any other?

  • sookie

    sookie

    @sookie-T06sFW Jun 8, 2010

    Hi goyal420,

    I am using broadband connection and if I run bharathpb's program in my machine, it is working fine. It shows my machine's [hostname]/[ipaddress provided by ISP] in the output. I think you should once check network settings in your machine.

  • Manish Goyal

    Manish Goyal

    @manish-r2Hoep Jun 8, 2010

    Thanks Guys for your reply

    now i am getting my ip address

    but why my program is not working ?I don't think that there is any syntax error but still there is a exception😕😕

  • bharathpb

    bharathpb

    @bharathpb-FtEhYi Jun 8, 2010

    goyal,,

    As already mentioned by me..provide the exact exception which you are getting...is it null pointer exception or is your output simply null????

  • Manish Goyal

    Manish Goyal

    @manish-r2Hoep Jun 8, 2010

    yes it simply output null in case of my first program