27

I am writing an application where I need the IP address. I have a domain name and I would like to know how to get the IP address from it. For example, "www.girionjava.com". How could I get the IP address of this website by programming in Java? Thanks.

CerebralCortexan
  • 299
  • 2
  • 17
giri
  • 26,773
  • 63
  • 143
  • 176

5 Answers5

34
InetAddress giriAddress = java.net.InetAddress.getByName("www.girionjava.com");

Then, if you want the IP as a String

String address = giriAddress.getHostAddress();
Powerlord
  • 87,612
  • 17
  • 125
  • 175
11

This should be simple.

InetAddress[] machines = InetAddress.getAllByName("yahoo.com");
for(InetAddress address : machines){
  System.out.println(address.getHostAddress());
}
redoc
  • 255
  • 3
  • 16
6
InetAddress.getByName("www.girionjava.com")
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
flybywire
  • 261,858
  • 191
  • 397
  • 503
0

(Extra mask in printing sine java considers all integers to be signed, but an IP address is unsigned)

InetAddress[] machines = InetAddress.getAllByName("yahoo.com");
for(InetAddress address : machines){
  byte[] ip = address.getAddress();
  for(byte b : ip){
    System.out.print(Integer.toString(((int)b)&0xFF)+".");
  }
  System.out.println();
}
M. Jessup
  • 8,153
  • 1
  • 29
  • 29
  • 2
    This assumes that you'll be getting only IPv4 adresses. IPv6 adresses are formatted differently, so you shouldn't manually format it anyway. – Joachim Sauer Mar 17 '10 at 13:22
-1

The InetAddress class in java.net has some static methods to do this.

        InetAddress a = InetAddress.getByName ("www.girionjava.com");
        System.out.println(a.getHostAddress());     

This is very basic stuff, for more complete control over DNS queries, you will have to use additional libraries.

rmalchow
  • 2,689
  • 18
  • 31
  • 1
    Welcome to Stack Overflow! Please read [answer] and [edit] your answer to contain an explanation as to why this code would actually solve the problem at hand. Always remember that you're not only solving the problem, but are also educating the OP and any future readers of this post. – Adriaan Dec 08 '22 at 09:27