Home > Software design >  Command line arguments
Command line arguments

Time:05-15

How would i go about coding (in C) a program that accepts one command line argument, (that includes the program name and the port number that will be used for the program). And it would return -1 if the argument is not specified or less than 1024?

And then it would initiate the required socket operations to create and bind a socket.

cheers

CodePudding user response:

#include<stdio.h>
#include<stdlib.h>
  
int main(int argc,char* argv[]){
    // printf("asdasdasdasd");
    // yo can capture program name as below
    // printf("Program Name Is : %s",argv[0]);
    if(argc==1){
        return(514);
    };
    if(argc>=2){
        int port = atoi(argv[1]);
        if(port<1024){
            return(514);
        }
        else{
            return(513);
        }
    }
    // printf("asdsads");
    return 0;
}

The return value from main is generally used to indicate the execution status.The max value returned from main is limited to 512. If you try to return a greater value than 512, for example 513, you will get 1 as return. If you returned 514, you will get 2 as return value. You can see the return value by running echo $? after execution. See below:

gcc -o main main.c
echo $?

Assuming your program name is main.c. Instead of returning -1 yo can check the status by returning an integer easily.

CodePudding user response:

    #include <stdio.h>
    #include <stdlib.h>
    #include <stdint.h>

    int main(int argc, char **argv) {
        // FIXME check for argc < 2
        uint16_t port = (uint16_t)atoi(argv[1]);
        if (port < 1024) {
            fprintf(stderr, "Port %s is less than 1024, cannot proceed.", argv[1]);
            return 3;
        }
    }

Ok let's start unpacking.

First off, convert the first argument to an integer. Then convert it to unsigned int16. (This happens to work correctly on the one 16 bit platform I looked at, but I don't know if its guaranteed or not. It definitely works on all 32 or 64 bit platforms.)

Ports are always unsigned 16 bit integers; thus the range from 0 to 65535; but 0 isn't usable in BSD sockets so the range is really 1 to 65535.

From there, we simply check if it's less than 1024; if so error message. Since the range of uint16_t is correct; we don't need any more checks. The error message contains the original string, which may or may not be the best way to report the problem to the user.

  •  Tags:  
  • c
  • Related