I am currently attempting to form a program that allows two programs to communicate using one go between file, acting as a data link layer.
The problem I'm having is that even though my message seems to be sending across the network, the message that is received has some weird garbage text after it, and when it is then passed to the main file, the garbage text is all that is passed, and the message disappears completely. Any pointers in the correct direction are greatly appreciated.
Sending program
main(){
dlinits("hostname", 43520);
dlsend("hello");
}
Receiving program
#include <string.h>
char* dlrecv();
main(){
char* test;
dlinitr(43520);
strcpy(test,dlrecv());
printf("%s\n", test);
}
Data Link program
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#define BUFMAX 100
static int sk;
static struct sockaddr_in remote;
static struct sockaddr_in local;
dlinits(char* host, int port){//initialize sender
struct hostent *hp;
sk = socket(AF_INET, SOCK_DGRAM, 0);
remote.sin_family = AF_INET;
hp = gethostbyname(host);
if (hp == NULL){
printf("Can't find host name\n");
exit(1);
}
bcopy(hp->h_addr,&remote.sin_addr.s_addr,hp->h_length);
remote.sin_port = ntohs(port);
}
dlinitr(int port){//initialize receiver
int rlen = sizeof(remote);
int len = sizeof(local);
char buf[BUFMAX];
sk = socket(AF_INET,SOCK_DGRAM,0);
local.sin_family = AF_INET;
local.sin_addr.s_addr = INADDR_ANY;
local.sin_port = htons(port);
bind (sk, &local,sizeof(local));
getsockname(sk,&local,&len);
}
dlsend(char* msg){//send data
printf("%s\n", msg);
sendto(sk,msg,sizeof(msg)+1,0,&remote,sizeof(remote));
}
char* dlrecv(){//receive data
char* msg[BUFMAX];
recvfrom(sk,msg,BUFMAX,0,&remote,sizeof(remote));
printf("%s\n", msg);
return msg;
}