Question

Assume I don't understand C++ Can someone explain this program to me Line by Line? Basically...

Assume I don't understand C++ Can someone explain this program to me Line by Line? Basically what each line actually does? whats the function? whats the point? Don't tell me what the program does as a whole, I need to understand what each line does in this program.

#include
#include
#include
#include
#include
#define SERVER_PORT 5432
#define MAX_LINE 256

int main(int argc, char * argv[])
{
   FILE *fp;
   struct hostent *hp;
   struct sockaddr_in sin;
   char *host;
   char buf[MAX_LINE];
   int s;
   int len;
   if (argc==2) {
   host = argv[1];
   }
   else {
       fprintf(stderr, "usage: simplex-talk host\n");
       exit(1);
       }
/* translate host name into peers IP address */
   hp = gethostbyname(host);
   if (!hp) {
       fprintf(stderr, "simplex-talk: unknown host: %s\n", host);
       exit(1);
       }
   /* build address data structure */
   bzero((char *)&sin, sizeof(sin));
   sin.sin_family = AF_INET;
   bcopy(hp->h_addr, (char *)&sin.sin_addr, hp->h_length);
   sin.sin_port = htons(SERVER_PORT);
   /* active open */
   if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
       perror("simplex-talk: socket");
       exit(1);
       }
   if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
       perror("simplex-talk: connect");
       close(s);
       exit(1);
       }
   /* main loop: get and send lines of text */
   while (fgets(buf, sizeof(buf), stdin)) {
   buf[MAX_LINE-1] = \0;
   len = strlen(buf) + 1;
   send(s, buf, len, 0);
   }
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

---->"#include" is pre-processor directive. For example if I write "#include <stdio.h>", it will include system library of standard input and output which contains printf() and scanf() like functions. There are many system libraries that you can include. For example if you "#include<algorithm>" in c++ you can use many complex algorithm just by calling functions from this library. For example you can use sort() function which will sort the array using quick sort (good part is you don't have to implement quick sort by yourself everytime)

----> "#define" is a macro definition. macro definitions allow constant values to be declared for use throughout your code. In our code macro definition is used to define a numeric constant. Macro definition is not variable and cannot be changed by your program code like other variables. You generally use this syntax when creating constants that represent number, string or expression.

---->In c and c++ the "main" function is treated as as the same as every function and it can also accept parameters in some cases. But the major difference is it is called by operating system while we run the program. That is the reason why "main" function is always the first code to run in our program.

----> FILE is a datatype. In our code "fp" means "File Pointer". In C standard library when using the fopen() function to open a file FILE pointer is returned. File is a kind of structure that holds information about file. It is returned as a pointer because a reference to it is needed, as it will get changed by other low level function like fclose().

----> Structure is a user define datatype. It allows us to combine different datatypes together. It is helpful to construct complex datatype which might be useful. As in code we use keyword "struct" to declare structure. "struct hostent *hp", in this hostent is our structure and hp is pointer to structure variable. "struct sockaddr_in sin", sockaddr is our structure ans sin is structure variable.

---->"char *host" , it is a character pointer. we can store the address of character variable in host. "char buf[MAX_LINE]" it will create a character array of size 256 (because as we discuss earlier MAX_LINE is numeric macro definition).

----> "int s" and "int len". We define a integer variable named s and integer variable named len

----> "If" and "else" is used for decision making in our program. It will check condition in if statement if that condition is true then it will execute that line of codes within "if" condition otherwise it will execute line of codes within "else" condition. If the value of argc is 2 then it will execute "host = argv[1]" which will assign argv[1] (second element of array argv) to host else it will execute "fprintf(stderr, "usage: simplex-talk host\n"); exit(1);" fprintf is used to print content of file. exit(0) and exit(1) are the jump statements of C++ that make the control jump out of a program while the program is in execution.The exit (0) shows the successful termination of the program and the exit(1) shows the abnormal termination of the program.

---->" /* translate host name into peers IP address */ " this is comment part in our program. It does not execute while we run the program

---->"hp = gethostbyname(host);" Given the name of a host, gethostbyname returns a pointer to the hostnet structure containing the host's IP address and other information

---->" if (!hp)" if there will be not successful retrieval of host name then it will execute "fprintf(stderr, "simplex-talk: unknown host: %s\n", host); exit(1);"

---->"bzero((char *)&sin, sizeof(sin));" , only zeroes out the sin structure .(bzero is basically memory operator basic syntax "void bzero(void *s, size_t n);" , The bzero() function should  place n zero-valued bytes in the area pointed to by s.)

---->"bcopy" is also a memory operator. (basic syntax "void bcopy(const void *s1, void *s2, size_t n);", The bcopy() function shall copy n bytes from the area pointed to by s1 to the area pointed to by s2 and The bytes are copied correctly even if the area pointed to by s1 overlaps the area pointed to by s2)

---->"sin.sin_port = htons(SERVER_PORT);" simple assignment of sin.sinport to hton(SERVER_PORT). The htons() function converts the unsigned short integer hostshort from host byte order to network byte order.

---->" if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0) " PF_INET refers to anything in the protocol, usually sockets/ports. PF_INET = Packet Format, Internet = IP, TCP/IP or UDP/IP. Passing PF_INET ensures that the connection works right. If Condition true then execute "perror("simplex-talk: socket"); exit(1);" . The perror() function produces a message on standard error describing the last error encounter during a call to system or library function. (basic syntax void perror(const char *str) in which str- This is the C string containing a custom message to be printed before the error message itself.)

---->"while (fgets(buf, sizeof(buf), stdin))", while is looping statement. It repeats the loop as long as statement given inside loop condition is true.

----> fgets() : It reads a line from the specified stream and stores it into the string pointed to by str. It stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first. Basic syntax char *fgets(char *str, int n, FILE *stream) .

It will loop until given condition (in our case fgets(buf, sizeof(buf), stdin)) gets false.

---->"buf[MAX_LINE-1] = \0; len = strlen(buf) + 1;" It will simply assign the value to given variable. ("\0" is null character strlen() is string funtion which will return the length of string ot array)

----> "send(s, buf, len, 0);" The send() function should initiate transmission of a message from the specified socket to its peer. The send() function shall send a message only when the socket is connected. Basic syntax "ssize_t send(int socket, const void *buffer, size_t length, int flags); " Upon successful completion, send() shall return the number of bytes sent. Otherwise, -1 shall be returned and errno set to indicate the error.

Add a comment
Know the answer?
Add Answer to:
Assume I don't understand C++ Can someone explain this program to me Line by Line? Basically...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Run the code in Linux and provide the screenshot of the output and input #include <signal.h>...

    Run the code in Linux and provide the screenshot of the output and input #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> static void cleanup(); static void docleanup(int signum); static const char *SERVER_ADDR = "127.0.0.1"; static const int SERVER_PORT = 61234; static int cfd = -1; int main(int argc, char *argv[]) { struct sockaddr_in saddr; char buf[128]; int bufsize = 128, bytesread; struct sigaction sigact; printf("client starts running ...\n"); atexit(cleanup); sigact.sa_handler =...

  • Modify the client server system program given below so that instead of sendto() and recvfrom(), you...

    Modify the client server system program given below so that instead of sendto() and recvfrom(), you use connect() and un-addresssed write() and read() calls. //Server.c #include #include #include #include #include #include #include #include #include #include # define PortNo 4567 # define BUFFER 1024 int main(int argc, char ** argv) { int ssd; int n; socklen_t len; char msg[BUFFER]; char clientmsg[BUFFER]; struct sockaddr_in server; struct sockaddr_in client; int max_iterations = 0; int count = 0, totalChar = 0, i = 0;...

  • For Unix in a C/C++ environment echoServer and echoClient are provided below In this lab, we will...

    For Unix in a C/C++ environment echoServer and echoClient are provided below In this lab, we will modifiy echoServer.c and echoClient.c programs (for the server's port# not fixed). (1) Modify echoServer.c program to take one argument (a port number) to be used for its listening port when it starts. (2) Modify echoClient.c program to take two arguments (server's IP address and Port number) to be used for its connection. (3) Find a port free for the server using netstat (see...

  • Combine two codes (code 1) to get names with(code 2) to get info: Code 1: #include<unistd.h>...

    Combine two codes (code 1) to get names with(code 2) to get info: Code 1: #include<unistd.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<dirent.h> #include<stdio.h> #include<stdlib.h> void do_ls(char []); int main(int argc,char *argv[]) { if(argc == 1) do_ls("."); else while(--argc){ printf("%s:\n",*++argv); do_ls(*argv); } } void do_ls(char dirname[]) { DIR *dir_ptr; struct dirent *direntp; if((dir_ptr = opendir(dirname)) == NULL) fprintf(stderr,"ls1:cannot open %s\n",dirname); else { while((direntp = readdir(dir_ptr)) != NULL) printf("%s\n",direntp->d_name); closedir(dir_ptr); } } ____________________________ code 2: #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> void show_stat_info(char *,...

  • IN UNIX, MODIFY CODE, PROVIDE SCREENSHOTS FOR GOOD RATING: T1. Modify Client.c program to accept two...

    IN UNIX, MODIFY CODE, PROVIDE SCREENSHOTS FOR GOOD RATING: T1. Modify Client.c program to accept two arguments (IP add & port no. of the concurrent Server with thread - conServThread.c). Similarly, modify the Server (conServThread.c) program to accept an argument which is the port number of the server to bind and listen to. Try these two updated programs (server and client) with a port number (e.g., hhmm6) with current time where hh is hours in 24-hour format and mm is...

  • C Language Programming. Using the program below - When executing on the command line only this...

    C Language Programming. Using the program below - When executing on the command line only this program name, the program will accept keyboard input and display such until the user does control+break to exit the program. The new code should within only this case situation “if (argc == 1){ /* no args; copy standard input */” Replace line #20 “filecopy(stdin, stdout);” with new code. Open read a text file “7NoInputFileResponse.txt” that contains a message “There were no arguments on the...

  • Would u help me fixing this CODE With Debugging Code with GDB #include <stdio.h> #include <stdlib.h>...

    Would u help me fixing this CODE With Debugging Code with GDB #include <stdio.h> #include <stdlib.h> #define SIZE (10) typedef struct _debugLab { int i; char c; } debugLab; // Prototypes void PrintUsage(char *); void DebugOption1(void); void DebugOption2(void); int main(int argc, char **argv) { int option = 0; if (argc == 1) { PrintUsage(argv[0]); exit(0); } option = atoi(argv[1]); if (option == 1) { DebugOption1(); } else if (option == 2) { DebugOption2(); } else { PrintUsage(argv[0]); exit(0); } }...

  • need this in c programming and you can edit the code below. also give me screenshot...

    need this in c programming and you can edit the code below. also give me screenshot of the output #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #define LINE_SIZE 1024 void my_error(char *s) { fprintf(stderr, "Error: %s\n", s); perror("errno"); exit(-1); } // This funciton prints lines (in a file) that contain string s. // assume all lines has at most (LINE_SIZE - 2) ASCII characters. // // Functions that may be called in this function: // fopen(), fclose(), fgets(), fputs(),...

  • C programming help! /* Your challenge is to format the following code in a readable manner, anwsering the questions in...

    C programming help! /* Your challenge is to format the following code in a readable manner, anwsering the questions in the comments. * */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <time.h> #include <sys/socket.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/uio.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <strings.h> #define BUFFERT 512 #define BACKLOG 1 int create_server_socket (int port); struct sockaddr_in sock_serv,sock_clt; int main(int argc, char** argv){ int sfd, fd; unsigned int length = sizeof(struct sockaddr_in); long int n, m, count...

  • In this activity, you will complete the RSS Client that connects to a UNL RSS feed,...

    In this activity, you will complete the RSS Client that connects to a UNL RSS feed, processes the XML data and outputs the results to the standard output. Most of the client has been completed for you. You just Lab Handout: Structures 4 need to complete the design and implementation of a C structure that models the essential parts of an RSS item. Your structure will need to support an RSS item’s title, link, description, and publication date. As a...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT