Find the answer to your Linux question:
Results 1 to 7 of 7
Hello again, I am still new to this language still and I have a programming project that needs to be done in 2 weeks. I am getting a head start ...
  1. #1
    Just Joined!
    Join Date
    Sep 2008
    Location
    Buffalo, NY
    Posts
    25

    C Programming Project - Have Questions about functions!!

    Hello again, I am still new to this language still and I have a programming project that needs to be done in 2 weeks. I am getting a head start now

    I have started the code already and I am trying to finish the introduction code before the conversion, which is going to be the hard part. If you look at the code, I need to use functions within each case that asks the questions for each choice, perform the operation, and display the answer.
    - ex:
    *"Enter the 32 bit binary IP that you want to be converted to dotted decimal ip form"
    *"The answer is ####"
    (I know printf and scanf can be used but I researched that using functions would be better and easier *if I knew how to use them*)

    My question:
    What function code should I use that would ask the question, perform the operation, and display the answer? I know the function needs to be placed within each case
    **Any suggestions/assistance/information would be greatly appreciated**

    Here is the project:
    Project 1
    project 1 menu:

    ***************************************
    Select from one of the choices:

    1) Convert from 32 bit binary(in chunks of 8 bits) ip form to dotted decimal ip form
    2) Convert from dotted decimal ip form to 32 bit binary ip form
    3) Convert a dotted decimal ip form to it's class
    and display the network and host portions separately
    4) Convert from CIDR slash notation to dotted decimal ip form
    5) Convert from subnet dotted ip form to CIDR slash form
    6) Quit the program

    Enter your choice:
    *********************************************

    do not include the *s, repeatly show the menu until the user decides
    to exit the program


    no external documentation is required for this project, the program may be
    written in C or C++ or Java or C#.

    TO RECEIVE CREDIT FOR YOUR PROJECT:
    email the source file as an attached file to ********.edu
    use the subject heading for the email "CS211 Proj1"
    (this is very critical, you may want to cut and paste this)

    DUE DATE : 11/26/2008

    *Code is attached
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    main()
    {
    int choice;
    
    do
    { printf("Select from one of the choices:\n");
      printf("1.) Convert from 32 bit binary ip form to dotted decimal ip form\n");
      printf("2.) Convert from dotted decimal ip form to 32 bit binary ip form\n");
      printf("3.) Convert a dotted decimal ip form to it's class and display the network portions separately\n");
      printf("4.) Convert from CIDR slash notation to dotted decimal ip form\n");
      printf("5.) Convert from subnet dotted ip form to CIDR slash form\n");
      printf("6.) Quit the the program\n");
    printf("Enter your choice: ");
    scanf(" %d", &choice);
    switch (choice)
      {
    case (1) : printf("1.) Convert from 32 bit binary ip form to dotted decimal ip form\n");
    break;
    case (2) : printf("2.) Convert from dotted decimal ip form to 32 bit binary ip form\n");
    break;
    case (3) : printf("3.) Convert a dotted decimal ip form to it's class and display the network portions separately\n");
    break;
    case (4) : printf("4.) Convert from CIDR slash notation to dotted decimal ip form\n");
    break;
    case (5) : printf("5.) Convert from subnet dotted ip form to CIDR slash form\n");
    break;
    case (6) : exit(0);
    break;
    default  : printf("I don't know the ");
               printf("option %d. \n", choice);
               printf("Try again. \n");
               break;
      }
    system("clear");
    } while(1);
    }

  2. #2
    Just Joined!
    Join Date
    Sep 2008
    Location
    Buffalo, NY
    Posts
    25
    After some more research and testing. I think I have the code to convert from decimal IP to 32 bit binary IP.

    What does everyone think?

    Code:
    {
    // Initialize the variables
    unsigned long a,b,c,d,base10IP;
    
    // Get the IP address from user
    cout << "\nEnter an IP address in dotted quad notation (x.x.x.x)";
    cout << "\nwith each section seperated by a space: ";
    cin >> a >> b >> c >> d;
    
    // Do calculations to covert IP to base 10
    a *= 16777216;
    b *= 65536;
    c *= 256;
    base10IP = a + b + c + d;
    
    // Output new IP address
    cout << "\nThe converted address is: " << base10IP << '\n';
    }

  3. #3
    Linux Engineer wje_lf's Avatar
    Join Date
    Sep 2007
    Location
    Mariposa
    Posts
    1,192
    Test it. Try various values. Does it work?
    --
    Bill

    Old age and treachery will overcome youth and skill.

  4. #4
    Just Joined!
    Join Date
    Sep 2008
    Location
    Buffalo, NY
    Posts
    25
    Quote Originally Posted by wje_lf View Post
    Test it. Try various values. Does it work?
    I am planning to try it as soon as I get home since I am on a PC that doesn't have C. I've been playing around in notepad until I get home.

  5. #5
    Just Joined!
    Join Date
    Sep 2008
    Location
    Buffalo, NY
    Posts
    25
    It doesn't work because I am using cout and cin which is not found in C but found in C++.

    Does anybody have any suggestions in code that performs the same functions of cout and cin in C??

  6. #6
    Linux Engineer wje_lf's Avatar
    Join Date
    Sep 2007
    Location
    Mariposa
    Posts
    1,192
    You're already familiary with printf() and fprintf(), yes?
    --
    Bill

    Old age and treachery will overcome youth and skill.

  7. #7
    Just Joined!
    Join Date
    Sep 2008
    Location
    Buffalo, NY
    Posts
    25
    If anybody wants to know the end code - here it is
    Thanks for the help everyone!

    Code:
    //************************************************************************
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    // read an IP address in binary form
    // store it into an array of 4 strings of 8 chars each
    // return 1 if read successfully or 0 if an error occurred
      int readBinary(char bin[4][8]) {
      char binString[80];
      int i, j;
      int nextChar = 0;
      int len;
    
    // read line
      printf("Enter 32-bit IP address in binary form (xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx): ");
      fflush(stdout); //flushes the output, it is needed on some version of linux/unix before scanf
      scanf("%[^\r\n]", binString);
    
    // store binary digits into bin array
      len = strlen(binString);
      for (i=0; i<4; i++) {
        if (nextChar >= len) {
          printf("Invalid input string (too short)\n");
          return 0;
        }
        for (j=0; j<8; j++) {
    // skip spaces
          while (nextChar < len && binString[nextChar] == ' ')
            nextChar++;
    // end of string? break the loop
          if (nextChar >= len) {
            printf("Invalid input string (too short)\n");
            return 0;
          }
          bin[i][j] = binString[nextChar];
          nextChar++;
    // only 0 and 1 accepted
          if (bin[i][j] != '0' && bin[i][j] != '1') {
            printf("Invalid input string (not a binary number)\n");
            return 0;
          }
        }
      }
    
    // return 1 (OK)
      return 1;
    }
    
    // read an IP address in decimal dotted form
    // return 1 if ok or 0 if an error occurs
      int readIPAddress(int ipaddr[]) {
      char decstring[4][4];
      int i;
    
    // read IP address as strings
      printf("Enter 32-bit IP address in dotted decimal notation (xxx.xxx.xxx.xxx): ");
      fflush(stdout);
      if (scanf("%[^.].%[^.].%[^.].%[^\r\n]", decstring[0], decstring[1], decstring[2], decstring[3]) < 4) {
        printf("Invalid input string (wrong IP address format)\n");
        return 0;
      }
    
    // convert each string to integer
      for (i=0; i<4; i++) {
        ipaddr[i] = atoi(decstring[i]);  // atoi converts a string to an integer
        if (ipaddr[i] < 0 || ipaddr[i] > 255) {
          printf("Invalid input string (incorrect numbers for IP address)\n");
          return 0;
        }
      }
    
      return 1;
    }
    
    // read an IP address slash netmask length (CIDR format)
    // return 1 if ok or 0 if an error occurs
    int readIPSlashAddress(int ipaddr[], int *slash) {
      char decstring[4][4];
      char slashstring[3];
      int i;
    
    // read IP address as strings
      printf("Enter IP-address in CIDR notation (xxx.xxx.xxx.xxx/xx): ");
      fflush(stdout);
      if (scanf("%[^.].%[^.].%[^.].%[^/]/%[^\r\n]", decstring[0], decstring[1], decstring[2], decstring[3], slashstring) < 5) {
        printf("Invalid input string (wrong IP address format)\n");
        return 0;
      }
    
    // convert each string to integer
      for (i=0; i<4; i++) {
        ipaddr[i] = atoi(decstring[i]);
        if (ipaddr[i] < 0 || ipaddr[i] > 255) {
          printf("Invalid input string (incorrect numbers for IP address)\n");
          return 0;
        }
      }
    
      *slash = atoi(slashstring);  // a variable and it stores the netmask-length
      if (*slash < 0 || *slash > 32) {
        printf("Invalid input string (invalid netmask length)\n");
        return 0;
      }
    
      return 1;
    }
    
    // read an IP address slash netmask
    // return 1 if ok or 0 if an error occurs
      int readIPMaskAddress(int ipaddr[], int mask[]) {
      char decstring[4][4];
      char maskstring[4][4];
      int i;
    
    // read IP address as strings
      printf("Enter IP-address/subnet you want converted to CIDR slash form (xxx.xxx.xxx.xxx/xxx.xxx.xxx.xxx.): ");
      fflush(stdout);
      if (scanf("%[^.].%[^.].%[^.].%[^/]/%[^.].%[^.].%[^.].%[^\r\n]", decstring[0], decstring[1], decstring[2], decstring[3],
          maskstring[0], maskstring[1], maskstring[2], maskstring[3]) < 8) {
        printf("Invalid input string (wrong IP address/netmask format)\n");
        return 0;
      }
    
    // convert each string to integer
       for (i=0; i<4; i++) {
        ipaddr[i] = atoi(decstring[i]);
        if (ipaddr[i] < 0 || ipaddr[i] > 255) {
          printf("Invalid input string (incorrect numbers for IP address)\n");
          return 0;
        }
      }
    
    // convert each string to integer
       for (i=0; i<4; i++) {
        mask[i] = atoi(maskstring[i]);
        if (mask[i] < 0 || mask[i] > 255) {
          printf("Invalid input string (incorrect numbers for netmask)\n");
          return 0;
        }
      }
      return 1;
    }
    
    void convertBinToDec(char bin[4][8], int dec[]) {
    
      int i, j;
    
    // convert each binary group to decimal number
      for (i=0; i<4; i++) {
        dec[i] = 0;
        for (j=0; j<8; j++) {
          dec[i] *= 2;
          if (bin[i][j] == '1')
            dec[i]++;
        }
      }
    
    }
    
    void convertDecToBin(int dec[], char bin[4][9]) {
    
      int i, j;
    
    // convert each decimal group to binary
      for (i=0; i<4; i++) {
        for (j=7; j>=0; j--) {
          bin[i][j] = (dec[i] & 1) + '0';
          dec[i] /= 2;
        }
        bin[i][8] = 0;
      }
    
    }
    
    // show network and host parts
    void showNetworkHost(int ipaddr[], int numNetwork) {
      int i;
    
      printf("Network portion is: ");
      for (i=0; i<=numNetwork; i++)
        printf("%d.", ipaddr[i]);
      printf("\n");
    
      printf("Host portion is: ");
      for (i=numNetwork+1; i<4; i++)
        printf(".%d", ipaddr[i]);
      printf("\n");
    }
    
    void convertCIDRToNetmask(int slash, int mask[]) {
    
    // create binary mask first, then convert to decimal
      char bin[4][8];
      int i, j;
    
    // write 1's while slash is positive, then write 0's
      for (i=0; i<4; i++)
        for (j=0; j<8; j++) {
          if (slash > 0) {
            bin[i][j] = '1';
            slash--;
          }
          else
            bin[i][j] = '0';
        }
    
    // convert to decimal
      convertBinToDec(bin, mask);
    }
    
      int convertNetmaskToCIDR(int mask[], int *slash) {
    // create binary mask first, then convert to slash form
      char bin[4][9];
      int i, j;
      char lastChar;
    
      convertDecToBin(mask, bin);
    
    // add to slash while 1's are found
      lastChar = '1';
      *slash = 0;
      for (i=0; i<4; i++)
        for (j=0; j<8; j++) {
          if (bin[i][j] == '1') {
    // once a zero is found - no more 1's should appear
            if (lastChar == '0') {
              printf("Cannot convert netmask to CIDR notation\n");
              return 0;
            }
            (*slash)++;
          }
          lastChar = bin[i][j];
        }
    
      return 1;
    }
    
    int main()
    {
      int choice;
      char bin[4][8];
      char bin2[4][9];
      int ipaddr[4];
      int mask[4];
      int slash;
    
    // temp string, used when reading - used to skip any remaining input after reading
    // a menu option in the main menu.  The main menu scanf reads an integer.  If a temp
    // string wasn't used, the next scanf trying to read a string would read an empty string 
      char temp[80];
    
      do
      {
        printf("\nSelect from one of the choices:\n\n");
        printf("1) Convert from 32 bit binary ip form to dotted decimal ip form\n");
        printf("2) Convert from dotted decimal ip form to 32 bit binary ip form\n");
        printf("3) Convert a dotted decimal ip form to its class and display the network and host portions separately\n");
        printf("4) Convert from IP/CIDR slash notation to dotted decimal ip form\n");
        printf("5) Convert from IP/subnet dotted ip form to CIDR slash form\n");
        printf("6) Quit the program\n");
        printf("\nEnter your choice: ");
        fflush(stdout);
        scanf("%d", &choice);
        scanf("%[^\n]", temp);
        scanf("%c", temp);
    
        switch (choice)
        {
          case (1) : // Convert from 32 bit binary ip form to dotted decimal ip form
    
                     if (!readBinary(bin))
                       break;
    
                     convertBinToDec(bin, ipaddr);
    
                     // print the resulting IP
                     printf("The address converted to decimal is: %d.%d.%d.%d\n", ipaddr[0], ipaddr[1], ipaddr[2], ipaddr[3]);
    
                     break;
    
          case (2) : // Convert from dotted decimal ip form to 32 bit binary ip form
                     if (!readIPAddress(ipaddr))
                       break;
    
                     convertDecToBin(ipaddr, bin2);
    
                     // print the results
                     printf("The address converted to binary is: %8s %8s %8s %8s\n", bin2[0], bin2[1], bin2[2], bin2[3]);
                     break;
    
          case (3) : // Convert a dotted decimal ip form to its class
                     if (!readIPAddress(ipaddr))
                       break;
    
                     if (ipaddr[0] < 128) {
                       printf("This address belongs to class A\n");
                       showNetworkHost(ipaddr, 0);
                     }
                     else if (ipaddr[0] < 192) {
                       printf("This address belongs to class B\n");
                       showNetworkHost(ipaddr, 1);
                     }
                     else if (ipaddr[0] < 224) {
                       printf("This address belongs to class C\n");
                       showNetworkHost(ipaddr, 2);
                     }
                     else if (ipaddr[0] < 240)
                       printf("This address belongs to class D\n");
                     else
                       printf("This address belongs to class E\n");
    
                     break;
          case (4) : // Convert from IP CIDR slash notation of to dotted decimal ip form
                     if (!readIPSlashAddress(ipaddr, &slash))
                       break;
    
                     convertCIDRToNetmask(slash, mask);
    
                     printf("IP/Netmask in dotted decimal IP form: %d.%d.%d.%d/%d.%d.%d.%d\n",
                         ipaddr[0], ipaddr[1], ipaddr[2], ipaddr[3], mask[0], mask[1], mask[2], mask[3]);
    
                     break;
    
          case (5) : // Convert from IP/subnet form to CIDR slash form
                     if (!readIPMaskAddress(ipaddr, mask))
                       break;
    
                     if (!convertNetmaskToCIDR(mask, &slash))
                       break;
    
                     printf("IP/Netmask-length in CIDR notation: %d.%d.%d.%d/%d",
                         ipaddr[0], ipaddr[1], ipaddr[2], ipaddr[3], slash);
    
                     break;
    
          case (6) : system("clear"); //clear program
                     exit(0); // close program
    
          default  : printf("I don't know the option %d.\n", choice);
                     printf("Try again.\n");
                     break;
        }
      } while(1);
    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...