Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.util.StringTokenizer;

public class Main {
    /**
     *
     * @param source
     *            ifconfig output
     * @param device
     *            device of interest
     * @return
     */
    public static String[] findIPandNetmask(String source, String device) {
        int deviceIndex = source.indexOf(device);
        source = source.substring(deviceIndex);
        int nextLine = source.indexOf("\n");
        source = source.substring(nextLine);
        int startOfIP = source.indexOf(":");
        int endOfIP = source.indexOf(" ", startOfIP);
        String ip = source.substring(startOfIP + 1, endOfIP);

        int startOfMask = source.indexOf("Mask:");
        int endOfMask = source.indexOf("\n", startOfMask);
        String mask = source.substring(startOfMask + 5, endOfMask);

        StringTokenizer ipTokens = new StringTokenizer(ip, ".");
        StringTokenizer maskTokens = new StringTokenizer(mask, ".");

        int firstOctet = Integer.parseInt(ipTokens.nextToken()) & Integer.parseInt(maskTokens.nextToken());
        int secondOctet = Integer.parseInt(ipTokens.nextToken()) & Integer.parseInt(maskTokens.nextToken());
        int thirdOctet = Integer.parseInt(ipTokens.nextToken()) & Integer.parseInt(maskTokens.nextToken());
        int fourthOctet = Integer.parseInt(ipTokens.nextToken()) & Integer.parseInt(maskTokens.nextToken());

        String networkAddress = firstOctet + "." + secondOctet + "." + thirdOctet + "." + fourthOctet;

        return new String[] { networkAddress, mask };

    }
}