Skip to content

Instantly share code, notes, and snippets.

@theonewolf
Last active August 29, 2015 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theonewolf/8738625 to your computer and use it in GitHub Desktop.
Save theonewolf/8738625 to your computer and use it in GitHub Desktop.
UDP OS X exploration
default:
clang udp.c -o udp
clean:
rm udp
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/ip.h>
#include <errno.h>
#define BUF_LEN 2048
#define PORT 4000
/* helper functions */
int get_socket()
{
int sock = 0;
struct sockaddr_in addr;
if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
{
perror("Error creating socket");
exit(EXIT_FAILURE);
}
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sock, (const struct sockaddr*) &addr, sizeof(struct sockaddr_in)))
{
perror("Error binding socket");
exit(EXIT_FAILURE);
}
return sock;
}
void receive_loop(int socket)
{
uint8_t buf[BUF_LEN];
ssize_t recv_len = 0;
while ((recv_len = recv(socket, buf, BUF_LEN, 0)) > 0)
{
fprintf(stdout, "Received Message: %*s\n", (int) recv_len, buf);
}
perror("Socket error on recv");
exit(EXIT_FAILURE);
}
/* main */
int main(int argc, char* argv[])
{
int socket = 0;
fprintf(stdout, "-- Getting socket -- \n");
socket = get_socket();
fprintf(stdout, "-- Looping for packets --\n");
receive_loop(socket);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment