Q:

Java program to extract octets from IP address

belongs to collection: Java Basic Programs

0

Java program to extract octets from IP address

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

Program/Source Code:

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to determine the class of a given IP ... >>
<< Java program to print string in hexadecimal format...