Skip to content

Instantly share code, notes, and snippets.

@SourLemonJuice
Last active August 19, 2024 19:07
Show Gist options
  • Save SourLemonJuice/2d7e8db37b07deeafb5191d3aec4a0ae to your computer and use it in GitHub Desktop.
Save SourLemonJuice/2d7e8db37b07deeafb5191d3aec4a0ae to your computer and use it in GitHub Desktop.
It's an example, of using a UDP socket to receive server messages on port 1907. Example server command: "netcat -l -u -p 1907 localhost"
#include <error.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/socket.h>
int UdpReceiveSocketDemo(void)
{
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0) {
perror("Create socket error");
exit(1);
}
struct sockaddr_in addr = {0};
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
addr.sin_port = htons(1907);
char buffer[256] = "Hello Server\n";
sendto(fd, buffer, sizeof(buffer), 0, (struct sockaddr *)&addr, sizeof(addr));
while (true) {
memset(buffer, 0, sizeof(buffer));
if (recv(fd, buffer, sizeof(buffer), 0) == -1) {
perror("Receive error");
return 3;
}
printf("Receive data: %s", buffer);
}
close(fd);
return 0;
}
int main(void)
{
return UdpReceiveSocketDemo();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment