Commit 8395b988 authored by Andreas Schmidt's avatar Andreas Schmidt

Initial UDP connection and API definition.

parent 2b34c2b6
CC=gcc
CFLAGS=-I
all:
$(CC) -o ./bin/sender prrt/prrt_socket.c sender.c -Wall
$(CC) -o ./bin/receiver prrt/prrt_socket.c receiver.c -Wall
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include "prrt_socket.h"
int prrt_socket() {
int fd;
if((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("cannot create socket");
return -1;
}
return fd;
}
int prrt_connect() {
return 0;
}
int prrt_bind(int fd, int port) {
struct sockaddr_in address;
memset((char*) &address, 0, sizeof(address));
address.sin_family = AF_INET;
address.sin_addr.s_addr = htonl(INADDR_ANY);
address.sin_port = htons(port);
return bind(fd, (struct sockaddr *) &address, sizeof(address));
}
int prrt_send(int fd, const void * data, size_t data_len) {
// TODO: should iterate over receivers
struct hostent *hp;
char *host = "localhost";
struct sockaddr_in targetaddr;
memset((char*) &targetaddr, 0, sizeof(targetaddr));
targetaddr.sin_family = AF_INET;
targetaddr.sin_port = htons(5000); // TODO: make port flexible
hp = gethostbyname(host);
memcpy((void *)&targetaddr.sin_addr, hp->h_addr_list[0], hp->h_length);
if((sendto(fd, data, data_len, 0, (struct sockaddr *) &targetaddr, sizeof(targetaddr)) < 0)) {
perror("sendto failed");
return -1;
}
return 0;
}
int prrt_recv(int fd, void * bufin, size_t length) {
int n;
struct sockaddr_in remote;
socklen_t addrlen = sizeof(remote);
n = recvfrom(fd, bufin,length, 0, (struct sockaddr *) &remote, &addrlen);
printf("got a datagram from %s port %d\n", inet_ntoa(remote.sin_addr), ntohs(remote.sin_port));
return n;
}
int prrt_close(int fd) {
close(fd);
return 0;
}
#ifndef PRRT_SOCKET
#define PRRT_SOCKET
int prrt_socket(void);
int prrt_close(int fd);
int prrt_bind(int fd, int port);
int prrt_connect();
int prrt_send(int fd, const void * data, size_t data_len);
int prrt_recv(int fd, void * bufin, size_t length);
#endif
#include <stdio.h>
#include <unistd.h>
#include "prrt/prrt_socket.h"
#define MAXBUF 1024*1024
int main() {
int n;
char bufin[MAXBUF];
printf("PRRT - RECEIVER\n");
int s = prrt_socket();
if(prrt_bind(s, 5000) < 0) {
perror("bind failed");
return 0;
}
while(1) {
n = prrt_recv(s,bufin,MAXBUF);
if(n < 0) {
perror("Error receiving data");
} else {
printf("GOT %d BYTES\n",n);
}
usleep(1000*1000);
}
return 0;
}
#include <stdio.h>
#include <string.h>
#include "prrt/prrt_socket.h"
int main() {
int fd;
printf("PRRT - SENDER\n");
char *message = "this is a message";
if((fd = prrt_socket()) < 0) {
perror("socket failed");
return 0;
}
prrt_connect();
prrt_send(fd, message, strlen(message));
prrt_close(fd);
return 0;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment