## C++ || Multi Digit, Decimal & Negative Number Infix To Postfix Conversion & Evaluation

The following is sample code which demonstrates the implementation of a multi digit, decimal, and negative number infix to postfix converter and evaluator using a Finite State Machine

REQUIRED KNOWLEDGE FOR THIS PROGRAM

```How To Convert Infix To Postfix How To Evaluate A Postfix Expression What Is A Finite State Machine? ```

Using a Finite State Machine, the program demonstrated on this page has the ability to convert and evaluate a single digit, multi digit, decimal number, and/or negative number infix equation. So for example, if the the infix equation of (19.87 * ~2) was entered into the program, the converted postfix expression of 19.87 ~2* would display to the screen, as well as the final evaluated answer of -39.74.

NOTE: In this program, negative numbers are represented by the “~” symbol.

This program has the following flow of control:

```• Get an infix expression from the user • Convert the infix expression to postfix • Use a Finite State Machine to isolate all of the math operators, multi digit, decimal, negative and single digit numbers that are found in the postfix expression • Evaluate the postfix expression using the tokens found from the above step • Display the evaluated answer to the screen ```

The above steps are implemented below.

``` Multi Digit Infix To Postfix Conversion & Evaluation C++ // ============================================================================ // Author: K Perkins // Taken From: http://programmingnotes.org/ // Date: Jan 31, 2014 // File: InToPostEval.cpp // Description: The following demonstrates the implementation of an infix to // postfix converter and evaluator. Using a Finite State Machine, this // program has the ability to convert and evaluate multi digit, decimal, // negative and positive values. // ============================================================================ #include <iostream> #include <cstdlib> #include <cmath> #include <cctype> #include <string> #include <vector> #include <stack> using namespace std; /* This holds the transition states for our Finite State Machine -- They are placed in numerical order for easy understanding within the FSM array, which is located below */ enum FSM_TRANSITIONS { REJECT = 0, INTEGER, REAL, NEGATIVE, OPERATOR, UNKNOWN, SPACE }; /* This is the Finite State Machine -- The zero represents a place holder, so the row in the array starts on row 1 instead of 0 integer, real, negative, operator, unknown, space */ int stateTable[][7] = {{0, INTEGER, REAL, NEGATIVE, OPERATOR, UNKNOWN, SPACE}, /* STATE 1 */ {INTEGER, INTEGER, REAL, REJECT, REJECT, REJECT, REJECT}, /* STATE 2 */ {REAL, REAL, REJECT, REJECT, REJECT, REJECT, REJECT}, /* STATE 3 */ {NEGATIVE, INTEGER, REAL, REJECT, REJECT, REJECT, REJECT}, /* STATE 4 */ {OPERATOR, REJECT, REJECT, REJECT, REJECT, REJECT, REJECT}, /* STATE 5 */ {UNKNOWN, REJECT, REJECT, REJECT, REJECT, UNKNOWN, REJECT}, /* STATE 6 */ {SPACE, REJECT, REJECT, REJECT, REJECT, REJECT, REJECT}}; // function prototypes void DisplayDirections(); string ConvertInfixToPostfix(string infix); bool IsMathOperator(char token); int OrderOfOperations(char token); vector<string> Lexer(string postfix); int Get_FSM_Col(char& currentChar); double EvaluatePostfix(const vector<string>& postfix); double Calculate(char token, double op1, double op2); int main() { // declare variables string infix = ""; string postfix = ""; double answer = 0; vector<string> tokens; // display directions to user DisplayDirections(); // get data from user cout<<"nPlease enter an Infix expression: "; getline(cin, infix); postfix = ConvertInfixToPostfix(infix); // use the "Lexer" function to isolate multi digit, negative and decimal // numbers, aswell as single digit numbers and math operators tokens = Lexer(postfix); // display the found tokens to the screen // for(unsigned x = 0; x < tokens.size(); ++x) // { // cout<<tokens.at(x)<<endl; // } cout <<"nThe Infix expression = "<<infix; cout <<"nThe Postfix expression = "<<postfix<<endl; answer = EvaluatePostfix(tokens); cout<<"nFinal answer = "<<answer<<endl; return 0; }// end of main void DisplayDirections() {// this function displays instructions to the screen cout << "n==== Infix To Postfix Conversion & Evaluation ====n" <<"nMath Operators:n" <<"+ || Additionn" <<"- || Subtractionn" <<"* || Multiplicationn" <<"/ || Divisionn" <<"% || Modulusn" <<"^ || Powern" <<"\$ || Square Rootn" <<"s || Sinen" <<"c || Cosinen" <<"t || Tangentn" <<"~ || Negative Numbernn" <<"Sample Infix Equation: ((s(~4^5)*1.4)/(\$(23+2)-~2.8))*(c(1%2)/(7.28*.1987)^(t23))n"; // ((sin(-4^5)*1.4)/(sqrt(23+2)--2.8))*(cos(1%2)/(7.28*.1987)^(tan(23))) }// end of DisplayDirections string ConvertInfixToPostfix(string infix) {// this function converts an infix expression to postfix // declare function variables string postfix; stack<char> charStack; // loop thru array until there is no more data for(unsigned x = 0; x < infix.length(); ++x) { // place numbers (standard, decimal, & negative) // numbers onto the 'postfix' string if((isdigit(infix[x])) || (infix[x] == '.') || (infix[x] == '~')) { postfix += infix[x]; } else if(isspace(infix[x])) { continue; } else if(IsMathOperator(infix[x])) { postfix += " "; // use the 'OrderOfOperations' function to check equality // of the math operator at the top of the stack compared to // the current math operator in the infix string while((!charStack.empty()) && (OrderOfOperations(charStack.top()) >= OrderOfOperations(infix[x]))) { // place the math operator from the top of the // stack onto the postfix string and continue the // process until complete postfix += charStack.top(); charStack.pop(); } // push the remaining math operator onto the stack charStack.push(infix[x]); } // push outer parentheses onto stack else if(infix[x] == '(') { charStack.push(infix[x]); } else if(infix[x] == ')') { // pop the current math operator from the stack while((!charStack.empty()) && (charStack.top() != '(')) { // place the math operator onto the postfix string postfix += charStack.top(); // pop the next operator from the stack and // continue the process until complete charStack.pop(); } if(!charStack.empty()) // pop '(' symbol off the stack { charStack.pop(); } else // no matching '(' { cout<<"nPARENTHESES MISMATCH #1n"; exit(1); } } else { cout<<"nINVALID INPUT #1n"; exit(1); } } // place any remaining math operators from the stack onto // the postfix array while(!charStack.empty()) { postfix += charStack.top(); charStack.pop(); } return postfix; }// end of ConvertInfixToPostfix bool IsMathOperator(char token) {// this function checks if operand is a math operator switch(tolower(token)) { case '+': case '-': case '*': case '/': case '%': case '^': case '\$': case 'c': case 's': case 't': return true; break; default: return false; break; } }// end of IsMathOperator int OrderOfOperations(char token) {// this function returns the priority of each math operator int priority = 0; switch(tolower(token)) { case 'c': case 's': case 't': priority = 5; break; case '^': case '\$': priority = 4; break; case '*': case '/': case '%': priority = 3; break; case '-': priority = 2; break; case '+': priority = 1; break; } return priority; }// end of OrderOfOperations vector<string> Lexer(string postfix) {// this function parses a postfix string using an FSM to generate // each individual token in the expression vector<string> tokens; char currentChar = ' '; int col = REJECT; int currentState = REJECT; string currentToken = ""; // use an FSM to parse multidigit and decimal numbers // also does error check for invalid input of decimals for(unsigned x = 0; x < postfix.length();) { currentChar = postfix[x]; // get the column number for the current character col = Get_FSM_Col(currentChar); // exit if the real number has multiple periods "." // in the expression (i.e: 19.3427.23) if((currentState == REAL) && (col == REAL)) { cerr<<"nINVALID INPUT #2n"; exit(1); } /* ======================================================== THIS IS WHERE WE CHECK THE FINITE STATE MACHINE TABLE USING THE "col" VARIABLE FROM ABOVE ^ ========================================================= */ // get the current state of our machine currentState = stateTable[currentState][col]; /* =================================================== THIS IS WHERE WE CHECK FOR A SUCESSFUL PARSE - If the current state in our machine == REJECT (the starting state), then we have sucessfully parsed a token, which is returned to its caller - ELSE we continue trying to find a sucessful token =================================================== */ if(currentState == REJECT) { if(currentToken != " ") // we dont care about whitespace { tokens.push_back(currentToken); } currentToken = ""; } else { currentToken += currentChar; ++x; } } // this ensures the last token gets saved when // we reach the end of the postfix string buffer if(currentToken != " ") // we dont care about whitespace { tokens.push_back(currentToken); } return tokens; }// end of Lexer int Get_FSM_Col(char& currentChar) {// this function determines the state of the type of character being examined // check for whitespace if(isspace(currentChar)) { return SPACE; } // check for integer numbers else if(isdigit(currentChar)) { return INTEGER; } // check for real numbers else if(currentChar == '.') { return REAL; } // check for negative numbers else if(currentChar == '~') { currentChar = '-'; return NEGATIVE; } // check for math operators else if(IsMathOperator(currentChar)) { return OPERATOR; } return UNKNOWN; }// end of Get_FSM_Col double EvaluatePostfix(const vector<string>& postfix) {// this function evaluates a postfix expression // declare function variables double op1 = 0; double op2 = 0; double answer = 0; stack<double> doubleStack; cout<<"nCalculations:n"; // loop thru array until there is no more data for(unsigned x = 0; x < postfix.size(); ++x) { // push numbers onto the stack if((isdigit(postfix[x][0])) || (postfix[x][0] == '.')) { doubleStack.push(atof(postfix[x].c_str())); } // push negative numbers onto the stack else if((postfix[x].length() > 1) && ((postfix[x][0] == '-') && (isdigit(postfix[x][1]) || (postfix[x][1] == '.')))) { doubleStack.push(atof(postfix[x].c_str())); } // if expression is a math operator, pop numbers from stack // & send the popped numbers to the 'Calculate' function else if(IsMathOperator(postfix[x][0]) && (!doubleStack.empty())) { char token = tolower(postfix[x][0]); // if expression is square root, sin, cos, // or tan operation only pop stack once if(token == '\$' || token == 's' || token == 'c' || token == 't') { op2 = 0; op1 = doubleStack.top(); doubleStack.pop(); answer = Calculate(token, op1, op2); doubleStack.push(answer); } else if(doubleStack.size() > 1) { op2 = doubleStack.top(); doubleStack.pop(); op1 = doubleStack.top(); doubleStack.pop(); answer = Calculate(token, op1, op2); doubleStack.push(answer); } } else // this should never execute, & if it does, something went really wrong { cout<<"nINVALID INPUT #3n"; exit(1); } } // pop the final answer from the stack, and return to main if(!doubleStack.empty()) { answer = doubleStack.top(); } return answer; }// end of EvaluatePostfix double Calculate(char token, double op1, double op2) {// this function carries out the actual math process double ans = 0; switch(tolower(token)) { case '+': cout<<op1<<token<<op2<<" = "; ans = op1 + op2; break; case '-': cout<<op1<<token<<op2<<" = "; ans = op1 - op2; break; case '*': cout<<op1<<token<<op2<<" = "; ans = op1 * op2; break; case '/': cout<<op1<<token<<op2<<" = "; ans = op1 / op2; break; case '%': cout<<op1<<token<<op2<<" = "; ans = ((int)op1%(int)op2)+modf(op1 , &op2); break; case '^': cout<<op1<<token<<op2<<" = "; ans = pow(op1, op2); break; case '\$': cout<<char(251)<<op1<<" = "; ans = sqrt(op1); break; case 'c': cout<<"cos("<<op1<<") = "; ans = cos(op1); break; case 's': cout<<"sin("<<op1<<") = "; ans = sin(op1); break; case 't': cout<<"tan("<<op1<<") = "; ans = tan(op1); break; default: ans = 0; break; } cout<<ans<<endl; return ans; }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454 // ============================================================================//   Author:  K Perkins//   Taken From: http://programmingnotes.org///   Date:  Jan 31, 2014//   File: InToPostEval.cpp//   Description: The following demonstrates the implementation of an infix to//     postfix converter and evaluator. Using a Finite State Machine, this//     program has the ability to convert and evaluate multi digit, decimal,//     negative and positive values.// ============================================================================#include <iostream>#include <cstdlib>#include <cmath>#include <cctype>#include <string>#include <vector>#include <stack>using namespace std; /* This holds the transition states for our Finite State Machine    -- They are placed in numerical order for easy understanding within     the FSM array, which is located below */ enum FSM_TRANSITIONS{    REJECT = 0,    INTEGER,    REAL,    NEGATIVE,    OPERATOR,    UNKNOWN,    SPACE}; /* This is the Finite State Machine    -- The zero represents a place holder, so the row in the array         starts on row 1 instead of 0                            integer,  real,  negative, operator, unknown, space */int stateTable[][7] = {{0, INTEGER,  REAL, NEGATIVE, OPERATOR,  UNKNOWN,  SPACE},/* STATE 1 */   {INTEGER,  INTEGER,  REAL,   REJECT,  REJECT,   REJECT,  REJECT},/* STATE 2 */   {REAL,       REAL,  REJECT,  REJECT,  REJECT,   REJECT,  REJECT},/* STATE 3 */   {NEGATIVE, INTEGER,  REAL,   REJECT,  REJECT,   REJECT,  REJECT},/* STATE 4 */   {OPERATOR,  REJECT, REJECT,  REJECT,  REJECT,   REJECT,  REJECT},/* STATE 5 */   {UNKNOWN,   REJECT, REJECT,  REJECT,  REJECT,   UNKNOWN, REJECT},/* STATE 6 */   {SPACE,     REJECT, REJECT,  REJECT,  REJECT,   REJECT,  REJECT}}; // function prototypesvoid DisplayDirections();string ConvertInfixToPostfix(string infix);bool IsMathOperator(char token);int OrderOfOperations(char token);vector<string> Lexer(string postfix);int Get_FSM_Col(char& currentChar);double EvaluatePostfix(const vector<string>& postfix);double Calculate(char token, double op1, double op2); int main(){    // declare variables    string infix = "";    string postfix = "";    double answer = 0;    vector<string> tokens;     // display directions to user    DisplayDirections();     // get data from user    cout<<"nPlease enter an Infix expression: ";    getline(cin, infix);     postfix = ConvertInfixToPostfix(infix);     // use the "Lexer" function to isolate multi digit, negative and decimal    // numbers, aswell as single digit numbers and math operators    tokens = Lexer(postfix);     // display the found tokens to the screen// for(unsigned x = 0; x < tokens.size(); ++x)// {//     cout<<tokens.at(x)<<endl;// }     cout <<"nThe Infix expression = "<<infix;    cout <<"nThe Postfix expression = "<<postfix<<endl;     answer = EvaluatePostfix(tokens);     cout<<"nFinal answer = "<<answer<<endl;     return 0;}// end of main void DisplayDirections(){// this function displays instructions to the screen    cout << "n==== Infix To Postfix Conversion & Evaluation ====n"        <<"nMath Operators:n"        <<"+ || Additionn"        <<"- || Subtractionn"        <<"* || Multiplicationn"        <<"/ || Divisionn"        <<"% || Modulusn"        <<"^ || Powern"        <<"\$ || Square Rootn"        <<"s || Sinen"        <<"c || Cosinen"        <<"t || Tangentn"        <<"~ || Negative Numbernn"        <<"Sample Infix Equation: ((s(~4^5)*1.4)/(\$(23+2)-~2.8))*(c(1%2)/(7.28*.1987)^(t23))n";        // ((sin(-4^5)*1.4)/(sqrt(23+2)--2.8))*(cos(1%2)/(7.28*.1987)^(tan(23)))}// end of DisplayDirections string ConvertInfixToPostfix(string infix){// this function converts an infix expression to postfix    // declare function variables    string postfix;    stack<char> charStack;     // loop thru array until there is no more data    for(unsigned x = 0; x < infix.length(); ++x)    {        // place numbers (standard, decimal, & negative)        // numbers onto the 'postfix' string        if((isdigit(infix[x])) || (infix[x] == '.') || (infix[x] == '~'))        {            postfix += infix[x];        }        else if(isspace(infix[x]))        {            continue;        }        else if(IsMathOperator(infix[x]))        {            postfix += " ";            // use the 'OrderOfOperations' function to check equality            // of the math operator at the top of the stack compared to            // the current math operator in the infix string            while((!charStack.empty()) &&                (OrderOfOperations(charStack.top()) >= OrderOfOperations(infix[x])))            {                // place the math operator from the top of the                // stack onto the postfix string and continue the                // process until complete                postfix += charStack.top();                charStack.pop();            }            // push the remaining math operator onto the stack            charStack.push(infix[x]);        }        // push outer parentheses onto stack        else if(infix[x] == '(')        {            charStack.push(infix[x]);        }        else if(infix[x] == ')')        {            // pop the current math operator from the stack            while((!charStack.empty()) && (charStack.top() != '('))            {                // place the math operator onto the postfix string                postfix += charStack.top();                // pop the next operator from the stack and                // continue the process until complete                charStack.pop();            }             if(!charStack.empty()) // pop '(' symbol off the stack            {                charStack.pop();            }            else // no matching '('            {                cout<<"nPARENTHESES MISMATCH #1n";                exit(1);            }        }        else        {            cout<<"nINVALID INPUT #1n";            exit(1);        }    }     // place any remaining math operators from the stack onto    // the postfix array    while(!charStack.empty())    {        postfix += charStack.top();        charStack.pop();    }     return postfix;}// end of ConvertInfixToPostfix bool IsMathOperator(char token){// this function checks if operand is a math operator    switch(tolower(token))    {        case '+': case '-': case '*': case '/':        case '%': case '^': case '\$': case 'c':        case 's': case 't':            return true;            break;        default:           return false;           break;    }}// end of IsMathOperator int OrderOfOperations(char token){// this function returns the priority of each math operator    int priority = 0;    switch(tolower(token))    {        case 'c': case 's': case 't':           priority = 5;           break;        case '^': case '\$':           priority = 4;           break;        case '*': case '/': case '%':           priority = 3;           break;        case '-':           priority = 2;           break;        case '+':           priority = 1;           break;    }    return priority;}// end of OrderOfOperations vector<string> Lexer(string postfix){// this function parses a postfix string using an FSM to generate //  each individual token in the expression    vector<string> tokens;    char currentChar = ' ';    int col = REJECT;    int currentState = REJECT;    string currentToken = "";     // use an FSM to parse multidigit and decimal numbers    // also does error check for invalid input of decimals    for(unsigned x = 0; x < postfix.length();)    {        currentChar = postfix[x];         // get the column number for the current character        col = Get_FSM_Col(currentChar);         // exit if the real number has multiple periods "."        // in the expression (i.e: 19.3427.23)        if((currentState == REAL) && (col == REAL))        {            cerr<<"nINVALID INPUT #2n";            exit(1);        }        /* ========================================================             THIS IS WHERE WE CHECK THE FINITE STATE MACHINE TABLE               USING THE "col" VARIABLE FROM ABOVE ^           ========================================================= */         // get the current state of our machine        currentState = stateTable[currentState][col];         /* ===================================================           THIS IS WHERE WE CHECK FOR A SUCESSFUL PARSE           - If the current state in our machine == REJECT             (the starting state), then we have sucessfully parsed             a token, which is returned to its caller             - ELSE we continue trying to find a sucessful token             =================================================== */        if(currentState == REJECT)        {            if(currentToken != " ") // we dont care about whitespace            {                tokens.push_back(currentToken);            }            currentToken = "";        }        else        {            currentToken += currentChar;            ++x;        }     }    // this ensures the last token gets saved when    // we reach the end of the postfix string buffer    if(currentToken != " ") // we dont care about whitespace    {        tokens.push_back(currentToken);    }    return tokens;}// end of Lexer int Get_FSM_Col(char& currentChar){// this function determines the state of the type of character being examined    // check for whitespace    if(isspace(currentChar))    {        return SPACE;    }     // check for integer numbers    else if(isdigit(currentChar))    {        return INTEGER;    }     // check for real numbers    else if(currentChar == '.')    {        return REAL;    }     // check for negative numbers    else if(currentChar == '~')    {        currentChar = '-';        return NEGATIVE;    }     // check for math operators    else if(IsMathOperator(currentChar))    {        return OPERATOR;    }    return UNKNOWN;}// end of Get_FSM_Col double EvaluatePostfix(const vector<string>& postfix){// this function evaluates a postfix expression    // declare function variables    double op1 = 0;    double op2 = 0;    double answer = 0;    stack<double> doubleStack;     cout<<"nCalculations:n";     // loop thru array until there is no more data    for(unsigned x = 0; x < postfix.size(); ++x)    {        // push numbers onto the stack        if((isdigit(postfix[x][0])) || (postfix[x][0] == '.'))        {           doubleStack.push(atof(postfix[x].c_str()));        }        // push negative numbers onto the stack        else if((postfix[x].length() > 1) && ((postfix[x][0] == '-') &&            (isdigit(postfix[x][1]) || (postfix[x][1] == '.'))))        {           doubleStack.push(atof(postfix[x].c_str()));        }        // if expression is a math operator, pop numbers from stack        // & send the popped numbers to the 'Calculate' function        else if(IsMathOperator(postfix[x][0]) && (!doubleStack.empty()))        {            char token = tolower(postfix[x][0]);             // if expression is square root, sin, cos,            // or tan operation only pop stack once            if(token == '\$' || token == 's' || token == 'c' || token == 't')            {                op2 = 0;                op1 = doubleStack.top();                doubleStack.pop();                answer = Calculate(token, op1, op2);                doubleStack.push(answer);            }            else if(doubleStack.size() > 1)            {                op2 = doubleStack.top();                doubleStack.pop();                op1 = doubleStack.top();                doubleStack.pop();                answer = Calculate(token, op1, op2);                doubleStack.push(answer);            }        }        else // this should never execute, & if it does, something went really wrong        {           cout<<"nINVALID INPUT #3n";           exit(1);        }    }    // pop the final answer from the stack, and return to main    if(!doubleStack.empty())    {        answer = doubleStack.top();    }    return answer;}// end of EvaluatePostfix double Calculate(char token, double op1, double op2){// this function carries out the actual math process    double ans = 0;    switch(tolower(token))    {        case '+':           cout<<op1<<token<<op2<<" = ";           ans = op1 + op2;           break;        case '-':           cout<<op1<<token<<op2<<" = ";           ans = op1 - op2;           break;        case '*':           cout<<op1<<token<<op2<<" = ";           ans = op1 * op2;           break;        case '/':           cout<<op1<<token<<op2<<" = ";           ans = op1 / op2;           break;        case '%':           cout<<op1<<token<<op2<<" = ";           ans = ((int)op1%(int)op2)+modf(op1 , &op2);           break;        case '^':           cout<<op1<<token<<op2<<" = ";           ans = pow(op1, op2);           break;        case '\$':           cout<<char(251)<<op1<<" = ";           ans = sqrt(op1);           break;        case 'c':            cout<<"cos("<<op1<<") = ";            ans = cos(op1);            break;        case 's':            cout<<"sin("<<op1<<") = ";            ans = sin(op1);            break;        case 't':            cout<<"tan("<<op1<<") = ";            ans = tan(op1);            break;        default:           ans = 0;           break;    }    cout<<ans<<endl;    return ans;}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

The following is sample output.

```====== RUN 1 ====== ==== Infix To Postfix Conversion & Evaluation ====```

``` Math Operators: + || Addition - || Subtraction * || Multiplication / || Division % || Modulus ^ || Power \$ || Square Root s || Sine c || Cosine t || Tangent ~ || Negative Number Sample Infix Equation: ((s(~4^5)*1.4)/(\$(23+2)-~2.8))*(c(1%2)/(7.28*.1987)^(t23)) Please enter an Infix expression: 12/3*9 The Infix expression = 12/3*9 The Postfix expression = 12 3 /9* Calculations: 12/3 = 4 4*9 = 36 Final answer = 36 ====== RUN 2 ====== ==== Infix To Postfix Conversion & Evaluation ==== Math Operators: + || Addition - || Subtraction * || Multiplication / || Division % || Modulus ^ || Power \$ || Square Root s || Sine c || Cosine t || Tangent ~ || Negative Number Sample Infix Equation: ((s(~4^5)*1.4)/(\$(23+2)-~2.8))*(c(1%2)/(7.28*.1987)^(t23)) Please enter an Infix expression: ~150.89996 - 87.56643 The Infix expression = ~150.89996 - 87.56643 The Postfix expression = ~150.89996 87.56643- Calculations: -150.9-87.5664 = -238.466 Final answer = -238.466 ====== RUN 3 ====== ==== Infix To Postfix Conversion & Evaluation ==== Math Operators: + || Addition - || Subtraction * || Multiplication / || Division % || Modulus ^ || Power \$ || Square Root s || Sine c || Cosine t || Tangent ~ || Negative Number Sample Infix Equation: ((s(~4^5)*1.4)/(\$(23+2)-~2.8))*(c(1%2)/(7.28*.1987)^(t23)) Please enter an Infix expression: ((s(~4^5)*1.4)/(\$(23+2)-~2.8))*(c(1%2)/(7.28*.1987)^(t23)) The Infix expression = ((s(~4^5)*1.4)/(\$(23+2)-~2.8))*(c(1%2)/(7.28*.1987)^(t23)) The Postfix expression = ~4 5^ s1.4* 23 2+ \$~2.8-/ 1 2% c7.28 .1987* 23t^/* Calculations: -4^5 = -1024 sin(-1024) = 0.158533 0.158533*1.4 = 0.221947 23+2 = 25 √25 = 5 5--2.8 = 7.8 0.221947/7.8 = 0.0284547 1%2 = 1 cos(1) = 0.540302 7.28*0.1987 = 1.44654 tan(23) = 1.58815 1.44654^1.58815 = 1.79733 0.540302/1.79733 = 0.300614 0.0284547*0.300614 = 0.00855389 Final answer = 0.00855389 ```

## Python || Find The Average Using A List – Omit Highest And Lowest Scores

This page will consist of a program which calculates the average of a specific amount of numbers using a list.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

```Lists For Loops Arithmetic Operators Basic Math - How To Find The Average ```

The following program is fairly simple, and was used to introduce the list concept. This program prompts the user to enter the total amount of numbers they wish to find the average for, then displays the answer to the screen. Using a sort, this program also has the ability to find the average of a list of numbers, omitting the highest and lowest valued items.

``` Find The Average Using A List Python # ============================================================================= # Author: K Perkins # Taken From: http://programmingnotes.org/ # Date: Jan 29, 2014 # File: Average.py # Description: The following demonstrates finding the average of numbers # contained in a list. # ============================================================================= # calculate the average of numbers in a list def Average(arry, size): total = 0 # traverse the list adding all the items together for x in range(size): total += arry[x] # return the average return total / size ## end of Average def main(): # declare variables arry = [] # initialize the list numElems = 0 # ask user how many items they want to place in list numElems = int(input("How many items do you want to place into the list?: ")) # print a newline print("") # user enters data into list using a for loop for x in range(0, numElems): arry.append(int(input("Enter item #%d: " % (x+1)))) # display data print("nThe current items inside the list are: ") for x in range(0, numElems): print("Item #%d: %d" % ((x+1), arry[x])) # display the average using a function print("nThe average of the %d numbers is %.2f" % (numElems, Average(arry, len(arry)))) # sort the numbers in the list from lowest to highest arry.sort() # erase the highest/lowest numbers arry.pop(len(arry)-1) arry.pop(0) # display the average using a function print("nThe average adjusted score omitting the highest and " "lowest result is %.2f" % (Average(arry, len(arry)))) ## end of main if __name__ == "__main__": main() # http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 # =============================================================================#   Author:  K Perkins#   Taken From: http://programmingnotes.org/#   Date:  Jan 29, 2014#   File: Average.py#   Description: The following demonstrates finding the average of numbers#     contained in a list.# =============================================================================# calculate the average of numbers in a listdef Average(arry, size):    total = 0     # traverse the list adding all the items together    for x in range(size):        total += arry[x]     # return the average    return total / size## end of Average def main():    # declare variables    arry = [] # initialize the list    numElems = 0     # ask user how many items they want to place in list    numElems = int(input("How many items do you want to place into the list?: "))     # print a newline    print("")     # user enters data into list using a for loop    for x in range(0, numElems):        arry.append(int(input("Enter item #%d: " % (x+1))))     # display data    print("nThe current items inside the list are: ")    for x in range(0, numElems):        print("Item #%d: %d" % ((x+1), arry[x]))     # display the average using a function    print("nThe average of the %d numbers is %.2f" %        (numElems, Average(arry, len(arry))))     # sort the numbers in the list from lowest to highest    arry.sort()     # erase the highest/lowest numbers    arry.pop(len(arry)-1)    arry.pop(0)     # display the average using a function    print("nThe average adjusted score omitting the highest and "        "lowest result is %.2f" % (Average(arry, len(arry))))## end of main if __name__ == "__main__":    main()# http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

The following is sample output.

`How many items do you want to place into the list?: 5`

``` Enter item #1: 7 Enter item #2: 7 Enter item #3: 4 Enter item #4: 8 Enter item #5: 7 The current items inside the list are: Item #1: 7 Item #2: 7 Item #3: 4 Item #4: 8 Item #5: 7 The average of the 5 numbers is 6.60 ```

```The average adjusted score omitting the highest and lowest result is 7.00 ```

## C++ || Simple Tokenizer Lexer Using A Finite State Machine

The following is sample code which demonstrates the implementation of a simple Lexer using a table driven Finite State Machine.

In its simplest form, a Finite State Machine is a procedure that can: (1) store the status of an event, (2) can operate on new (or existing) input to change the status of an event, and (3) can cause an action to take place (based on the input change) for the particular event being examined.

State machines usually adhere to the following basic principles:

```• Has an initial state or record of something stored someplace • Has a set of possible input events • Has a set of new states that may result from the input • Has a set of possible actions or output events that result from a new state ```

Finite state machines usually have a limited or finite number of possible states. The Finite State Machine implemented on this page has 6 transition states. Those transition states has the ability to isolate tokens from a given input string, based on characteristics defined in the transition state table.

The machine was implemented with compiler construction in mind, resulting in the grammar for the 6 transition states to resemble that of many popular programming languages.

The transition table defined in this program can be further fine tuned by allowing the states to accept or reject different parameters, and/or by adding more transition states. Tuning the parameters in the state transition table allows you to change the behavior of the state machine without having the need to alter the Finite State Machine Algorithm (the “Lexer” function) much at all.

NOTE: The example on this page uses a sample input file. Click here to download the file.

``` Simple Lexer Using A Finite State Machine C++ // ============================================================================ // Author: K Perkins // Taken From: http://programmingnotes.org/ // Date: Jan 29, 2014 // File: FSM.cpp // Description: The following demonstrates the implementation of a simple // Lexer using a table driven Finite State Machine. // ============================================================================ #include <iostream> #include <cstdlib> #include <cctype> #include <string> #include <vector> #include <fstream> using namespace std; /* This holds the transition states for our Finite State Machine -- They are placed in numerical order for easy understanding within the FSM array, which is located below */ enum FSM_TRANSITIONS { REJECT = 0, INTEGER, REAL, OPERATOR, STRING, UNKNOWN, SPACE }; /* This is the Finite State Machine Table -- The zero represents a place holder, so the row in the array starts on row 1 instead of 0. -- You can tune this table to make the states accept or reject different parameters, thus changing its behavior. More states can be added to this table. integer, real, operator, string, unknown, space */ int stateTable[][7] = {{0, INTEGER, REAL, OPERATOR, STRING, UNKNOWN, SPACE}, /* STATE 1 */ {INTEGER, INTEGER, REAL, REJECT, REJECT, REJECT, REJECT}, /* STATE 2 */ {REAL, REAL, UNKNOWN, REJECT, REJECT, REJECT, REJECT}, /* STATE 3 */ {OPERATOR, REJECT, REJECT, REJECT, STRING, REJECT, REJECT}, /* STATE 4 */ {STRING, STRING, REJECT, STRING, STRING, REJECT, REJECT}, /* STATE 5 */ {UNKNOWN, UNKNOWN, UNKNOWN, UNKNOWN, UNKNOWN, UNKNOWN, REJECT}, /* STATE 6 */ {SPACE, REJECT, REJECT, REJECT, REJECT, REJECT, REJECT}}; // struct to hold token information struct TokenType { string token; int lexeme; string lexemeName; }; // function prototypes vector<TokenType> Lexer(string expression); int Get_FSM_Col(char currentChar); string GetLexemeName(int lexeme); int main() { // declare variables ifstream infile; string fileName = ""; string expression = ""; vector<TokenType> tokens; // get data from user cout<<"nPlease enter the name of the file: "; getline(cin, fileName); infile.open(fileName.c_str()); if(infile.fail()) { cout<<"n** ERROR - the file ""<<fileName<<"" cannot be found!nn"; exit(1); } // use a loop to scan each line in the file while(getline(infile, expression)) { // use the "Lexer" function to isolate integer, real, operator, // string, and unknown tokens tokens = Lexer(expression); // display the tokens to the screen for(unsigned x = 0; x < tokens.size(); ++x) { cout<<tokens[x].lexemeName<<" t" <<tokens[x].token<<endl; } } infile.close(); return 0; }// end of main /** * FUNCTION: Lexer * USE: Parses the "expression" string using the Finite State Machine to * isolate each individual token and lexeme name in the expression. * @param expression - A std::string containing text. * @return - Returns a vector containing the tokens found in the string */ vector<TokenType> Lexer(string expression) { TokenType access; vector<TokenType> tokens; char currentChar = ' '; int col = REJECT; int currentState = REJECT; int prevState = REJECT; string currentToken = ""; // use an FSM to parse the expression for(unsigned x = 0; x < expression.length();) { currentChar = expression[x]; // get the column number for the current character col = Get_FSM_Col(currentChar); /* ======================================================== THIS IS WHERE WE CHECK THE FINITE STATE MACHINE TABLE USING THE "col" VARIABLE FROM ABOVE ^ ========================================================= */ // get the current state of the expression currentState = stateTable[currentState][col]; /* =================================================== THIS IS WHERE WE CHECK FOR A SUCESSFUL PARSE - If the current state of the expression == REJECT (the starting state), then we have sucessfully parsed a token. - ELSE we continue trying to find a sucessful token =================================================== */ if(currentState == REJECT) { if(prevState != SPACE) // we dont care about whitespace { access.token = currentToken; access.lexeme = prevState; access.lexemeName = GetLexemeName(access.lexeme); tokens.push_back(access); } currentToken = ""; } else { currentToken += currentChar; ++x; } prevState = currentState; } // this ensures the last token gets saved when // we reach the end of the loop (if a valid token exists) if(currentState != SPACE && currentToken != "") {// ^^ we dont care about whitespace access.token = currentToken; access.lexeme = currentState; access.lexemeName = GetLexemeName(access.lexeme); tokens.push_back(access); } return tokens; }// end of Lexer /** * FUNCTION: Get_FSM_Col * USE: Determines the state of the type of character being examined. * @param currentChar - A character. * @return - Returns the state of the type of character being examined. */ int Get_FSM_Col(char currentChar) { // check for whitespace if(isspace(currentChar)) { return SPACE; } // check for integer numbers else if(isdigit(currentChar)) { return INTEGER; } // check for real numbers else if(currentChar == '.') { return REAL; } // check for characters else if(isalpha(currentChar)) { return STRING; } // check for operators else if(ispunct(currentChar)) { return OPERATOR; } return UNKNOWN; }// end of Get_FSM_Col /** * FUNCTION: GetLexemeName * USE: Returns the string equivalent of an integer lexeme token type. * @param lexeme - An integer lexeme token type. * @return - An std::string string representing the name of the integer * lexeme token type. */ string GetLexemeName(int lexeme) { switch(lexeme) { case INTEGER: return "INTEGER"; break; case REAL: return "REAL "; break; case OPERATOR: return "OPERATOR"; break; case STRING: return "STRING"; break; case UNKNOWN: return "UNKNOWN"; break; case SPACE: return "SPACE"; break; default: return "ERROR"; break; } }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251 // ============================================================================//   Author:  K Perkins//   Taken From: http://programmingnotes.org///   Date:  Jan 29, 2014//   File: FSM.cpp//   Description: The following demonstrates the implementation of a simple//     Lexer using a table driven Finite State Machine.// ============================================================================#include <iostream>#include <cstdlib>#include <cctype>#include <string>#include <vector>#include <fstream>using namespace std; /* This holds the transition states for our Finite State Machine    -- They are placed in numerical order for easy understanding within     the FSM array, which is located below */ enum FSM_TRANSITIONS{    REJECT = 0,    INTEGER,    REAL,    OPERATOR,    STRING,    UNKNOWN,    SPACE}; /* This is the Finite State Machine Table    -- The zero represents a place holder, so the row in the array starts on   row 1 instead of 0.     -- You can tune this table to make the states accept or reject different   parameters, thus changing its behavior. More states can be added to   this table.                           integer,  real,  operator,  string,  unknown,  space */int stateTable[][7] = {{0, INTEGER,  REAL,  OPERATOR,  STRING, UNKNOWN,  SPACE},/* STATE 1 */   {INTEGER,  INTEGER,  REAL,   REJECT,   REJECT,  REJECT,  REJECT},/* STATE 2 */   {REAL,       REAL,  UNKNOWN, REJECT,   REJECT,  REJECT,  REJECT},/* STATE 3 */   {OPERATOR,  REJECT, REJECT,  REJECT,   STRING,  REJECT,  REJECT},/* STATE 4 */   {STRING,    STRING, REJECT,  STRING,   STRING,  REJECT,  REJECT},/* STATE 5 */   {UNKNOWN,  UNKNOWN, UNKNOWN, UNKNOWN,  UNKNOWN, UNKNOWN, REJECT},/* STATE 6 */   {SPACE,     REJECT, REJECT,  REJECT,   REJECT,  REJECT,  REJECT}};  // struct to hold token informationstruct TokenType{    string token;    int lexeme;    string lexemeName;}; // function prototypesvector<TokenType> Lexer(string expression);int Get_FSM_Col(char currentChar);string GetLexemeName(int lexeme); int main(){    // declare variables    ifstream infile;    string fileName = "";    string expression = "";    vector<TokenType> tokens;     // get data from user    cout<<"nPlease enter the name of the file: ";    getline(cin, fileName);     infile.open(fileName.c_str());     if(infile.fail())    {        cout<<"n** ERROR - the file ""<<fileName<<"" cannot be found!nn";        exit(1);    }     // use a loop to scan each line in the file    while(getline(infile, expression))    {        // use the "Lexer" function to isolate integer, real, operator,        // string, and unknown tokens        tokens = Lexer(expression);         // display the tokens to the screen        for(unsigned x = 0; x < tokens.size(); ++x)        {            cout<<tokens[x].lexemeName<<"  t"                <<tokens[x].token<<endl;        }    }     infile.close();     return 0;}// end of main /*** FUNCTION: Lexer* USE: Parses the "expression" string using the Finite State Machine to*     isolate each individual token and lexeme name in the expression.* @param expression - A std::string containing text.* @return - Returns a vector containing the tokens found in the string*/vector<TokenType> Lexer(string expression){    TokenType access;    vector<TokenType> tokens;    char currentChar = ' ';    int col = REJECT;    int currentState = REJECT;    int prevState = REJECT;    string currentToken = "";     // use an FSM to parse the expression    for(unsigned x = 0; x < expression.length();)    {        currentChar = expression[x];         // get the column number for the current character        col = Get_FSM_Col(currentChar);         /* ========================================================             THIS IS WHERE WE CHECK THE FINITE STATE MACHINE TABLE               USING THE "col" VARIABLE FROM ABOVE ^           ========================================================= */         // get the current state of the expression        currentState = stateTable[currentState][col];         /* ===================================================           THIS IS WHERE WE CHECK FOR A SUCESSFUL PARSE           - If the current state of the expression == REJECT             (the starting state), then we have sucessfully parsed             a token.             - ELSE we continue trying to find a sucessful token             =================================================== */        if(currentState == REJECT)        {            if(prevState != SPACE) // we dont care about whitespace            {                access.token = currentToken;                access.lexeme = prevState;                access.lexemeName = GetLexemeName(access.lexeme);                tokens.push_back(access);            }            currentToken = "";        }        else        {            currentToken += currentChar;            ++x;        }        prevState = currentState;     }    // this ensures the last token gets saved when    // we reach the end of the loop (if a valid token exists)    if(currentState != SPACE && currentToken != "")    {// ^^ we dont care about whitespace        access.token = currentToken;        access.lexeme = currentState;        access.lexemeName = GetLexemeName(access.lexeme);        tokens.push_back(access);    }    return tokens;}// end of Lexer /*** FUNCTION: Get_FSM_Col* USE: Determines the state of the type of character being examined.* @param currentChar - A character.* @return - Returns the state of the type of character being examined.*/int Get_FSM_Col(char currentChar){    // check for whitespace    if(isspace(currentChar))    {        return SPACE;    }     // check for integer numbers    else if(isdigit(currentChar))    {        return INTEGER;    }     // check for real numbers    else if(currentChar == '.')    {        return REAL;    }     // check for characters    else if(isalpha(currentChar))    {        return STRING;    }     // check for operators    else if(ispunct(currentChar))    {        return OPERATOR;    }    return UNKNOWN;}// end of Get_FSM_Col /*** FUNCTION: GetLexemeName* USE: Returns the string equivalent of an integer lexeme token type.* @param lexeme - An integer lexeme token type.* @return - An std::string string representing the name of the integer*        lexeme token type.*/string GetLexemeName(int lexeme){    switch(lexeme)    {        case INTEGER:           return "INTEGER";           break;        case REAL:           return "REAL  ";           break;        case OPERATOR:           return "OPERATOR";           break;        case STRING:           return "STRING";           break;        case UNKNOWN:           return "UNKNOWN";           break;        case SPACE:           return "SPACE";           break;        default:           return "ERROR";           break;    }}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

NOTE: The example on this page uses a sample input file. Click here to download the file.

The following is sample output.

``` Please enter the name of the file: FiniteStateMachine_programmingnotes_freeweq_com.txt STRING Rat12F STRING Function STRING function STRING Identifier OPERATOR ( OPERATOR ) OPERATOR : OPERATOR : OPERATOR ; OPERATOR , OPERATOR { OPERATOR } OPERATOR = OPERATOR [ OPERATOR ] STRING int STRING boolean STRING real STRING If STRING if STRING else STRING fi STRING while STRING Return STRING return OPERATOR ; STRING printf STRING scanf OPERATOR ( STRING IDs OPERATOR ) OPERATOR ; OPERATOR = OPERATOR = OPERATOR ! OPERATOR = OPERATOR > OPERATOR > OPERATOR < OPERATOR = OPERATOR > OPERATOR < OPERATOR = OPERATOR + OPERATOR - OPERATOR * OPERATOR / OPERATOR / OPERATOR - STRING true STRING false INTEGER 123 INTEGER 0000 REAL 13.456 REAL .567 UNKNOWN 12.45.67. STRING a_c__4t STRING a____t STRING x STRING x56 STRING _fgt OPERATOR % OPERATOR & OPERATOR / OPERATOR * STRING Middle OPERATOR * OPERATOR / OPERATOR / OPERATOR * STRING end OPERATOR * OPERATOR / INTEGER 67 STRING yu 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 Please enter the name of the file: FiniteStateMachine_programmingnotes_freeweq_com.txt STRING   Rat12FSTRING   FunctionSTRING   functionSTRING   IdentifierOPERATOR   (OPERATOR   )OPERATOR   :OPERATOR   :OPERATOR   ;OPERATOR   ,OPERATOR   {OPERATOR   }OPERATOR   =OPERATOR   [OPERATOR   ]STRING   intSTRING   booleanSTRING   realSTRING   IfSTRING   ifSTRING   elseSTRING   fiSTRING   whileSTRING   ReturnSTRING   returnOPERATOR   ;STRING   printfSTRING   scanfOPERATOR   (STRING   IDsOPERATOR   )OPERATOR   ;OPERATOR   =OPERATOR   =OPERATOR   !OPERATOR   =OPERATOR   >OPERATOR   >OPERATOR   <OPERATOR   =OPERATOR   >OPERATOR   <OPERATOR   =OPERATOR   +OPERATOR   -OPERATOR   *OPERATOR   /OPERATOR   /OPERATOR   -STRING   trueSTRING   falseINTEGER   123INTEGER   0000REAL     13.456REAL     .567UNKNOWN   12.45.67.STRING   a_c__4tSTRING   a____tSTRING   xSTRING   x56STRING   _fgtOPERATOR   %OPERATOR   &OPERATOR   /OPERATOR   *STRING   MiddleOPERATOR   *OPERATOR   /OPERATOR   /OPERATOR   *STRING   endOPERATOR   *OPERATOR   /INTEGER   67STRING   yu ```

## C++ || Snippet – How To Send Text Over A Network Using A TCP Connection

The following is sample code which demonstrates the use of the “socket“, “connect“, “bind“, “read“, and “write” function calls for interprocess communication over a network on Unix based systems.

The following example demonstrates a simple network application in which a client sends text to a server, and the server replies (sends text) back to the client. This program demonstrates communication between two programs using a TCP connection.

Click here to examine the UDP version.

Note: The server program must be ran before the client program!

=== 1. SERVER ===

``` IPC Networking - TCP Server C++ // ============================================================================ // Author: K Perkins // Date: Jan 8, 2014 // Taken From: http://programmingnotes.org/ // File: ServerTCP.cpp // Description: This program implements a simple network application in // which a client sends text to a server and the server replies back to the // client. This is the server program, and has the following functionality: // 1. Listen for incoming connections on a specified port. // 2. When a client tries to connect, the connection is accepted. // 3. When a connection is created, text is received from the client. // 4. Text is sent back to the client from the server. // 5. Close the connection and go back to waiting for more connections. // ============================================================================ #include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> using namespace std; // Compile & Run // g++ ServerTCP.cpp -o ServerTCP // ./ServerTCP 1234 // the maximum size for sending/receiving text const int MSG_SIZE = 100; int main(int argc, char* argv[]) { // declare variables // the port number int port = -1; // the integer to store the file descriptor number // which will represent a socket on which the server // will be listening int listenfd = -1; // the file descriptor representing the connection to the client int connfd = -1; // the number of bytes read int numRead = -1; // the buffer to store text char data[MSG_SIZE]; // the structures representing the server and client // addresses respectively sockaddr_in serverAddr, cliAddr; // stores the size of the client's address socklen_t cliLen = sizeof(cliAddr); // make sure the user has provided the port number to listen on if(argc < 2) { cerr<<"n** ERROR NOT ENOUGH ARGS!n" <<"USAGE: "<<argv[0]<<" <SERVER PORT #>nn"; exit(1); } // get the port number port = atoi(argv[1]); // make sure that the port is within a valid range if(port < 0 || port > 65535) { cerr<<"Invalid port numbern"; exit(1); } // create a socket that uses // IPV4 addressing scheme (AF_INET), // Supports reliable data transfer (SOCK_STREAM), // and choose the default protocol that provides // reliable service (i.e. 0); usually TCP if((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("socket"); exit(1); } // set the structure to all zeros memset(&serverAddr, 0, sizeof(serverAddr)); // convert the port number to network representation serverAddr.sin_port = htons(port); // set the server family serverAddr.sin_family = AF_INET; // retrieve packets without having to know your IP address, // and retrieve packets from all network interfaces if the // machine has multiple ones serverAddr.sin_addr.s_addr = htonl(INADDR_ANY); // associate the address with the socket if(bind(listenfd, (sockaddr *) &serverAddr, sizeof(serverAddr)) < 0) { perror("bind"); exit(1); } // listen for connections on socket listenfd. // allow no more than 100 pending clients. if(listen(listenfd, 100) < 0) { perror("listen"); exit(1); } cerr<<"nServer started!n"; // wait forever for connections to come while(true) { cerr<<"nWaiting for someone to connect..n"; // a structure to store the client address if((connfd = accept(listenfd, (sockaddr *)&cliAddr, &cliLen)) < 0) { perror("accept"); exit(1); } // receive whatever the client sends if((numRead = read(connfd, data, sizeof(data))) < 0) { perror("read"); exit(1); } // NULL terminate the received string data[numRead] = '\0'; cerr<<"nRECEIVED: ""<<data<<"" from the clientn"; //cerr<<"Bytes read: "<<numRead<<endl; // set the array to all zeros memset(&data, 0, sizeof(data)); // retrieve the time time_t rawtime; time(&rawtime); struct tm* timeinfo; timeinfo = localtime(&rawtime); strftime(data, sizeof(data),"%a, %b %d %Y, %I:%M:%S %p", timeinfo); cerr<<"nSENDING: ""<<data<<"" to the clientn"; // send the client a message if(write(connfd, data, strlen(data)+1) < 0) { perror("write"); exit(1); } // close the socket close(connfd); } return 0; }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169 // ============================================================================//   Author: K Perkins//   Date:  Jan 8, 2014//   Taken From: http://programmingnotes.org///   File: ServerTCP.cpp//   Description: This program implements a simple network application in //     which a client sends text to a server and the server replies back to the//     client. This is the server program, and has the following functionality://       1. Listen for incoming connections on a specified port.//       2. When a client tries to connect, the connection is accepted.//       3. When a connection is created, text is received from the client.//       4. Text is sent back to the client from the server.//       5. Close the connection and go back to waiting for more connections.// ============================================================================#include <iostream>#include <cstdio>#include <cstdlib>#include <cstring>#include <ctime>#include <unistd.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>using namespace std; // Compile & Run// g++ ServerTCP.cpp -o ServerTCP// ./ServerTCP 1234 // the maximum size for sending/receiving textconst int MSG_SIZE = 100; int main(int argc, char* argv[]){    // declare variables         // the port number     int port = -1;     // the integer to store the file descriptor number    // which will represent a socket on which the server    // will be listening    int listenfd = -1;     // the file descriptor representing the connection to the client     int connfd = -1;        // the number of bytes read     int numRead = -1;         // the buffer to store text    char data[MSG_SIZE];     // the structures representing the server and client    // addresses respectively         sockaddr_in serverAddr, cliAddr;     // stores the size of the client's address     socklen_t cliLen = sizeof(cliAddr);      // make sure the user has provided the port number to listen on         if(argc < 2)    {     cerr<<"n** ERROR NOT ENOUGH ARGS!n"         <<"USAGE: "<<argv[0]<<" <SERVER PORT #>nn";     exit(1);     }             // get the port number     port = atoi(argv[1]);     // make sure that the port is within a valid range     if(port < 0 || port > 65535)     {     cerr<<"Invalid port numbern";     exit(1);    }      // create a socket that uses    // IPV4 addressing scheme (AF_INET),    // Supports reliable data transfer (SOCK_STREAM),    // and choose the default protocol that provides    // reliable service (i.e. 0); usually TCP         if((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)    {     perror("socket");     exit(1);    }     // set the structure to all zeros     memset(&serverAddr, 0, sizeof(serverAddr));     // convert the port number to network representation     serverAddr.sin_port = htons(port);     // set the server family     serverAddr.sin_family = AF_INET;     // retrieve packets without having to know your IP address,    // and retrieve packets from all network interfaces if the    // machine has multiple ones         serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);     // associate the address with the socket     if(bind(listenfd, (sockaddr *) &serverAddr, sizeof(serverAddr)) < 0)    {     perror("bind");     exit(1);    }     // listen for connections on socket listenfd.    // allow no more than 100 pending clients.         if(listen(listenfd, 100) < 0)    {     perror("listen");     exit(1);    }        cerr<<"nServer started!n";     // wait forever for connections to come     while(true)    {         cerr<<"nWaiting for someone to connect..n";         // a structure to store the client address         if((connfd = accept(listenfd, (sockaddr *)&cliAddr, &cliLen)) < 0)        {            perror("accept");            exit(1);        }         // receive whatever the client sends        if((numRead = read(connfd, data, sizeof(data))) < 0)        {            perror("read");             exit(1);        }          // NULL terminate the received string        data[numRead] = '\0';          cerr<<"nRECEIVED: ""<<data<<"" from the clientn";        //cerr<<"Bytes read: "<<numRead<<endl;                   // set the array to all zeros         memset(&data, 0, sizeof(data));          // retrieve the time         time_t rawtime;        time(&rawtime);        struct tm* timeinfo;        timeinfo = localtime(&rawtime);                                  strftime(data, sizeof(data),"%a, %b %d %Y, %I:%M:%S %p", timeinfo);                     cerr<<"nSENDING: ""<<data<<"" to the clientn";         // send the client a message        if(write(connfd, data, strlen(data)+1) < 0)        {            perror("write");            exit(1);        }         // close the socket         close(connfd);    }     return 0;}// http://programmingnotes.org/ ```

=== 2. CLIENT ===

``` IPC Networking - TCP Client C++ // ============================================================================ // Author: K Perkins // Date: Jan 8, 2014 // Taken From: http://programmingnotes.org/ // File: ClientTCP.cpp // Description: This program implements a simple network application in // which a client sends text to a server and the server replies back to the // client. This is the client program, and has the following functionality: // 1. Establish a connection to the server. // 2. Send text to the server. // 3. Recieve text from the server. // 4. Close the connection and exit. // ============================================================================ #include <iostream> #include <cstdio> #include <ctime> #include <cstdlib> #include <cstring> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> using namespace std; // Compile & Run // g++ ClientTCP.cpp -o ClientTCP // ./ClientTCP 127.0.0.1 1234 // the maximum size for sending/receiving text const int MSG_SIZE = 100; int main(int argc, char* argv[]) { // declare variables // the port number int port = -1; // the file descriptor representing the connection to the client int connfd = -1; // the buffer to store text char data[MSG_SIZE] = "Server, what time is it?"; // the number of bytes read int numRead = -1; // the structures representing the server address sockaddr_in serverAddr; // stores the size of the client's address socklen_t servLen = sizeof(serverAddr); // make sure the user has provided the port number to listen on if(argc < 3) { cerr<<"n** ERROR NOT ENOUGH ARGS!n" <<"USAGE: "<<argv[0]<<" <SERVER IP> <SERVER PORT #>nn"; exit(1); } // get the port number port = atoi(argv[2]); // make sure that the port is within a valid range if(port < 0 || port > 65535) { cerr<<"Invalid port numbern"; exit(1); } // connect to the server if((connfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("socket"); exit(1); } // set the structure to all zeros memset(&serverAddr, 0, sizeof(serverAddr)); // set the server family serverAddr.sin_family = AF_INET; // convert the port number to network representation serverAddr.sin_port = htons(port); // convert the IP from the presentation format (i.e. string) // to the format in the serverAddr structure. if(!inet_pton(AF_INET, argv[1], &serverAddr.sin_addr)) { perror("inet_pton"); exit(1); } // connect to the server. This call will return a socket used // used for communications between the server and the client. if(connect(connfd, (sockaddr*)&serverAddr, sizeof(sockaddr)) < 0) { perror("connect"); exit(1); } cerr<<"nSENDING: ""<<data<<"" to the servern"; // send the server a message if(write(connfd, data, strlen(data)+1) < 0) { perror("write"); exit(1); } // receive whatever the server sends if((numRead = read(connfd, data, sizeof(data))) < 0) { perror("read"); exit(1); } // NULL terminate the received string data[numRead] = '\0'; cerr<<"nRECEIVED: ""<<data<<"" from the servern"; //cerr<<"Bytes read: "<<numRead<<endl; // close the connection socket close(connfd); return 0; }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130 // ============================================================================//   Author: K Perkins//   Date:  Jan 8, 2014//   Taken From: http://programmingnotes.org///   File: ClientTCP.cpp//   Description: This program implements a simple network application in //     which a client sends text to a server and the server replies back to the//     client. This is the client program, and has the following functionality://       1. Establish a connection to the server.//       2. Send text to the server.//       3. Recieve text from the server.//       4. Close the connection and exit.// ============================================================================#include <iostream>#include <cstdio>#include <ctime>#include <cstdlib>#include <cstring>#include <unistd.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>using namespace std; // Compile & Run// g++ ClientTCP.cpp -o ClientTCP// ./ClientTCP 127.0.0.1 1234 // the maximum size for sending/receiving textconst int MSG_SIZE = 100; int main(int argc, char* argv[]){    // declare variables    // the port number     int port = -1;     // the file descriptor representing the connection to the client     int connfd = -1;     // the buffer to store text    char data[MSG_SIZE] = "Server, what time is it?";     // the number of bytes read     int numRead = -1;     // the structures representing the server address     sockaddr_in serverAddr;     // stores the size of the client's address     socklen_t servLen = sizeof(serverAddr);      // make sure the user has provided the port number to listen on         if(argc < 3)    {     cerr<<"n** ERROR NOT ENOUGH ARGS!n"         <<"USAGE: "<<argv[0]<<" <SERVER IP> <SERVER PORT #>nn";     exit(1);     }     // get the port number     port = atoi(argv[2]);     // make sure that the port is within a valid range     if(port < 0 || port > 65535)     {     cerr<<"Invalid port numbern";     exit(1);    }      // connect to the server     if((connfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)    {     perror("socket");     exit(1);    }     // set the structure to all zeros     memset(&serverAddr, 0, sizeof(serverAddr));     // set the server family     serverAddr.sin_family = AF_INET;     // convert the port number to network representation     serverAddr.sin_port = htons(port);     //  convert the IP from the presentation format (i.e. string)    //  to the format in the serverAddr structure.         if(!inet_pton(AF_INET, argv[1], &serverAddr.sin_addr))    {     perror("inet_pton");     exit(1);    }     // connect to the server. This call will return a socket used     // used for communications between the server and the client.         if(connect(connfd, (sockaddr*)&serverAddr, sizeof(sockaddr)) < 0)    {     perror("connect");     exit(1);    }        cerr<<"nSENDING: ""<<data<<"" to the servern";      // send the server a message     if(write(connfd, data, strlen(data)+1) < 0)    {        perror("write");        exit(1);    }     // receive whatever the server sends     if((numRead = read(connfd, data, sizeof(data))) < 0)    {     perror("read");     exit(1);    }     // NULL terminate the received string     data[numRead] = '\0';     cerr<<"nRECEIVED: ""<<data<<"" from the servern";     //cerr<<"Bytes read: "<<numRead<<endl;     // close the connection socket     close(connfd);     return 0;}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

The following is sample output.

SERVER OUTPUT:

`Server started!`

``` Waiting for someone to connect.. RECEIVED: "Server, what time is it?" from the client ```

```SENDING: "Wed, Jan 08 2014, 07:51:53 PM" to the client ```

CLIENT OUTPUT:

`SENDING: "Server, what time is it?" to the server`

``` ```

```RECEIVED: "Wed, Jan 08 2014, 07:51:53 PM" from the server ```

## C++ || Snippet – How To Send Text Over A Network Using A UDP Connection

The following is sample code which demonstrates the use of the “socket“, “bind“, “recvfrom“, and “sendto” function calls for interprocess communication over a network on Unix based systems.

The following example demonstrates a simple network application in which a client sends text to a server, and the server replies (sends text) back to the client. This program demonstrates communication between two programs using a UDP connection.

Click here to examine the TCP version.

Note: The server program must be ran before the client program!

=== 1. SERVER ===

``` IPC Networking - UDP Server C++ // ============================================================================ // Author: K Perkins // Date: Jan 8, 2014 // Taken From: http://programmingnotes.org/ // File: ServerUDP.cpp // Description: This program implements a simple network application in // which a client sends text to a server and the server replies back to the // client. This is the server program, and has the following functionality: // 1. Listen for incoming connections on a specified port. // 2. When a client connects, text is received from the client. // 3. Text is sent back to the client from the server. // 4. Go back to waiting for more connections. // ============================================================================ #include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <sys/socket.h> #include <netinet/in.h> using namespace std; // Compile & Run // g++ ServerUDP.cpp -o ServerUDP // ./ServerUDP 1234 // the maximum size for sending/receiving text const int MSG_SIZE = 100; int main(int argc, char* argv[]) { // declare variables // to store the port number int port = -1; // to store the socket file descriptor int socketfd = -1; // the address structures for the server and the client sockaddr_in servaddr, cliaddr; // the size of sockaddr_in structure socklen_t sockaddr_in_len = 0; // the number of bytes received and sent int numRead = -1, numSent = -1; // the buffer to store the string to send/receive char data[MSG_SIZE]; // check the command line if(argc < 2) { cerr<<"n** ERROR NOT ENOUGH ARGS!n" <<"USAGE: "<<argv[0]<<" <SERVER PORT #>n"; exit(1); } // convert the port number to an integer port = atoi(argv[1]); // make sure the port range is valid if(port < 0 || port > 65535) { cerr<<"nInvalid port numbern"; exit(1); } // create a UDP socket if((socketfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("socket"); exit(1); } // clear the structure for the server address memset(&servaddr, 0, sizeof(servaddr)); // populate the server address structure servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(port); // bind the socket to the port if(bind(socketfd,(sockaddr *)&servaddr, sizeof(servaddr)) < 0) { perror("bind"); exit(1); } cerr<<"nServer started!n"; // keep receiving forever while(true) { cerr<<"nWaiting for someone to connect..n"; // get the size of the client address data structure sockaddr_in_len = sizeof(cliaddr); // get something from the client; Will block until the client sends. if((numRead = recvfrom(socketfd, data, sizeof(data), 0, (sockaddr *)&cliaddr, &sockaddr_in_len)) < 0) { perror("recvfrom"); exit(1); } cerr<<"nRECEIVED: ""<<data<<"" from the clientn"; //cerr<<"Bytes read: "<<numRead<<endl; // set the array to all zeros memset(&data, 0, sizeof(data)); // retrieve the time time_t rawtime; time(&rawtime); struct tm* timeinfo; timeinfo = localtime(&rawtime); strftime(data, sizeof(data),"%a, %b %d %Y, %I:%M:%S %p", timeinfo); cerr<<"nSENDING: ""<<data<<"" to the clientn"; // send the time to the client if((numSent = sendto(socketfd, data, strlen(data)+1, 0, (sockaddr *)&cliaddr,sizeof(cliaddr))) < 0) { perror("sendto"); exit(1); } } return 0; }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134 // ============================================================================//   Author: K Perkins//   Date:  Jan 8, 2014//   Taken From: http://programmingnotes.org///   File: ServerUDP.cpp//   Description: This program implements a simple network application in //     which a client sends text to a server and the server replies back to the//     client. This is the server program, and has the following functionality://       1. Listen for incoming connections on a specified port.//       2. When a client connects, text is received from the client.//       3. Text is sent back to the client from the server.//       4. Go back to waiting for more connections.// ============================================================================#include <iostream>#include <cstdio>#include <cstdlib>#include <cstring>#include <ctime>#include <sys/socket.h>#include <netinet/in.h>using namespace std; // Compile & Run// g++ ServerUDP.cpp -o ServerUDP// ./ServerUDP 1234 // the maximum size for sending/receiving textconst int MSG_SIZE = 100; int main(int argc, char* argv[]){    // declare variables    // to store the port number    int port = -1;     // to store the socket file descriptor    int socketfd = -1;     // the address structures for the server and the client    sockaddr_in servaddr, cliaddr;     // the size of sockaddr_in structure    socklen_t sockaddr_in_len = 0;     // the number of bytes received and sent    int numRead = -1, numSent = -1;     // the buffer to store the string to send/receive    char data[MSG_SIZE];     // check the command line    if(argc < 2)    {     cerr<<"n** ERROR NOT ENOUGH ARGS!n"         <<"USAGE: "<<argv[0]<<" <SERVER PORT #>n";     exit(1);    }     // convert the port number to an integer    port = atoi(argv[1]);     // make sure the port range is valid    if(port < 0 || port > 65535)     {     cerr<<"nInvalid port numbern";     exit(1);    }     // create a UDP socket    if((socketfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)    {     perror("socket");     exit(1);    }     // clear the structure for the server address    memset(&servaddr, 0, sizeof(servaddr));     // populate the server address structure    servaddr.sin_family = AF_INET;    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);    servaddr.sin_port = htons(port);     // bind the socket to the port    if(bind(socketfd,(sockaddr *)&servaddr, sizeof(servaddr)) < 0)    {     perror("bind");     exit(1);    }     cerr<<"nServer started!n";        // keep receiving forever    while(true)    {        cerr<<"nWaiting for someone to connect..n";                    // get the size of the client address data structure        sockaddr_in_len = sizeof(cliaddr);          // get something from the client; Will block until the client sends.         if((numRead = recvfrom(socketfd, data, sizeof(data), 0,             (sockaddr *)&cliaddr, &sockaddr_in_len)) < 0)        {            perror("recvfrom");            exit(1);        }          cerr<<"nRECEIVED: ""<<data<<"" from the clientn";        //cerr<<"Bytes read: "<<numRead<<endl;                   // set the array to all zeros         memset(&data, 0, sizeof(data));          // retrieve the time         time_t rawtime;        time(&rawtime);        struct tm* timeinfo;        timeinfo = localtime(&rawtime);                                  strftime(data, sizeof(data),"%a, %b %d %Y, %I:%M:%S %p", timeinfo);                        cerr<<"nSENDING: ""<<data<<"" to the clientn";          // send the time to the client        if((numSent = sendto(socketfd, data, strlen(data)+1, 0,            (sockaddr *)&cliaddr,sizeof(cliaddr))) < 0)        {            perror("sendto");            exit(1);        }    }     return 0;}// http://programmingnotes.org/ ```

=== 2. CLIENT ===

``` IPC Networking - UDP Client C++ // ============================================================================ // Author: K Perkins // Date: Jan 8, 2014 // Taken From: http://programmingnotes.org/ // File: ClientUDP.cpp // Description: This program implements a simple network application in // which a client sends text to a server and the server replies back to the // client. This is the client program, and has the following functionality: // 1. Send text to the server on a specified port. // 2. Recieve text from the server and exit. // ============================================================================ #include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> using namespace std; // Compile & Run // g++ ClientUDP.cpp -o ClientUDP // ./ClientUDP 127.0.0.1 1234 // the maximum size for sending/receiving text const int MSG_SIZE = 100; int main(int argc, char* argv[]) { // declare variables // to store the port number int port = -1; // to store the socket file descriptor int socketfd = -1; // the address structures for the server and the client sockaddr_in servaddr, cliaddr; // the size of sockaddr_in structure socklen_t sockaddr_in_len = 0; // the number of bytes received and sent int numRead = -1, numSent = -1; // the buffer to store the string to send/receive char data[MSG_SIZE] = "Server, what time is it?"; // check the command line if(argc < 3) { cerr<<"n** ERROR NOT ENOUGH ARGS!n" <<"USAGE: "<<argv[0]<<" <SERVER IP> <SERVER PORT #>n"; exit(1); } // convert the port number to an integer port = atoi(argv[2]); // make sure the port range is valid if(port < 0 || port > 65535) { cerr<<"nInvalid port numbern"; exit(1); } // create a UDP socket if((socketfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("socket"); exit(1); } // clear the structure for the server address memset(&servaddr, 0, sizeof(servaddr)); // populate the server address structure servaddr.sin_family = AF_INET; // initialize the IP address of the server if(!inet_pton(AF_INET, argv[1], &servaddr.sin_addr.s_addr)) { perror("inet_pton"); exit(1); } // set the port servaddr.sin_port = htons(port); // get the size of the client address data structure sockaddr_in_len = sizeof(cliaddr); cerr<<"nSENDING: ""<<data<<"" to the servern"; // send the time to the client if((numSent = sendto(socketfd, data, strlen(data)+1, 0, (sockaddr *)&servaddr, sizeof(servaddr))) < 0) { perror("sendto"); exit(1); } // get something from the client; Will block until the client sends. if((numRead = recvfrom(socketfd, data, sizeof(data), 0, (sockaddr *)&cliaddr, &sockaddr_in_len)) < 0) { perror("recvfrom"); exit(1); } // NULL terminate the received string data[numRead] = '�'; cerr<<"nRECEIVED: ""<<data<<"" from the servern"; //cerr<<"Bytes read: "<<numRead<<endl; return 0; }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 // ============================================================================//   Author:  K Perkins//   Date:  Jan 8, 2014//   Taken From: http://programmingnotes.org///   File: ClientUDP.cpp//   Description: This program implements a simple network application in //     which a client sends text to a server and the server replies back to the//     client. This is the client program, and has the following functionality://       1. Send text to the server on a specified port.//       2. Recieve text from the server and exit.// ============================================================================#include <iostream>#include <cstdio>#include <cstdlib>#include <cstring>#include <ctime>#include <unistd.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>using namespace std; // Compile & Run// g++ ClientUDP.cpp -o ClientUDP// ./ClientUDP 127.0.0.1 1234 // the maximum size for sending/receiving textconst int MSG_SIZE = 100; int main(int argc, char* argv[]){    // declare variables    // to store the port number    int port = -1;     // to store the socket file descriptor    int socketfd = -1;     // the address structures for the server and the client    sockaddr_in servaddr, cliaddr;     // the size of sockaddr_in structure    socklen_t sockaddr_in_len = 0;     // the number of bytes received and sent    int numRead = -1, numSent = -1;     // the buffer to store the string to send/receive    char data[MSG_SIZE] = "Server, what time is it?";     // check the command line    if(argc < 3)    {     cerr<<"n** ERROR NOT ENOUGH ARGS!n"         <<"USAGE: "<<argv[0]<<" <SERVER IP> <SERVER PORT #>n";     exit(1);    }     // convert the port number to an integer    port = atoi(argv[2]);     // make sure the port range is valid    if(port < 0 || port > 65535)     {     cerr<<"nInvalid port numbern";     exit(1);    }     // create a UDP socket    if((socketfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)    {     perror("socket");     exit(1);    }     // clear the structure for the server address    memset(&servaddr, 0, sizeof(servaddr));     // populate the server address structure    servaddr.sin_family = AF_INET;     // initialize the IP address of the server    if(!inet_pton(AF_INET, argv[1], &servaddr.sin_addr.s_addr))    {     perror("inet_pton");     exit(1);    }     // set the port    servaddr.sin_port = htons(port);     // get the size of the client address data structure    sockaddr_in_len = sizeof(cliaddr);        cerr<<"nSENDING: ""<<data<<"" to the servern";     // send the time to the client    if((numSent = sendto(socketfd, data, strlen(data)+1, 0,     (sockaddr *)&servaddr, sizeof(servaddr))) < 0)    {     perror("sendto");     exit(1);    }     // get something from the client; Will block until the client sends.     if((numRead = recvfrom(socketfd, data, sizeof(data), 0,     (sockaddr *)&cliaddr, &sockaddr_in_len)) < 0)    {     perror("recvfrom");     exit(1);    }     // NULL terminate the received string     data[numRead] = '';     cerr<<"nRECEIVED: ""<<data<<"" from the servern";     //cerr<<"Bytes read: "<<numRead<<endl;     return 0;}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

The following is sample output.

SERVER OUTPUT:

`Server started!`

``` Waiting for someone to connect.. RECEIVED: "Server, what time is it?" from the client ```

```SENDING: "Wed, Jan 08 2014, 11:47:12 PM" to the client ```

CLIENT OUTPUT:

`SENDING: "Server, what time is it?" to the server`

``` ```

```RECEIVED: "Wed, Jan 08 2014, 11:47:12 PM" from the server ```

## Java || Snippet – How To Send Text Over A Network Using Socket

The following is sample code which demonstrates the use of the “socket” function call for interprocess communication over a network.

The following example demonstrates a simple network application in which a client sends text to a server, and the server replies (sends text) back to the client.

Note: The server program must be ran before the client program!

=== 1. SERVER ===

``` IPC Networking - Server Java // ============================================================================ // Author: K Perkins // Date: Jan 8, 2014 // Taken From: http://programmingnotes.org/ // File: Server.java // Description: This program implements a simple network application in // which a client sends text to a server and the server replies back to the // client. This is the server program, and has the following functionality: // 1. Listen for incoming connections on a specified port. // 2. When a client tries to connect, the connection is accepted. // 3. When a connection is created, text is received from the client. // 4. Text is sent back to the client from the server. // 5. Close the connection and go back to waiting for more connections. // ============================================================================ import java.io.*; import java.net.*; import java.util.Date; // Compile & Run // javac Server.java // java Server 1234 class Server { // the port on which to listen protected int listenPort; // the initialization constructor public Server(int port) { // save the listening port listenPort = port; }// end of Server // executes the main server loop public void mainServerLoop() throws Exception { // create a listening socket in the specified port. ServerSocket listenSock = new ServerSocket(this.listenPort); // keep servicing the clients while(true) { System.out.println("nWaiting for someone to connect.."); // accept the incoming connection from the client Socket communicationSocket = listenSock.accept(); // the client-to-server stream BufferedReader inFromClient = new BufferedReader(new InputStreamReader( communicationSocket.getInputStream())); // the server-to-client stream DataOutputStream outToClient = new DataOutputStream(communicationSocket.getOutputStream()); // display misc. IPC information System.out.println("n(SRCIP=" + communicationSocket.getInetAddress()+ ", SRCPORT="+communicationSocket.getPort() + ") "+"(DESTIP="+ communicationSocket.getLocalAddress()+", DESTPORT="+ communicationSocket.getLocalPort()+")"); // receive a string from the client String clientMsg = inFromClient.readLine(); System.out.println("nRECEIVED: ""+clientMsg+"" from the client"); // instantiate a date class: used for obtaining the current time Date date = new Date(); // send the current time and date to the client System.out.println("nSENDING: ""+date.toString()+"" to the client"); outToClient.writeBytes(date.toString()); // close the connection to the client communicationSocket.close(); } }// end of mainServerLoop public static void main(String[] args) { // make sure the port number is provided if(args.length != 1) { System.out.println("USAGE: java Server <SERVER PORT #>"); } else { // create an instance of the server class Server server = new Server(Integer.parseInt(args[0])); try { // start receiving client connections System.out.println("nServer started!"); server.mainServerLoop(); } catch(Exception e) { e.printStackTrace(); } } }// end of main }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 // ============================================================================//   Author: K Perkins//   Date:  Jan 8, 2014//   Taken From: http://programmingnotes.org///   File: Server.java//   Description: This program implements a simple network application in //     which a client sends text to a server and the server replies back to the//     client. This is the server program, and has the following functionality://       1. Listen for incoming connections on a specified port.//       2. When a client tries to connect, the connection is accepted.//       3. When a connection is created, text is received from the client.//       4. Text is sent back to the client from the server.//       5. Close the connection and go back to waiting for more connections.// ============================================================================import java.io.*;import java.net.*;import java.util.Date; // Compile & Run// javac Server.java// java Server 1234 class Server{    // the port on which to listen     protected int listenPort;     // the initialization constructor     public Server(int port)    {     // save the listening port     listenPort = port;    }// end of Server     // executes the main server loop     public void mainServerLoop() throws Exception    {     // create a listening socket in the specified port.          ServerSocket listenSock = new ServerSocket(this.listenPort);      // keep servicing the clients     while(true)     {     System.out.println("nWaiting for someone to connect..");          // accept the incoming connection from the client     Socket communicationSocket = listenSock.accept();      // the client-to-server stream     BufferedReader inFromClient =     new BufferedReader(new InputStreamReader(     communicationSocket.getInputStream()));      // the server-to-client stream     DataOutputStream outToClient =     new DataOutputStream(communicationSocket.getOutputStream());      // display misc. IPC information     System.out.println("n(SRCIP=" + communicationSocket.getInetAddress()+     ", SRCPORT="+communicationSocket.getPort() + ") "+"(DESTIP="+     communicationSocket.getLocalAddress()+", DESTPORT="+                 communicationSocket.getLocalPort()+")");                     // receive a string from the client     String clientMsg = inFromClient.readLine();     System.out.println("nRECEIVED: ""+clientMsg+"" from the client");     // instantiate a date class: used for obtaining the current time     Date date = new Date();      // send the current time and date to the client     System.out.println("nSENDING: ""+date.toString()+"" to the client");     outToClient.writeBytes(date.toString());      // close the connection to the client     communicationSocket.close();     }     }// end of mainServerLoop      public static void main(String[] args)    {     // make sure the port number is provided     if(args.length != 1)     {     System.out.println("USAGE: java Server <SERVER PORT #>");     }     else     {     // create an instance of the server class     Server server = new Server(Integer.parseInt(args[0]));     try     {     // start receiving client connections     System.out.println("nServer started!");     server.mainServerLoop();     }     catch(Exception e) { e.printStackTrace(); }     }    }// end of main}// http://programmingnotes.org/ ```

=== 2. CLIENT ===

``` IPC Networking - Client Java // ============================================================================ // Author: K Perkins // Date: Jan 8, 2014 // Taken From: http://programmingnotes.org/ // File: Client.java // Description: This program implements a simple network application in // which a client sends text to a server and the server replies back to the // client. This is the client program, and has the following functionality: // 1. Establish a connection to the server. // 2. Send text to the server. // 3. Recieve text from the server. // 4. Close the connection and exit. // ============================================================================ import java.io.*; import java.net.*; // Compile & Run // javac Client.java // java Client localhost 1234 class Client { // the server IP address protected String svrIpAddr; // the server port number protected int svrPort; /* the initialization constructor * @param ipAddr - the IP address of the server * @param port - the port on which the server is listening */ public Client(String ipAddr, int port) { // save the server's IP address and port number svrIpAddr = ipAddr; svrPort = port; }// end of Client // connects to the server public void connectToServer() throws Exception { // the message to send to the server String msgForServer = "Server, what time is it?"; // the string to store the date and time to be received from the server String dateAndTime = null; // create a socket and use it for connecting to the server Socket clientSocket = new Socket(svrIpAddr, svrPort); // the client-to-server stream DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); // the server-to-client stream BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); // write the string to the server System.out.println("nSENDING: ""+msgForServer+"" to the servern"); outToServer.writeBytes(msgForServer+"n"); // get the date and time from the server dateAndTime = inFromServer.readLine(); // print the date and time received from the server System.out.println("RECEIVED: ""+dateAndTime+"" from the servern"); // close the socket clientSocket.close(); }// end of connectToServer public static void main(String args[]) { // check the command line arguments if(args.length < 2) { System.err.println("n** ERROR NOT ENOUGH ARGS!n" +"USAGE: Client <SERVER IP> <SERVER PORT #>n"); } else { // instantiate the client class Client client = new Client(args[0], Integer.parseInt(args[1])); try { // connect to the server client.connectToServer(); } catch(Exception e) { e.printStackTrace(); } } }// end of main }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 // ============================================================================//   Author: K Perkins//   Date:  Jan 8, 2014//   Taken From: http://programmingnotes.org///   File: Client.java//   Description: This program implements a simple network application in //     which a client sends text to a server and the server replies back to the//     client. This is the client program, and has the following functionality://       1. Establish a connection to the server.//       2. Send text to the server.//       3. Recieve text from the server.//       4. Close the connection and exit.// ============================================================================import java.io.*;import java.net.*; // Compile & Run// javac Client.java// java Client localhost 1234 class Client{ // the server IP address   protected String svrIpAddr; // the server port number   protected int svrPort; /* the initialization constructor * @param ipAddr - the IP address of the server * @param port - the port on which the server is listening */ public Client(String ipAddr, int port) { // save the server's IP address and port number   svrIpAddr = ipAddr; svrPort = port; }// end of Client // connects to the server    public void connectToServer() throws Exception { // the message to send to the server   String msgForServer = "Server, what time is it?"; // the string to store the date and time to be received from the server   String dateAndTime = null; // create a socket and use it for connecting to the server      Socket clientSocket = new Socket(svrIpAddr, svrPort); // the client-to-server stream   DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());  // the server-to-client stream   BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); // write the string to the server System.out.println("nSENDING: ""+msgForServer+"" to the servern"); outToServer.writeBytes(msgForServer+"n"); // get the date and time from the server     dateAndTime = inFromServer.readLine(); // print the date and time received from the server   System.out.println("RECEIVED: ""+dateAndTime+"" from the servern"); // close the socket   clientSocket.close(); }// end of connectToServer public static void main(String args[]) { // check the command line arguments   if(args.length < 2) { System.err.println("n** ERROR NOT ENOUGH ARGS!n"     +"USAGE: Client <SERVER IP> <SERVER PORT #>n"); } else { // instantiate the client class   Client client = new Client(args[0], Integer.parseInt(args[1])); try { // connect to the server   client.connectToServer(); } catch(Exception e) { e.printStackTrace(); } } }// end of main}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

The following is sample output.

SERVER OUTPUT:

`Server started!`

``` Waiting for someone to connect.. (SRCIP=/127.0.0.1, SRCPORT=46608) (DESTIP=/127.0.0.1, DESTPORT=1234) RECEIVED: "Server, what time is it?" from the client ```

```SENDING: "Wed Jan 08 18:07:15 PST 2014" to the client ```

CLIENT OUTPUT:

`SENDING: "Server, what time is it?" to the server`

``` ```

```RECEIVED: "Wed Jan 08 18:07:15 PST 2014" from the server ```

## Python || Snippet – How To Send Text Over A Network Using Socket, Send, & Recv

The following is sample code which demonstrates the use of the “socket“, “connect“, “send“, and “recv” function calls for interprocess communication over a network.

The following example demonstrates a simple network application in which a client sends text to a server, and the server replies (sends text) back to the client.

Note: The server program must be ran before the client program!

=== 1. SERVER ===

``` IPC Networking - Server Python # ============================================================================= # Author: K Perkins # Date: Jan 8, 2014 # Taken From: http://programmingnotes.org/ # File: Server.py # Description: This program implements a simple network application in # which a client sends text to a server and the server replies back to the # client. This is the server program, which has the following functionality: # 1. Listen for incoming connections on a specified port. # 2. When a client tries to connect, the connection is accepted. # 3. When a connection is created, text is received from the client. # 4. Text is sent back to the client from the server. # 5. Close the connection and go back to waiting for more connections. # ============================================================================= import socket, sys, datetime # Run # python3 Server.py 1234 # the client message size MAX_MSG_LEN = 4096 def main(argc, argv): # check the command line arguments if(argc < 2): print("n** ERROR NOT ENOUGH ARGS!n" "USAGE: %s <SERVER PORT #>n" %(argv[0])) sys.exit(1) # get the port number port = int(argv[1]) # the backlog backlog = 100 # create A TCP socket listenSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # bind the socket to the port listenSocket.bind(("", port)) # start listening for incoming connections listenSocket.listen(backlog) print("nServer started!") # service clients forever while(True): print("nWaiting for someone to connect..") # accept a connection from the client client, address = listenSocket.accept() # get the data from the client data = client.recv(MAX_MSG_LEN) print("nRECEIVED: "%s" from the client" %(data.decode("UTF-8"))) # make sure the data was successfully received if(data): # get the current date and time now = datetime.datetime.now() dateAndTime = now.strftime("%a, %b %d %Y, %I:%M:%S %p") # send the date and time to the client print("nSENDING: "%s" to the client" %(dateAndTime)) client.send(dateAndTime.encode("UTF-8")) # close the connection to the client client.close() if __name__ == "__main__": main(len(sys.argv), sys.argv) # http://programmingnotes.org/ 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 # =============================================================================#   Author: K Perkins#   Date:  Jan 8, 2014#   Taken From: http://programmingnotes.org/#   File: Server.py#   Description: This program implements a simple network application in #     which a client sends text to a server and the server replies back to the#     client. This is the server program, which has the following functionality:#       1. Listen for incoming connections on a specified port.#       2. When a client tries to connect, the connection is accepted.#       3. When a connection is created, text is received from the client.#       4. Text is sent back to the client from the server.#       5. Close the connection and go back to waiting for more connections.# =============================================================================import socket, sys, datetime # Run# python3 Server.py 1234 # the client message sizeMAX_MSG_LEN = 4096 def main(argc, argv):    # check the command line arguments    if(argc < 2):        print("n** ERROR NOT ENOUGH ARGS!n"            "USAGE: %s <SERVER PORT #>n" %(argv[0]))        sys.exit(1)     # get the port number     port = int(argv[1])      # the backlog    backlog = 100     # create A TCP socket    listenSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)      # bind the socket to the port     listenSocket.bind(("", port))      # start listening for incoming connections    listenSocket.listen(backlog)        print("nServer started!")     # service clients forever    while(True):     print("nWaiting for someone to connect..")            # accept a connection from the client     client, address = listenSocket.accept()      # get the data from the client     data = client.recv(MAX_MSG_LEN)     print("nRECEIVED: "%s" from the client" %(data.decode("UTF-8")))     # make sure the data was successfully received     if(data):                 # get the current date and time     now = datetime.datetime.now()     dateAndTime = now.strftime("%a, %b %d %Y, %I:%M:%S %p")          # send the date and time to the client          print("nSENDING: "%s" to the client" %(dateAndTime))     client.send(dateAndTime.encode("UTF-8"))            # close the connection to the client     client.close() if __name__ == "__main__":    main(len(sys.argv), sys.argv)# http://programmingnotes.org/ ```

=== 2. CLIENT ===

``` IPC Networking - Client Python # ============================================================================= # Author: K Perkins # Date: Jan 8, 2014 # Taken From: http://programmingnotes.org/ # File: Client.py # Description: This program implements a simple network application in # which a client sends text to a server and the server replies back to the # client. This is the client program, which has the following functionality: # 1. Establish a connection to the server. # 2. Send text to the server. # 3. Recieve text from the server. # 4. Close the connection and exit. # ============================================================================= import socket, sys # Run # python3 Client.py localhost 1234 # the size of the message sent by server MAX_MSG_LEN = 4096 def main(argc, argv): # check the command line arguments if(argc < 3): print("n** ERROR NOT ENOUGH ARGS!n" "USAGE: %s <SERVER IP> <SERVER PORT #>n" %(argv[0])) sys.exit(1) # get the host name (or IP) host = argv[1] # get the server's port number port = int(argv[2]) # the client socket clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # connect to the server clientSocket.connect((host,port)) # send a string to the server data = "Server, what time is it?" print("nSENDING: "%s" to the server" %(data)) clientSocket.send(data.encode("UTF-8")) # get the date from the server data = clientSocket.recv(MAX_MSG_LEN) print("nRECEIVED: "%s" from the servern" %(data.decode("UTF-8"))) # close the connection to the server clientSocket.close() if __name__ == "__main__": main(len(sys.argv), sys.argv) # http://programmingnotes.org/ 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 # =============================================================================#   Author: K Perkins#   Date:  Jan 8, 2014#   Taken From: http://programmingnotes.org/#   File: Client.py#   Description: This program implements a simple network application in #     which a client sends text to a server and the server replies back to the#     client. This is the client program, which has the following functionality:#       1. Establish a connection to the server.#       2. Send text to the server.#       3. Recieve text from the server.#       4. Close the connection and exit.# =============================================================================import socket, sys # Run# python3 Client.py localhost 1234 # the size of the message sent by serverMAX_MSG_LEN = 4096 def main(argc, argv):    # check the command line arguments    if(argc < 3):     print("n** ERROR NOT ENOUGH ARGS!n"         "USAGE: %s <SERVER IP> <SERVER PORT #>n" %(argv[0]))     sys.exit(1)     # get the host name (or IP)    host = argv[1]     # get the server's port number     port = int(argv[2])     # the client socket    clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)      # connect to the server    clientSocket.connect((host,port))      # send a string to the server    data = "Server, what time is it?"    print("nSENDING: "%s" to the server" %(data))    clientSocket.send(data.encode("UTF-8"))     # get the date from the server    data = clientSocket.recv(MAX_MSG_LEN)     print("nRECEIVED: "%s" from the servern" %(data.decode("UTF-8")))     # close the connection to the server    clientSocket.close()  if __name__ == "__main__":    main(len(sys.argv), sys.argv)# http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

The following is sample output.

SERVER OUTPUT:

`Server started!`

``` Waiting for someone to connect.. RECEIVED: "Server, what time is it?" from the client ```

```SENDING: "Wed, Jan 08 2014, 04:02:13 PM" to the client ```

CLIENT OUTPUT:

`SENDING: "Server, what time is it?" to the server`

``` ```

```RECEIVED: "Wed, Jan 08 2014, 04:02:13 PM" from the server ```