BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java program to get IP address

Last Updated: September 10, 2022 by Chaitanya Singh | Filed Under: Java Examples

In this example we are gonna see how to get IP address of a System. The steps are as follows:

1) Get the local host address by calling getLocalHost() method of InetAddress class.
2) Get the IP address by calling getHostAddress() method.

import java.net.InetAddress;

class GetMyIPAddress
{
   public static void main(String args[]) throws Exception
   {
      /* public static InetAddress getLocalHost()
       * throws UnknownHostException: Returns the address 
       * of the local host. This is achieved by retrieving 
       * the name of the host from the system, then resolving 
       * that name into an InetAddress. Note: The resolved 
       * address may be cached for a short period of time.
       */
      InetAddress myIP=InetAddress.getLocalHost();
 
      /* public String getHostAddress(): Returns the IP 
       * address string in textual presentation.
       */
      System.out.println("My IP Address is:");
      System.out.println(myIP.getHostAddress());
  }
}

Output:

My IP Address is:
115.242.7.243

Reference:
InetAddress javadoc

Top Related Articles:

  1. Java Program to print Even numbers from 1 to n or 1 to 100
  2. Fascinating Number Program in Java
  3. Check Duck Number in Java and Print these numbers in a range
  4. Java program for bubble sort in Ascending & descending order
  5. Program to Implement Merge Sort in Java

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Examples

  • Check Odd-even
  • Linear Search
  • Binary Search
  • Floyd's Triangle
  • Reverse number
  • Random Number
  • first n prime numbers
  • Disp prime Numbers
  • Check Prime number
  • Palindrome String
  • Find factorial
  • Sum of elements of Array
  • Area of rectangle
  • Area of Square
  • Area of Triangle
  • Circle

Tutorials

  • Java Tutorial
  • OOPs Concepts
  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap