×

Java Programs

Java Practice

Java program to extract octets from IP address

Given/input an IP address, we have to extract octets from it.
Submitted by Nidhi, on March 05, 2022

Problem Solution:

In this program, we will read an IP address from the user and extract the octets from the IP address.

Java program to extract octets from IP address

The source code to extract octets from the IP address is given below. The given program is compiled and executed successfully.

// Java program to extract octets 
// from IP address

import java.util.Scanner;

public class Main {
  static void extractIpAddress(String sourceString) {
    short len = 0;

    int oct[] = new int[4];
    String buf = "";

    short cnt = 0;
    short i = 0;

    len = (short) sourceString.length();
    for (i = 0; i < len; i++) {
      if (sourceString.charAt(i) != '.') {
        buf += sourceString.charAt(i);
      }
      if (sourceString.charAt(i) == '.' || i == len - 1) {
        oct[cnt++] = Integer.parseInt(buf);
        buf = "";
      }
    }

    System.out.println("Octete1 : " + oct[0]);
    System.out.println("Octete2 : " + oct[1]);
    System.out.println("Octete3 : " + oct[2]);
    System.out.println("Octete4 : " + oct[3]);
  }

  public static void main(String[] args) {
    Scanner SC = new Scanner(System.in);

    String ip;
    int i = 0;

    System.out.print("Enter valid IP address: ");
    ip = SC.next();

    extractIpAddress(ip);
  }
}

Output:

Enter valid IP address: 192.168.10.235
Octete1 : 192
Octete2 : 168
Octete3 : 10
Octete4 : 235

Explanation:

In the above program, we imported the "java.util.Scanner" package to read input from the user. And, created a public class Main. It contain two static methods extractIpAddress() and main().

The extractIpAddress() method is used to extract octets from the input IP address and print them on the console screen.

The main() method is an entry point for the program. And, we read an IP address in string format. Then we extracted octets using the extractIpAddress() method and printed the result.

Java Basic Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.