C++ when used in networking is completely cryptic to me. Would anyone mind helping me break down the errors in this code? It was given to my class as an example of how not to make a UDP server.
I already notice a few issues like how the buffers are a fixed 256 bytes long, but for the most part I don’t understand it. I’m more of a PHP/Java/JavaScript programmer.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
void error(char *msg)
{
perror(msg);
exit(1);
}
int main(int argc, char *argv[])
{
int sockfd, portno, clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
if (argc <= 2) {
fprintf(stderr,"Error, no port provided\n");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("Error opening socket");
bzero((char *) &cli_addr, sizeof(serv_addr));
portno = atoi(argv[2]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr,
sizeof(cli_addr)) < 0)
error("ERROR on binding");
clilen = sizeof(cli_addr);
while(100)
{
bzero(buffer,256);
n = recvfrom(sockfd,buffer, 0, 255,
(struct sockaddr *) &serv_addr,&clilen);
printf("A client from %s port %d connected\n", inet_aton(cli_addr.sin_addr), htons(cli_addr.sin_port));
if (n < 0) error("Error reading from socket");
printf("Here is the message: %s\n",buffer);
n = sendto(sockfd,"I got your message",18,0,(struct sockaddr *) &serv_addr,sizeof(cli_addr));
if (n < 0) error("Error writing to socket");
}
close(sockfd);
return 0;
}
Have you tried it? Use nc/aka netcat to try sending UDP packets too it.
Oh and here is another clue from socket()’s man page
An you are right about the buffer size although it should not overflow – I would use 2^16 aka 65536 as this is the largest UDP packet supported in IPv4