Last active
September 24, 2017 05:48
-
-
Save AjayKrP/7835ea2f054395fb3193ae7d41a568e5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.String; | |
public class subnet_mask{ | |
/*Function to separate the IP entered into 4 different octets*/ | |
public int[] get_ip_octets(String string) { | |
int length = string.length(); | |
/*This array has 4 rows, one for each octet of the IP address, | |
and 3 columns, one for each digit of the octet.*/ | |
int oct[][] = new int[4][3]; | |
for(int j = 0; j < 4; ++j) { | |
for (int q = 0; q < 3; ++q) { | |
oct[j][q] = -1; | |
} | |
} | |
String ipnum = string; | |
int k = 0; | |
int oct_num = 0; | |
int oct_digit = 0; | |
/*This loop separates the 4 octets of an IP address into the multidimensional array and | |
converts the values from Chars to Int*/ | |
while (k < length){ | |
if(ipnum.charAt(k) != '.'){ | |
oct[oct_num][oct_digit] = ipnum.charAt(k)- '0'; | |
oct_digit++; | |
k++; | |
} | |
else { | |
k++; | |
oct_num++; | |
oct_digit = 0; | |
} | |
} | |
int octets[] = {0, 0, 0, 0}; | |
for(int j = 0; j < 4; j++ ){/*This loop adds the digits*/ | |
if ( oct[j][2] != -1){ | |
octets[j] = oct[j][2]; | |
octets[j] += (oct[j][1] * 10); | |
octets[j] += (oct[j][0] * 100); | |
} | |
else if ( oct[j][2] == -1 && oct[j][1] != -1 ){ | |
octets[j] += oct[j][1] ; | |
octets[j] += oct[j][0] * 10; | |
} | |
else if ( oct[j][2] == -1 && oct[j][1] == -1 ){ | |
octets[j] = oct[j][0]; | |
} | |
} | |
return octets; | |
} | |
public int [] default_mask(int ip[]){ | |
int def_mask[] = {0, 0, 0, 0}; | |
if ( ip[0] > 224 ) | |
System.exit(0); | |
if ( ip[0] > 191 ) | |
def_mask[2] = 255; | |
if ( ip[0] > 127 ) | |
def_mask[1] = 255; | |
if ( ip[0] > 0 ) | |
def_mask[0] = 255; | |
return def_mask; | |
} | |
public static void main(String[] args) { | |
int oct[], def_subnet[]; | |
subnet_mask sm = new subnet_mask(); | |
oct = sm.get_ip_octets(args[0]); | |
def_subnet = sm.default_mask(oct); | |
System.out.print("Network address: "); | |
for (int i = 0; i < 4; ++i){ | |
if( i != 3){ | |
System.out.printf("%d.", oct[i]); | |
} | |
else { | |
System.out.printf("%d\n", oct[i]); | |
} | |
} | |
System.out.println(); | |
System.out.print("Default Subnet Mask: "); | |
for (int i = 0; i < 4; ++i){ | |
if( i != 3){ | |
System.out.printf("%d.", def_subnet[i]); | |
} | |
else { | |
System.out.printf("%d\n", def_subnet[i]); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment