User Tools

Site Tools


tcp_udp

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
tcp_udp [2017/05/01 23:27] – [Protocol Introductions] dwallacetcp_udp [2017/05/02 22:45] (current) dwallace
Line 10: Line 10:
 {{ dylanw:tcp_vs_udp.jpg?600 }} {{ dylanw:tcp_vs_udp.jpg?600 }}
 \\ \\
-The photo above depicts the differences between TCP & UDP connections which allow you to create different forms of communications. The big picture problem is high-latency or low-bandwidth telerobotics. Solving this partially or completely is important because it will allow remote operation of space robotics, disaster relief, etc. This tutorial shows you how to create a TCP client & server, and a UDP talker & listener, and takes approximately hours to complete. +The photo above depicts the differences between TCP & UDP connections which allow you to create different forms of communications. The big picture problem is high-latency or low-bandwidth telerobotics. Solving this partially or completely is important because it will allow remote operation of space robotics, disaster relief, etc. This tutorial shows you how to create a TCP client & server, and a UDP talker & listener, and takes approximately hours to complete. 
 \\ \\
 ===== Motivation and Audience ===== ===== Motivation and Audience =====
Line 85: Line 85:
 ===== TCP Client & Server ===== ===== TCP Client & Server =====
  
 +In this section we will go over the C code for the TCP client and server. Please note that this code is meant for sockets on Unix systems, and therefore may not work on Windows without some modifications. For these modifications, see [[https://msdn.microsoft.com/en-us/library/windows/desktop/ms740673(v=vs.85).aspx|Winsock documentation]].
 +
 +The complete code for the client and server can be found below:
 +
 +[[https://github.com/D-Wazzle/Simple-C-Communications/tree/master/TCP|TCP Client & Server]]\\ 
 +
 +==== Server ====
 +
 +Let's break down the server code. The server is a program that binds to a certain port, and send a predefined message to any client that connects to it. The first block is where we include all the necessary libraries and define essential constants.
 +
 +<code c>
 +#include <stdio.h>      // Standard Input/Output
 +#include <stdlib.h>     // Standard library
 +#include <unistd.h>     // Unix API
 +#include <errno.h>      // Error library
 +#include <string.h>     // String library
 +#include <sys/types.h>  // Unix System types
 +#include <sys/socket.h> // Unix System sockets
 +#include <netinet/in.h> // Internet library
 +#include <netdb.h>      // Internet database
 +#include <arpa/inet.h>  // Internet library
 +#include <sys/wait.h>   // Wait library
 +#include <signal.h>     // Exception/error handler
 +
 +#define PORT "4800"     // the port users will be connecting to
 +
 +#define BACKLOG 10      // how many pending connections queue will hold
 +</code>
 +
 +Next, we will define a function to read the dead processes from previous programs, in order to free up memory. Don't worry too much about the specifics.
 +
 +<code c>
 +// Function to reap all dead processes
 +void sigchld_handler(int s)
 +{
 +    // waitpid() might overwrite errno, so we save and restore it:
 +    int saved_errno = errno;
 +
 +    while(waitpid(-1, NULL, WNOHANG) > 0);
 +
 +    errno = saved_errno; // Restore errno
 +}
 +</code>
 +
 +Next, we will define a function to get the IP address regardless of IP version.
 +
 +<code c>
 +// Function to get sockaddr, IPv4 or IPv6
 +void *get_in_addr(struct sockaddr *sa)
 +{
 +    if (sa->sa_family == AF_INET) { // If IPv4
 +        return &(((struct sockaddr_in*)sa)->sin_addr); //Return IPv4
 +    }
 +
 +    return &(((struct sockaddr_in6*)sa)->sin6_addr); //Otherwise return IPv6
 +}
 +</code>
 +
 +Now, we will get to the main( ). We will start off with declaring all of our objects, and filling our structs with important info.
 +
 +<code c>
 +    int sockfd, new_fd;  // Listen on sockfd, new connection on new_fd
 +    struct addrinfo hints, *servinfo, *p; //Holds IP address info
 +    struct sockaddr_storage their_addr; // Connector's address information
 +    socklen_t sin_size; // Holds socket size
 +    struct sigaction sa; // Holds data for reaping dead processes
 +    int yes = 1; // Boolean reference
 +    char s[INET6_ADDRSTRLEN]; // Holds the socket IP address in string form
 +    int rv; // Holds error status for getaddrinfo
 +
 +    memset(&hints, 0, sizeof hints); // Fill out empty addrinfo struct
 +    hints.ai_family = AF_UNSPEC; // Set family to either IPv4 or IPv6, we don't care
 +    hints.ai_socktype = SOCK_STREAM; // Set socket type to stream (TCP)
 +    hints.ai_flags = AI_PASSIVE; // Use my IP
 +</code>
 +
 +Then, we will get the necessary info from our struct using getaddrinfo.
 +
 +<code c>
 +    if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) { // If error in getaddrinfo
 +        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); // Print error info
 +        return 1;
 +    }
 +</code>
 +
 +Now that our servinfo struct is filled, we will loop through the linked-list of them until we successfully create and bind to a socket.
 +
 +<code c>
 +    for(p = servinfo; p != NULL; p = p->ai_next) { // Loop through all the results and bind to the first we can
 +        if ((sockfd = socket(p->ai_family, p->ai_socktype,
 +                p->ai_protocol)) == -1) { // If error during sock creation
 +            perror("server: socket"); // Give socket error
 +            continue;
 +        }
 +
 +        if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes,
 +                sizeof(int)) == -1) { // If error in getting the option
 +            perror("setsockopt"); // Give option error
 +            exit(1);
 +        }
 +
 +        if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { // If error during bind
 +            close(sockfd); // Close the socket
 +            perror("server: bind"); // Give bind error
 +            continue;
 +        }
 +
 +        break;
 +    }
 +</code>
 +
 +Now that our server is bound to a port successfully, we will free the addrinfo struct, and check if we properly bound to the port by validating the port and listening in to the port.
 +
 +<code c>
 +    freeaddrinfo(servinfo); // Free up this structure
 +
 +    if (p == NULL)  { // If no port bound to p
 +        fprintf(stderr, "server: failed to bind\n"); // Give failure to bind error
 +        exit(1);
 +    }
 +
 +    if (listen(sockfd, BACKLOG) == -1) { // If listen fails
 +        perror("listen"); // Give listen error
 +        exit(1);
 +    }
 +</code>
 +
 +Now that our server has validated the connection, we will reap all dead processes, and if successful, print that we are now awaiting a connection.
 +
 +<code c>
 +    sa.sa_handler = sigchld_handler; // Reap all dead processes
 +    sigemptyset(&sa.sa_mask); // Clear processes
 +    sa.sa_flags = SA_RESTART;
 +    if (sigaction(SIGCHLD, &sa, NULL) == -1) { // If reap error
 +        perror("sigaction"); // Give sigaction error
 +        exit(1);
 +    }
 +
 +    printf("server: waiting for connections...\n"); // Print waiting statement
 +</code>
 +
 +In order to accept a connection to the server on the defined socket/port, we will put all of the accept/send code within one while loop. This allows the server to be used for multiple different clients. At the beginning of the loop we accept an incoming connection. This accept call waits until a connection has been requested by the client. If the accept succeeds, then we will convert the IP address into a string and print it along with our successful connection message. Finally, we will attempt to send our message, and then close the port.
 +
 +<code c>
 +    while(1) {  // Main accept() loop
 +        sin_size = sizeof their_addr;
 +        new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size); // Accept the connection
 +        if (new_fd == -1) { // If error during accept
 +            perror("accept"); // Give accept error
 +            continue;
 +        }
 +
 +        inet_ntop(their_addr.ss_family,
 +            get_in_addr((struct sockaddr *)&their_addr),
 +            s, sizeof s); // Translate IP address into string form
 +        printf("server: got connection from %s\n", s); // Print client IP address
 +
 +        if (!fork()) { // This is the child process
 +            close(sockfd); // Child doesn't need the listener
 +            if (send(new_fd, "Hello, world!", 13, 0) == -1) // If send error (Note: the message being sent can be changed here)
 +                perror("send"); // Give send error
 +            close(new_fd); // Close the connection
 +            exit(0);
 +        }
 +        close(new_fd);  // Close the connection
 +    }
 +</code>
 +
 +Note, don't forget that all of the code after the first two blocks belongs in main( ), and that we must return 0 at the end of main( ).
 +
 +Here is what it looks like when we launch the server:
 +
 +{{ dylanw:tcp_server_launch.jpg?500 }}
 +\\ 
 +And here is what it looks like when something connects to the server:
 +
 +{{ dylanw:tcp_server_connect.jpg?500 }}
 +
 +==== Client ====
 +
 +Now, let's go over the client. The client is a program that connects to server port at a given IP address, and receives the message that the server sends. This program is much simpler, as it only need to handle one connection during its run. We start out with the includes and the constant declarations, just as with the server.
 +
 +<code c>
 +#include <stdio.h> // Standard Input/Output library
 +#include <stdlib.h> // Standard library
 +#include <unistd.h> // Unix API
 +#include <errno.h> // Error library
 +#include <string.h> // String library
 +#include <netdb.h> // Internet database
 +#include <sys/types.h> // System types library
 +#include <netinet/in.h> // Main internet library
 +#include <sys/socket.h> // Sockets library
 +
 +#include <arpa/inet.h> // The Internet library
 +
 +#define PORT "4800" // The port client will be connecting to
 +
 +#define MAXDATASIZE 100 // Max number of bytes we can get at once
 +</code>
 +
 +Now that we have taken care of these, we define the same get_in_addr function from the server.
 +
 +<code c>
 +// Get sockaddr, IPv4 or IPv6
 +void *get_in_addr(struct sockaddr *sa)
 +{
 +    if (sa->sa_family == AF_INET) { // If IPv4
 +        return &(((struct sockaddr_in*)sa)->sin_addr); // Return IPv4
 +    }
 +
 +    return &(((struct sockaddr_in6*)sa)->sin6_addr); // Otherwise return IPv6
 +}
 +</code>
 +
 +Now we will enter the main( ) function, which takes command line arguments for the IP address of the server. At the beginning of main( ), we will declare some important structures, check the command line arguments, and fill the IP address struct with basic info.
 +
 +<code c>
 +    int sockfd, numbytes; // Stores our socket descriptor, and number of bytes read
 +    char buf[MAXDATASIZE]; // Data buffer for reading the message
 +    struct addrinfo hints, *servinfo, *p; // Stores our IP address info
 +    int rv; // Used for error checking
 +    char s[INET6_ADDRSTRLEN]; // Used to store IP address of server
 +
 +    if (argc != 2) { // Check CL argument count
 +        fprintf(stderr,"usage: client hostname\n"); // Give usage if wrong
 +        exit(1);
 +    }
 +
 +    memset(&hints, 0, sizeof hints); // Fill out addrinfo with empty data
 +    hints.ai_family = AF_UNSPEC; // Don't care if IPv4 or IPv6
 +    hints.ai_socktype = SOCK_STREAM; // TCP type
 +
 +</code>
 +
 +After this, we use the getaddrinfo function just like in the server.
 +
 +<code c>
 +    if ((rv = getaddrinfo(argv[1], PORT, &hints, &servinfo)) != 0) { // If getaddrinfo fails
 +        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); // Display error if failed
 +        return 1;
 +    }
 +</code>
 +
 +Now, we do a similar for loop to the server, where we search through the servinfo linked-list until we properly create and connect to the socket.
 +
 +<code c>
 +    // Loop through all the results and connect to the first we can
 +    for(p = servinfo; p != NULL; p = p->ai_next) {
 +        if ((sockfd = socket(p->ai_family, p->ai_socktype,
 +                p->ai_protocol)) == -1) { // If the socket fails to create properly
 +            perror("client: socket"); // Give socket error
 +            continue;
 +        }
 +
 +        if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) { // If fails to connect
 +            close(sockfd); // Close the socket
 +            perror("client: connect"); // Give connection error
 +            continue;
 +        }
 +
 +        break;
 +    }
 +</code>
 +
 +Now, to ensure we are properly connected, we will check to make sure anything actually connected. Then, we will convert the IP address to a string, and then print it along with the connection message.
 +
 +<code c>
 +    if (p == NULL) { // If nothing ever connected
 +        fprintf(stderr, "client: failed to connect\n"); // Print connection failure
 +        return 2;
 +    }
 +
 +    inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr),
 +            s, sizeof s); // Convert IP address into a string
 +    printf("client: connecting to %s\n", s); // Print connection message and IP address
 +
 +    freeaddrinfo(servinfo); // Free the servinfo structure
 +</code>
 +
 +Now that we have ensured a proper connection, we will receive the message from the server, add a null-terminator to it, and print the message that was received. Finally, we will close the socket.
 +
 +<code c>
 +    if ((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) { // If receiving the message fails
 +        perror("recv"); // Give receive error
 +        exit(1);
 +    }
 +
 +    buf[numbytes] = '\0'; // Add null termination
 +
 +    printf("client: received '%s'\n",buf); // Print received string
 +
 +    close(sockfd); // Close the socket
 +
 +</code>
 +
 +Just as with the server, we must ensure that everything after the first two blocks is in the main( ) function, and that we return 0 at the end.
 +
 +Here is what it looks like when the client is launched, and receives a message:
 +
 +{{ dylanw:tcp_client_launch.jpg?700 }}
  
 ===== UDP Talker & Listener ===== ===== UDP Talker & Listener =====
  
 +Now that we have established the TCP server & client, we can move onto the UDP talker & listener. The code for these is fairly similar, with only some minor changes.
 +
 +The code for the UDP Talker & Listener can be found below:
 +
 +[[https://github.com/D-Wazzle/Simple-C-Communications/tree/master/UDP|UDP Talker & listener]]\\ 
 +
 +==== Listener ====
 +
 +This listener has very similar style to the TCP server we created. The listener is a program that binds to a predefined port, and listens to any messages received on that port, like a "reverse server". As usual it starts with the includes and constant declarations.
 +
 +<code c>
 +#include <stdio.h>      // Standard Input/Output library
 +#include <stdlib.h>     // Standard library
 +#include <unistd.h>     // Unix API
 +#include <errno.h>      // Error library
 +#include <string.h>     // String library
 +#include <sys/types.h>  // System types library
 +#include <sys/socket.h> // Sockets library
 +#include <netinet/in.h> // Main internet library
 +#include <arpa/inet.h>  // The Internet library
 +#include <netdb.h>      // Internet database
 +
 +#define MYPORT "4812"   // The port users will be connecting to
 +
 +#define MAXBUFLEN 100   // The maximum receiving buffer
 +</code>
 +
 +And again, the get_in_addr function.
 +
 +<code c>
 +// Function to get sockaddr, IPv4 or IPv6
 +void *get_in_addr(struct sockaddr *sa)
 +{
 +    if (sa->sa_family == AF_INET) { // If IPv4
 +        return &(((struct sockaddr_in*)sa)->sin_addr); // Return IPv4
 +    }
 +
 +    return &(((struct sockaddr_in6*)sa)->sin6_addr); // Return IPv6
 +}
 +</code>
 +
 +Now, we move onto the main( ) function. We start out with the usual data declarations, fill out IP address structures, and getaddrinfo for our IP address.
 +
 +<code c>
 +    int sockfd; // Socket descriptor
 +    struct addrinfo hints, *servinfo, *p; // Used to store IP address info
 +    int rv; // Used for error checking
 +    int numbytes; // Number of bytes received
 +    struct sockaddr_storage their_addr; // Store the talker IP address
 +    char buf[MAXBUFLEN]; // Receiving buffer
 +    socklen_t addr_len; // IP address length
 +    char s[INET6_ADDRSTRLEN]; // String to store IP address
 +
 +    memset(&hints, 0, sizeof hints); // Fill structure with empty info
 +    hints.ai_family = AF_UNSPEC; // Don't care if IPv4 or IPv6 (set to AF_INET to force IPv4)
 +    hints.ai_socktype = SOCK_DGRAM; // UDP type
 +    hints.ai_flags = AI_PASSIVE; // Use my IP to listen to the socket
 +
 +    if ((rv = getaddrinfo(NULL, MYPORT, &hints, &servinfo)) != 0) { // If getaddrinfo fails
 +        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); // Give getaddrinfo error
 +        return 1;
 +    }
 +</code>
 +
 +Then we use a for loop to search through the servinfo linked-list, until we find a socket that is created and bound successfully.
 +
 +<code c>
 +    // Loop through all the results and bind to the first we can
 +    for(p = servinfo; p != NULL; p = p->ai_next) {
 +        if ((sockfd = socket(p->ai_family, p->ai_socktype,
 +                p->ai_protocol)) == -1) { // If socket creation error
 +            perror("listener: socket"); // Give socket error
 +            continue;
 +        }
 +
 +        if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { // If bind fails
 +            close(sockfd); // Close the socket
 +            perror("listener: bind"); // Give bind error
 +            continue;
 +        }
 +
 +        break;
 +    }
 +</code>
 +
 +Now, we check to see if anything was actually created and bound, and if so, free up the structure and print the waiting message.
 +
 +<code c>
 +    if (p == NULL) { // If nothing ever bound to the socket
 +        fprintf(stderr, "listener: failed to bind socket\n"); // Give failure to bind message
 +        return 2;
 +    }
 +
 +    freeaddrinfo(servinfo); // Free the structure
 +
 +    printf("listener: waiting to recvfrom...\n"); // Give waiting to receive message
 +</code>
 +
 +Finally, we attempt to receive a message, waiting until one is received, and then print where the message was received from, how many bytes were sent, and what the message was. Finally, we close the socket.
 +
 +<code c>
 +    addr_len = sizeof their_addr;
 +    if ((numbytes = recvfrom(sockfd, buf, MAXBUFLEN-1 , 0,
 +        (struct sockaddr *)&their_addr, &addr_len)) == -1) { // If receiving error
 +        perror("recvfrom"); // Give receive error
 +        exit(1);
 +    }
 +
 +    printf("listener: got packet from %s\n",
 +        inet_ntop(their_addr.ss_family,
 +            get_in_addr((struct sockaddr *)&their_addr),
 +            s, sizeof s)); // Print received message and converted IP address
 +    printf("listener: packet is %d bytes long\n", numbytes); // Give number of bytes in the packet
 +    buf[numbytes] = '\0'; // Add null-terminator
 +    printf("listener: packet contains \"%s\"\n", buf); // Print packet contents
 +
 +    close(sockfd); // Close the socket
 +</code>
 +
 +As with the others, make sure to include all of this in main( ), and return 0 at the end.
 +
 +Here is what it looks like when the listener is launched:
 +
 +{{ dylanw:udp_listener_launch.jpg?500 }}
 +\\ 
 +And here is what it looks like when the listener receives a message:
 +
 +{{ dylanw:udp_listener_receive.jpg?500 }}
 +
 +==== Talker ====
 +
 +The talker is probably the simplest program of all of these, with just 65 lines of code. The talker is a program that send  given message to a predefined port on the given IP address. It doesn't assume anything is listening, although it is useless without anything listening. As usual, we start with includes and constant declarations.
 +
 +<code c>
 +#include <stdio.h>      // Standard Input/Output library
 +#include <stdlib.h>     // Standard library
 +#include <unistd.h>     // Unix API
 +#include <errno.h>      // Error library
 +#include <string.h>     // String library
 +#include <sys/types.h>  // System types library
 +#include <sys/socket.h> // Sockets library
 +#include <netinet/in.h> // Main internet library
 +#include <arpa/inet.h>  // The Internet library
 +#include <netdb.h>      // Internet database
 +
 +#define SERVERPORT "4812" // The port users will be connecting to
 +</code>
 +
 +Unlike all of the other programs, no need to define a get_in_addr function, because we are simply sending a UDP packet to the given IP address at the defined port.
 +
 +So we move onto the main( ) function, with command line arguments. We start off with the usual: declaring structures, checking argument count, filling out the IP address structure, and calling getaddrinfo for the given IP address.
 +
 +<code c>
 +    int sockfd; // Socket descriptor
 +    struct addrinfo hints, *servinfo, *p; // Structs to store IP address info
 +    int rv; // Error checking
 +    int numbytes; // Number of bytes to send
 +
 +    if (argc != 3) { // Check command line arguments
 +        fprintf(stderr,"usage: talker hostname message\n"); // Print usage if needed
 +        exit(1);
 +    }
 +
 +    memset(&hints, 0, sizeof hints); // Fill out empty structure
 +    hints.ai_family = AF_UNSPEC; // We don't care if IPv4 or IPv6 (set to AF_INET to force IPv4)
 +    hints.ai_socktype = SOCK_DGRAM; // UDP type
 +
 +    if ((rv = getaddrinfo(argv[1], SERVERPORT, &hints, &servinfo)) != 0) { // If getaddrinfo fails
 +        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); // Give getaddrinfo error
 +        return 1;
 +    }
 +</code>
 +
 +Next, we loop through the servinfo linked-list trying to create a socket, and then check if we actually created one.
 +
 +<code c>
 +    // Loop through all the results and make a socket
 +    for(p = servinfo; p != NULL; p = p->ai_next) {
 +        if ((sockfd = socket(p->ai_family, p->ai_socktype,
 +                p->ai_protocol)) == -1) { // If socket create fails
 +            perror("talker: socket"); // Give socket error
 +            continue;
 +        }
 +
 +        break;
 +    }
 +
 +    if (p == NULL) { // Check if anything actually ever was created
 +        fprintf(stderr, "talker: failed to create socket\n"); // Give failure to create message
 +        return 2;
 +    }
 +</code>
 +
 +Finally, we attempt to send the message packet to the IP address given and the port defined, free the IP address structure, print the message detailing the number of bytes sent, and finally close the socket.
 +
 +<code c>
 +    if ((numbytes = sendto(sockfd, argv[2], strlen(argv[2]), 0,
 +             p->ai_addr, p->ai_addrlen)) == -1) { // If sending error
 +        perror("talker: sendto"); // Give sending error
 +        exit(1);
 +    }
 +
 +    freeaddrinfo(servinfo); // Free the IP address structure
 +
 +    printf("talker: sent %d bytes to %s\n", numbytes, argv[1]); // Print number of bytes sent to the IP address
 +    close(sockfd); // Close the socket
 +</code>
 +
 +As usual, make sure that the code besides the first block is within main( ), with Cl arguments, and you return 0 at the end.
 +
 +Here is what it looks like when the talker is launched, and sends a message:
 +
 +{{ dylanw:udp_talker_launch.jpg?700 }}
 +
 +
 +This is basically it. Once you understand the basic network calls, and the looping structure, then it should be very easy to implement this yourself. Try out the program given yourself, and then try writing your own, and see if you can make it more efficient, or unique in your own way. Again, this is just the basics, and more difficult concepts will be covered in the future.
  
 ===== Final Words ===== ===== Final Words =====
tcp_udp.1493706466.txt.gz · Last modified: 2017/05/01 23:27 by dwallace