我目前正在尝试组建一个程序,允许两个程序在文件之间进行通信,充当数据链接层。
我遇到的问题是,即使我的消息似乎是通过网络发送的,收到的消息后面有一些奇怪的垃圾文本,然后传递给它主文件,垃圾文本全部通过,消息完全消失。非常感谢任何正确方向的指针。
发送程序
main(){
dlinits("hostname", 43520);
dlsend("hello");
}
接收程序
#include <string.h>
char* dlrecv();
main(){
char* test;
dlinitr(43520);
strcpy(test,dlrecv());
printf("%s\n", test);
}
数据链接程序
#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;
}
答案 0 :(得分:1)
该行
sendto(sk,msg,sizeof(msg)+1,0,&remote,sizeof(remote));
应该是
sendto(sk,msg,strlen(msg)+1,0,&remote,sizeof(remote));