I'm trying to set up a simple communication scheme with a program I wrote using UDP. The program will set up a UDP socket in a nonblocking fashion, then use select() to read non blocking from the socket. Here are the contents of the program:
#include <stdio.h> /* Standard input/output definitions */
#include <stdlib.h> /* UNIX standard function definitions */
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/un.h>
#include <sys/socket.h>
#include <fcntl.h> /* File control definitions */
#include <signal.h>
#include <time.h>
#include <stdint.h> /* Standard integer types */
#include <string.h> /* String function definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/select.h>
int setupUdpSocketN(int *fd, uint16_t port_no)
{
struct sockaddr_in my_addr;
// Create UDP socket:
if ( (*fd = socket(AF_INET,SOCK_DGRAM,0)) < 0 )
return -1;
fcntl(*fd, F_SETFL, O_NONBLOCK);
// Bind socket:
memset((char *)&my_addr, 0, sizeof(my_addr));
my_addr.sin_family = AF_INET;
my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
my_addr.sin_port = htons(port_no);
if ( bind(*fd, (struct sockaddr*)&my_addr, sizeof(my_addr)) == -1 ) {
close(*fd);
return -2;
}
return EXIT_SUCCESS;
}
int main(void) {
int fd, maxfd, nready;
size_t recvlen;
uint8_t buf[256];
fd_set rset;
setupUdpSocketN(&fd, 60000);
maxfd = fd + 1;
while(1) {
FD_ZERO(&rset);
FD_SET(fd, &rset);
if( (nready = select(maxfd, &rset, NULL, NULL, NULL)) < 0 ) {
printf("Error in select: %s\n", strerror(errno));
}
if( FD_ISSET(fd, &rset) ) {
recvlen = recv(fd, buf, 256, 0);
//recvlen = recvfrom(fd, buf, 256, 0, NULL, NULL);
for(int i = 0; i < recvlen; i++) {
printf("%02x ", buf[i]);
}
printf("\n");
}
}
return 0;
}
I then try and send this program binary data using echo, xxd, and netcat:
echo -ne "\xfe\x64\x32\x1a\xb0" | xxd -rp | nc -u localhost 60000
However, this program when run just blocks endlessly. I'm very new to socket programming and unsure how to proceed.