I am trying to read binary data from a UDP socket. The data (binary, incremented every step) has 16 bits and is sent via an FPGA Ethernet interface to my host computer (Ubuntu 20). My UDP server is receiving data but does not display it. I suppose the "printf" function has a problem, because when I am sending (local) text via terminal it works. How can I display this data? The code for the UDP server is as follows:
#include <QCoreApplication>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <iostream>
#include <string>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#define BUFLEN 512 //Max length of buffer
#define PORT 1024 //The port on which to listen for incoming data
void die(char *s)
{
perror(s);
exit(1);
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
struct sockaddr_in si_me, si_other;
socklen_t slen = sizeof(si_other);
int s, i , recv_len;
char buf[BUFLEN];
//create a UDP socket
if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
{
die("socket");
}
// zero out the structure
memset((char *) &si_me, 0, sizeof(si_me));
si_me.sin_family = AF_INET;
si_me.sin_port = htons(PORT);
si_me.sin_addr.s_addr = htonl(INADDR_ANY);
//bind socket to port
if( bind(s , (struct sockaddr*)&si_me, sizeof(si_me) ) == -1)
{
die("bind");
}
printf("Using port %d, ctrl + C abort\n", PORT);
//keep listening for data
while(1)
{
printf("Waiting for data...");
fflush(stdout);
//try to receive some data, this is a blocking call
if ((recv_len = recvfrom(s, buf, BUFLEN, MSG_WAITALL, (struct sockaddr *) &si_other, &slen)) == -1)
{
die("recvfrom()");
}
//print details of the client/peer and the data received
printf("Received packet from %s:%d\n", inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port));
printf("Data: %s\n" , buf);
}
close(s);
return 0;
return a.exec();
}
Solution: There was indeed a problem with the printf() function. In order to print received hex data, I used this hint (Problem reading hexadecimal buffer from C socket) to print the data:
#include <ctype.h>
#include <stdio.h>
void hexdumpunformatted(void *ptr, int buflen) {
unsigned char *buf = (unsigned char*)ptr;
int i, j;
for (i=0; i<buflen; i++) {
printf("%02x ", buf[i]);
printf(" ");
}
}