What is my ip address java

How to Lookup IP Addresses in Java

A host is a computer that can connect to the internet. Every host has a unique identification number that distinguishes it from other online devices.

Prerequisites

To follow along, you should have:

  • A basic understanding of Java and networking.
  • Some knowledge in using the Java.Net package.

Table of contents

Definition of an IP address

An IP address is a string of numbers separated by dots that stands for Internet Protocol.

IP addresses are four-digit numbers in a 32-bit format known as IPv4 addresses. For example, 192.168.1.3.

There are also IPv6 addresses that use six-digit numbers in 128-bit format.

Each integer in the set can be anywhere between 0 and 255. This means that the range of an IP address is from 0.0.0.0 to 255.255.255.255.

IP addresses are not just random numbers that one can assign to a host. The Internet Assigned Numbers Authority creates and allocates IP addresses to devices.

Definition of DNS and its workflow

DNS (Domain Name System) is a TCP/IP protocol that defines how application processes in different systems exchange messages.

Читайте также:  Функция длины массива питон

DNS functions similarly to an internet-based database. It has a list of hostnames (domains) and IP addresses.

DNS helps users to connect to all types of websites by remembering their domain hostnames. Therefore, one does not need to carry around a catalog full of IP addresses.

DNS associates hostnames that humans can remember (such as www.google.com) with IP addresses that computers can remember (e.g., 172.217.170.164).

How DNS works

DNS is not self-contained; it requires extra programs, one of which is a resolver.

A resolver is client-side software that makes it easier to connect to a DNS server.

It is a program on the client computer that assists in connecting to a DNS server.

A web browser and mail client are the most widely used resolvers. Therefore, to access the DNS server, you must have a web browser or an e-mail client installed on your computer.

Chrome, Opera, Firefox, and Safari are some of the most popular browsers.

Procedure of a DNS workflow

  1. Two DNS servers
  2. A web browser
  3. A computer
  • The client computer asks the local DNS server for a website’s IP address.
  • The local DNS server will check its records and reserve the information.
  • If the DNS server finds the reserved file, it will immediately give the browser app an IP address. If the server can’t find it, it sends a request to the online DNS server.
  • Once the IP address has been acquired, the local server puts it in a stash/cache. When the client computer requests the IP address again, the DNS server does not need to contact other online servers.
  • The data or cache is transferred to a different DNS server if it can’t get sited on the current server.

Representing IP Addresses in Java using the InetAddress Class

Java Net packages act as the interconnection point between two or more computing devices. This allows them to share resources and control applications centrally.

Java.net.InetAddress class is a high-level representation of an IP address in Java for IPv4 and IPv6. It generally includes both a hostname and an IP address.

Java InetAddress Class Methods

InetAddress methods can connect to a local DNS server to retrieve or send information.

The InetAddress class caches the results of DNS lookups for future reference.

If the IP address does not change while your program is running, there will be no issues.

Negative results such as host not found are slightly problematic. This error will occur when the first connection attempt times out while the information was in transit from the remote DNS server.

InetAddress.getByName() is the frequently used method. This static function takes the hostname that you are looking for as its arguments. It then looks up the host’s IP address using DNS.

 InetAddress address = InetAddress.getByName("www.google.com"); 

Exception handling

The InetAddress.getByName() method throws UnknownHostException if the host cannot be found.

It can either be declared using the throws exception or wrapped in a try-catch block, as shown below:

try  InetAddress address = InetAddress.getByName("www.google.com");  System.out.println(address); > catch(UnknownHostException ex)  System.out.println("www.google.com not found"); > 

Commonly used methods

Below is a sample code using getByName() method:

package com.company;  import java.net.InetAddress; import java.net.UnknownHostException;  public class GetIpAddress   public static void main(String[]args) throws UnknownHostException  InetAddress address = InetAddress.getByName("www.microsoft.com");   System.out.println("my local machine: " + address);  > > 
my local machine: www.microsoft.com/2.21.100.214 

For machines that do not have hostnames, you can always pass a string that contains a hexadecimal form of the IP address to InetAddress.getByName() .

InetAddress address = InetAddress.getByName("172.217.170.164"); 

Hostnames are more stable than IP addresses. Most services have maintained the same hostnames but have changed their IP addresses severally.

Some computers will have more than one IP address. This means that the InetAddress.getAllByName() will return an array of addresses that correspond to that hostname.

This is shown in the code snippet below:

InetAddress[] address = InetAddress.getAllByName("www.google.com"); 

The following code shows how to return an array of addresses using the getAllByName() method:

package com. company;  import java.net.InetAddress; import java.net.UnknownHostException;  public class GetIpAddress   public static void main(String[] args) throws UnknownHostException    InetAddress[] inetAddresses=InetAddress.getAllByName("www.google.com");   for (InetAddress ipAddress : inetAddresses)    System.out.println("Google different ip " + ipAddress);  >  > > 
Google different ip:www.google.com/172.217.170.164 

Hosts with multiple IP addresses are usually high-volume web servers.

The getLocalHost method returns the InetAddress of the host machine.

The getLocalHost function throws UnknownHostException when it cannot find the host’s address.

InetAddress address = InetAddress.getLocalHost(); 

The following code shows how to use getLocalHost() method:

package com. company;  import java.net.InetAddress; import java.net.UnkownHostException;  public class GetIpAddress   public static void main(String[] args)throws UnknownHostException   InetAddress inetaddress = InetAddress.getLocalHost();  System.out.println("My local machine Ip is: "+ inetaddress);   > > 
My local machine Ip is: DESKTOP-MC2R176/192.168.43.35 

When you are not connected to the internet, and the computer lacks a fixed IP address or domain name, the default domain name and IP address are localhost , and 127.0.0.1 respectively.

Conclusion

In this tutorial, we learned about IP addresses and their versions. We also discussed DNS and its workflow.

We learned that IP addresses and hostnames are accessible via the InetAddress class.

Peer Review Contributions by: Dawe-Daniel

Источник

How to get my machine or local host IP address in Java?

Below example shows how to get IP address of a host or machine. You can get it by using InetAddress class. getLocalHost() method returns the information about the host, and returns InetAddress object. If you call getHostAddress() method, you can get IP address of the host.

package com.myjava.ip; import java.net.InetAddress; import java.net.UnknownHostException; public class MyIpAddress < public static void main(String a[])< try < InetAddress ipAddr = InetAddress.getLocalHost(); System.out.println(ipAddr.getHostAddress()); >catch (UnknownHostException ex) < ex.printStackTrace(); >> >

List Of All Networking Examples:

  1. How to create URL object?
  2. How to create File URL object?
  3. How to create URL object with all properties?
  4. How to get URL properties?
  5. How to get URL object with relative path?
  6. How to compare two URL objects path?
  7. How to read URL content?
  8. How to encode URL content?
  9. How to decode URL content?
  10. How to get my machine IP address?
  11. How to get IP address of a host?
  12. How to get host name by IP address?
  13. How to get machine host name?
  14. How to get all IP addresses of a host?

In System.out, out is an instance of PrintStream. It is a static member variable in System class. This is called standard output stream, connected to console.

There is a great difference between worry and concern. A worried person sees a problem, and a concerned person solves a problem.

About Author

I’m Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected] .

Most Visited Pages

Источник

How to get Server IP Address and Hostname in Java

Find IP Address in Java with Hostname

In Java, you can use InetAddress.getLocalHost() to get the Ip Address of the current Server running the Java app and InetAddress.getHostName() to get Hostname of the current Server name.

package com.crunchify.tutorials; import java.net.InetAddress; import java.net.UnknownHostException; /** * @author Crunchify.com */ public class CrunchifyGetIPHostname < public static void main(String[] args) < InetAddress ip; String hostname; try < ip = InetAddress.getLocalHost(); hostname = ip.getHostName(); System.out.println("Your current IP address : " + ip); System.out.println("Your current Hostname : " + hostname); >catch (UnknownHostException e) < e.printStackTrace(); >> >
Your current IP address : appshah-mac/192.168.0.1 Your current Hostname : appshah-mac

Another must read:

On the face of it, InetAddress.getLocalHost() should give you the IP address of this host. The problem is that a host could have lots of network interfaces, and an interface could be bound to more than one IP address. And to top that, not all IP addresses will be reachable from off the machine. Some could be virtual devices, and others could be private network IP addresses.

What this means is that the IP address returned by InetAddress.getLocalHost() might not be the right one to use.

How can you deal with this?

  • One approach is to use Java’s NetworkInterface.getNetworkInterfaces() API to get all of the known network interfaces on the host, and then iterate over each NI’s addresses.
  • Another approach is to (somehow) get the externally advertised FQDN for the host, and use InetAddress.getByName() to look up the primary IP address. (But how do you get it, and how do you deal with a DNS-based load balancer?)
  • A variation of the previous is to get the preferred FQDN from a config file or a command line parameter.
  • Another variation is to to get the IP address from a config file or a command line parameter.

In summary, InetAddress.getLocalHost() will typically work, but you may need to provide an alternative method for the cases where your code is run in an environment with “complicated” networking.

If you liked this article, then please share it on social media. Have a question or suggestion? Please leave a comment to start the discussion.

Suggested Articles.

Источник

Оцените статью