0

I am just learning how to use sockets and am trying to make some sample UDP client-server code. Everything seems to work fine, but when the client sends a message, the server does not receive it. I have not tried using TCP to see if that works yet, but i have tried echo "data" > /dev/udp/127.0.0.1/9999 and it works.

server.cpp

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFLEN 1024
#define PORT 9999
void die(char s[]) {
    perror(s);
    exit(1);
}
int main() {
    int sock;
    char buffer[BUFLEN];
    struct sockaddr_in here, from;
    if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
        die("Socket creation error: ");
    }
    memset(&here, 0, sizeof(here));
    memset(&from, 0, sizeof(from));
    here.sin_family = AF_INET;
    here.sin_addr.s_addr = inet_addr("127.0.0.1");
    here.sin_port = htons(PORT);
    if (bind(sock, (struct sockaddr *)&here, sizeof(here)) < 0) {
        die("Socket binding error: ");
    }
    printf("Waiting for message...\n");
    socklen_t froms = sizeof(from);
    int n = recvfrom(sock, (char *)buffer, BUFLEN, MSG_WAITALL, (struct sockaddr *)&from, (socklen_t *)&froms);
    if (n < 0) {
        die("Message recieving error: ");
    }
    buffer[n] = '\0';
    printf("Client says: %s\nEnding program...\n", buffer);
    return 0;
}

client.cpp

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFLEN 1024
#define PORT 9999
void die(char s[]) {
    perror(s);
    exit(1);
}
int main() {
     int sock;
     char * msg = "Hello Server!";
     struct sockaddr_in there;
     if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
         die("Socket creation error: ");
     }
     memset(&there, 0, sizeof(there));
     there.sin_family = AF_INET;
     there.sin_port = htons(PORT);
     there.sin_addr.s_addr = inet_addr("127.0.0.1");
     printf("Sending message...\n");
     if (sendto(sock, (char *)msg, sizeof(msg), MSG_CONFIRM, (struct sockaddr *)&there, sizeof(there)) < 0) {
         die("Message sending error: ");
     }
     printf("Message sent.\nEnding program...\n");
}

Expected result: For the data from sendto() to be sent when i run server.cpp and then client.cpp.

Actual result: server.cpp returns no error, but client.cpp returns "Message sending error: Invalid arguments". Data shows up when using echo > /dev/udp/127.0.0.1/9999.

0 Answers0