1 #include <stdio.
h>
2 // Includes the standard input/output library for functions like printf and scanf.
3 // Why: Needed for printing output and reading user input.
4 // How: Provides access to I/O functions used throughout the program.
5
6 #include <stdlib.h>
7 // Includes the standard library for functions like atoi.
8 // Why: Used for converting string tokens to integers in IP parsing.
9 // How: Provides utility functions for string-to-number conversion.
10
11 #include <string.h>
12 // Includes the string library for functions like strtok and strcspn.
13 // Why: Needed for string manipulation, such as splitting IP addresses.
14 // How: Enables tokenizing and string length operations.
15
16 void ipv4_to_binary(char *ip) {
17 // Defines a function to convert an IPv4 address from decimal to binary.
18 // Why: Encapsulates the logic for decimal-to-binary conversion.
19 // How: Takes a string IP (e.g., "192.168.1.1") and prints its binary form.
20
21 char iv_copy[16];
22 // Declares a character array to store a copy of the input IP address.
23 // Why: Protects the original input string from modification by strtok.
24 // How: Allocates 16 bytes, sufficient for an IPv4 address (e.g., "255.255.255.255").
25
26 strcpy(iv_copy, ip);
27 // Copies the input IP string to iv_copy.
28 // Why: Ensures the original IP string is not altered during tokenization.
29 // How: Uses strcpy to duplicate the string into iv_copy.
30
31 int binary[32];
32 // Declares an array to store the 32-bit binary representation.
33 // Why: Stores the binary bits for all four octets (8 bits each).
34 // How: Allocates space for 32 integers (0s or 1s).
35
36 int i = 0;
37 // Initializes an index for the binary array.
38 // Why: Tracks the position in the binary array when storing bits.
39 // How: Starts at 0 and increments as bits are added.
40
41 char *token = strtok(iv_copy, ".");
42 // Splits the IP string at the first '.' and returns the first octet.
43 // Why: Breaks the IP address into octets for processing.
44 // How: strtok modifies iv_copy and returns a pointer to the first token (e.g., "192").
45
46 while (token != NULL) {
47 // Loops through each octet token until no more are found.
48 // Why: Processes all four octets of the IP address.
49 // How: Continues until strtok returns NULL, indicating no more tokens.
50
51 int octet = atoi(token);
52 // Converts the current octet string to an integer.
53 // Why: Converts the string (e.g., "192") to a number for binary conversion.
54 // How: atoi parses the string and returns its integer value.
55
56 for (int j = 7; j >= 0; j--) {
57 // Loops through each bit position (7 to 0) for the current octet.
58 // Why: Extracts each bit of the octet to build the binary representation.
59 // How: Iterates from the most significant bit (j=7) to the least (j=0).
60
61 binary[i++] = (octet >> j) & 1;
62 // Extracts the j-th bit of the octet and stores it in the binary array.
63 // Why: Converts the octet to binary by checking each bit.
64 // How: Right-shifts octet by j positions, masks with 1 to get the bit, and stores it.
65
66 }
67 token = strtok(NULL, ".");
68 // Gets the next octet token by continuing the tokenization.
69 // Why: Moves to the next part of the IP address (e.g., "168").
70 // How: strtok continues from the last position, using '.' as the delimiter.
71
72 }
73 for (int k = 0; k < 32; k++) {
74 // Loops through the binary array to print the 32 bits.
75 // Why: Displays the binary representation of the IP address.
76 // How: Iterates through all 32 bits in the binary array.
77
78 printf("%d", binary[k]);
79 // Prints the current bit (0 or 1).
80 // Why: Outputs each bit of the binary representation.
81 // How: Uses printf to print the integer value (0 or 1).
82
83 if ((k + 1) % 8 == 0) {
84 // Checks if the current bit is the last in an octet (every 8 bits).
85 // Why: Adds a space after each octet for readability.
86 // How: After bits 8, 16, 24, and 32, prints a space.
87
88 printf(" ");
89 // Prints a space to separate octets.
90 // Why: Improves readability of the binary output (e.g., 11000000 10101000).
91 // How: Outputs a single space character.
92
93 }
94 }
95 printf("\n");
96 // Prints a newline after the binary output.
97 // Why: Ensures the output is formatted cleanly.
98 // How: Adds a newline character to move to the next line.
99
100 }
101
102 void binary_to_ipv4(char *binary_ip) {
103 // Defines a function to convert a binary IP string to decimal IPv4 format.
104 // Why: Encapsulates the logic for binary-to-decimal conversion.
105 // How: Takes a binary string (e.g., "11000000 10101000 00000001 00000001") and prints the
decimal IP.
106
107 int octet_values[4] = {0};
108 // Initializes an array to store the decimal values of the four octets.
109 // Why: Stores the computed decimal value for each octet.
110 // How: Allocates an array of four integers, initialized to 0.
111
112 int index = 0;
113 // Initializes an index to track the position in the binary_ip string.
114 // Why: Keeps track of which character in the binary string is being processed.
115 // How: Starts at 0 and increments as bits are read.
116
117 for (int i = 0; i < 4; i++) {
118 // Loops through each of the four octets.
119 // Why: Processes each 8-bit segment of the binary string.
120 // How: Iterates i from 0 to 3 for the four octets.
121
122 for (int j = 0; j < 8; j++) {
123 // Loops through each bit in the current octet.
124 // Why: Reads each bit to compute the decimal value of the octet.
125 // How: Iterates j from 0 to 7 for the 8 bits in an octet.
126
127 if (binary_ip[index] == '1') {
128 // Checks if the current character is '1'.
129 // Why: Determines if the current bit contributes to the octet's value.
130 // How: Compares the character at binary_ip[index] to '1'.
131
132 octet_values[i] |= (1 << (7 - j));
133 // Sets the corresponding bit in the octet value.
134 // Why: Builds the decimal value by setting the j-th bit.
135 // How: Left-shifts 1 by (7-j) positions and uses bitwise OR to set the bit.
136
137 }
138 index++;
139 // Increments the index to move to the next character in binary_ip.
140 // Why: Advances to the next bit in the binary string.
141 // How: Increments index by 1.
142
143 }
144 index++;
145 // Increments the index to skip the space between octets.
146 // Why: Accounts for spaces in the binary string (e.g., after 8 bits).
147 // How: Increments index to skip the space character.
148
149 }
150 printf("IPv4 representation: %d.%d.%d.%d\n", octet_values[0], octet_values[1],
octet_values[2], octet_values[3]);
151 // Prints the decimal IPv4 address.
152 // Why: Outputs the converted IP address in dotted-decimal format.
153 // How: Uses printf to format the four octet values with dots.
154
155 }
156
157 char get_ip_class(int first_octet) {
158 // Defines a function to determine the IP address class based on the first octet.
159 // Why: Identifies the class (A, B, C, or invalid) for network categorization.
160 // How: Takes the first octet and returns a character ('A', 'B', 'C', or 'X').
161
162 if (first_octet >= 1 && first_octet <= 126)
163 // Checks if the first octet is in the range for Class A (1–126).
164 // Why: Class A IPs have first octet values from 1 to 126.
165 // How: Returns 'A' if the condition is true.
166
167 return 'A';
168 // Returns 'A' for Class A IP addresses.
169 // Why: Indicates the IP belongs to Class A.
170 // How: Returns the character 'A'.
171
172 else if (first_octet >= 128 && first_octet <= 191)
173 // Checks if the first octet is in the range for Class B (128–191).
174 // Why: Class B IPs have first octet values from 128 to 191.
175 // How: Returns 'B' if the condition is true.
176
177 return 'B';
178 // Returns 'B' for Class B IP addresses.
179 // Why: Indicates the IP belongs to Class B.
180 // How: Returns the character 'B'.
181
182 else if (first_octet >= 192 && first_octet <= 223)
183 // Checks if the first octet is in the range for Class C (192–223).
184 // Why: Class C IPs have first octet values from 192 to 223.
185 // How: Returns 'C' if the condition is true.
186
187 return 'C';
188 // Returns 'C' for Class C IP addresses.
189 // Why: Indicates the IP belongs to Class C.
190 // How: Returns the character 'C'.
191
192 else
193 // Handles cases where the first octet is outside valid class ranges.
194 // Why: Catches invalid or reserved IP addresses (e.g., 0, 127, 224+).
195 // How: Returns 'X' for invalid classes.
196
197 return 'X';
198 // Returns 'X' for invalid IP classes.
199 // Why: Indicates the IP does not belong to Class A, B, or C.
200 // How: Returns the character 'X'.
201
202 }
203
204 int main() {
205 // Defines the main function, the entry point of the program.
206 // Why: Contains the primary logic for user interaction and function calls.
207 // How: Executes the program’s core functionality.
208
209 char ipv4_address[16];
210 // Declares a character array to store the input IPv4 address.
211 // Why: Holds the user-entered IP address (e.g., "192.168.1.1").
212 // How: Allocates 16 bytes, sufficient for an IPv4 string.
213
214 int choice;
215 // Declares a variable to store the user’s menu choice.
216 // Why: Determines whether to perform decimal-to-binary or binary-to-decimal conversion.
217 // How: Stores an integer (1 or 2) based on user input.
218
219 printf("Enter an IPv4 address : ");
220 // Prompts the user to enter an IPv4 address.
221 // Why: Instructs the user to input an IP address for processing.
222 // How: Prints the prompt to the console.
223
224 fgets(ipv4_address, sizeof(ipv4_address), stdin);
225 // Reads the user’s input IP address from standard input.
226 // Why: Captures the entire line, including dots, as a string.
227 // How: Stores the input in ipv4_address, up to 16 characters.
228
229 ipv4_address[strcspn(ipv4_address, "\n")] = '\0';
230 // Removes the newline character from the input string.
231 // Why: Cleans the input by replacing the newline with a null terminator.
232 // How: Uses strcspn to find the newline and replaces it with '\0'.
233
234 int first_octet;
235 // Declares a variable to store the first octet of the IP address.
236 // Why: Needed to determine the IP class.
237 // How: Will hold the integer value of the first octet.
238
239 sscanf(ipv4_address, "%d", &first_octet);
240 // Extracts the first octet from the IP address string.
241 // Why: Parses the first number before the first dot to check the IP class.
242 // How: Reads the first integer from ipv4_address into first_octet.
243
244 char ip_class = get_ip_class(first_octet);
245 // Determines the IP class by calling get_ip_class.
246 // Why: Checks if the IP belongs to Class A, B, C, or is invalid.
247 // How: Passes first_octet to get_ip_class and stores the returned class.
248
249 if (ip_class == 'X') {
250 // Checks if the IP class is invalid.
251 // Why: Prevents processing of invalid IP addresses.
252 // How: Compares ip_class to 'X' to decide whether to exit.
253
254 printf("Invalid IP class! Please enter Class A, B, or C IP.\n");
255 // Prints an error message for invalid IP classes.
256 // Why: Informs the user that the IP is not valid for processing.
257 // How: Outputs the error message to the console.
258
259 return 1;
260 // Exits the program with an error code.
261 // Why: Terminates execution if the IP class is invalid.
262 // How: Returns 1 to indicate an error.
263
264 }
265 printf("IP belongs to Class %c\n", ip_class);
266 // Prints the IP class (A, B, or C).
267 // Why: Informs the user of the IP’s class.
268 // How: Uses printf to display the class character.
269
270 printf("Choose an option:\n");
271 // Prompts the user to select a conversion option.
272 // Why: Guides the user to choose between conversion types.
273 // How: Prints the menu prompt.
274
275 printf("1. Convert to Binary\n");
276 // Displays the first menu option.
277 // Why: Informs the user about the decimal-to-binary conversion option.
278 // How: Prints option 1.
279
280 printf("2. Convert Binary to IPv4\n");
281 // Displays the second menu option.
282 // Why: Informs the user about the binary-to-decimal conversion option.
283 // How: Prints option 2.
284
285 printf("Enter your choice: ");
286 // Prompts the user to enter their choice.
287 // Why: Requests the user’s selection (1 or 2).
288 // How: Prints the prompt for input.
289
290 scanf("%d", &choice);
291 // Reads the user’s choice from standard input.
292 // Why: Captures the user’s selection for conversion type.
293 // How: Stores the input integer in choice.
294
295 getchar();
296 // Consumes the newline character left in the input buffer.
297 // Why: Prevents issues when reading subsequent input (e.g., binary IP).
298 // How: Reads and discards the leftover newline.
299
300 if (choice == 1) {
301 // Checks if the user chose decimal-to-binary conversion.
302 // Why: Determines whether to call the ipv4_to_binary function.
303 // How: Compares choice to 1.
304
305 ipv4_to_binary(ipv4_address);
306 // Calls the function to convert the IP to binary.
307 // Why: Performs the decimal-to-binary conversion.
308 // How: Passes the input IP address to ipv4_to_binary.
309
310 } else if (choice == 2) {
311 // Checks if the user chose binary-to-decimal conversion.
312 // Why: Determines whether to call the binary_to_ipv4 function.
313 // How: Compares choice to 2.
314
315 char binary_ip[36];
316 // Declares a character array to store the binary IP input.
317 // Why: Holds the user-entered binary IP (e.g., "11000000 10101000 00000001 00000001").
318 // How: Allocates 36 bytes to accommodate 32 bits plus spaces and null terminator.
319
320 printf("Enter binary IP (format: xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx): ");
321 // Prompts the user to enter a binary IP address.
322 // Why: Instructs the user to input the binary IP in the correct format.
323 // How: Prints the prompt with the expected format.
324
325 fgets(binary_ip, sizeof(binary_ip), stdin);
326 // Reads the binary IP string from standard input.
327 // Why: Captures the user’s binary IP input.
328 // How: Stores the input in binary_ip, up to 36 characters.
329
330 binary_ip[strcspn(binary_ip, "\n")] = '\0';
331 // Removes the newline character from the binary IP input.
332 // Why: Cleans the input by replacing the newline with a null terminator.
333 // How: Uses strcspn to find the newline and replaces it with '\0'.
334
335 binary_to_ipv4(binary_ip);
336 // Calls the function to convert the binary IP to decimal.
337 // Why: Performs the binary-to-decimal conversion.
338 // How: Passes the binary IP string to binary_to_ipv4.
339
340 } else {
341 // Handles invalid menu choices.
342 // Why: Catches cases where the user enters a number other than 1 or 2.
343 // How: Executes if choice is neither 1 nor 2.
344
345 printf("Invalid choice!\n");
346 // Prints an error message for invalid choices.
347 // Why: Informs the user that their selection is not valid.
348 // How: Outputs the error message to the console.
349
350 }
351 return 0;
352 // Exits the program with a success code.
353 // Why: Indicates successful execution of the program.
354 // How: Returns 0 to the operating system.
355
356 }