Linux下源程序,用来测试向Windows发送自定义的结构,我接收的总是错误!
/* server.c */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
typedef struct _record {
char type; //记录类型
time_t begintime; //开始时间
time_t endtime; //结束时间
int person; //人员编号
char keyID; //钥匙编号
}RECORD;
RECORD brecord[10];
void initstruct(void) {
brecord[0].type = 1;
brecord[0].begintime = 1000;
brecord[0].endtime = 10000;
brecord[0].person = 1;
brecord[0].keyID = 1;
printf("the number of struct%d/n",sizeof(RECORD));
}
main()
{
int sockfd,new_fd;
struct sockaddr_in my_addr;
struct sockaddr_in their_addr;
int sin_size,numbytes;
char buff[100],check[10];
memset(buff,0,100);
memset(check,0,100);
initstruct(); //init
//建立TCP套接口
if((sockfd = socket(AF_INET,SOCK_STREAM,0))==-1) {
perror("socket"
;
exit(1);
}
//初始化结构体,并绑定2323端口
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(9999);
my_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(my_addr.sin_zero),8);
//绑定套接口
if(bind(sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr)) < 0)
{
perror("bind"
;
exit(1);
}
//创建监听套接口
if(listen(sockfd,10)==-1) {
perror("listen"
;
exit(1);
}
//等待连接
while(1) {
sin_size = sizeof(struct sockaddr_in);
perror("server is run"
;
//如果建立连接,将产生一个全新的套接字
if((new_fd = accept(sockfd,(struct sockaddr *)&their_addr,(socklen_t *) &sin_size)) < 0)
{
perror("accept"
;
exit(1);
}
//生成一个子进程来完成和客户端的会话,父进程继续监听
if(!fork()) {
//读取客户端发来的信息
if((numbytes = recv(new_fd,buff,sizeof(buff),0)) < 0) {
perror("recv"
;
exit(0);
}
if(strcmp(buff, "0x06"
!= 0) {
exit(0);
}
write(new_fd,&brecord,sizeof(RECORD));
printf("type:%d/n",brecord[0].type);
printf("begin:%d/n",brecord[0].begintime);
printf("type:%d/n",brecord[0].endtime);
printf("type:%d/n",brecord[0].person);
printf("type:%d/n",brecord[0].keyID);
//if(send(new_fd,buff,strlen(buff),0) < 0) perror("send"
;
close(new_fd);
exit(0);
}
close(new_fd);
}
close(sockfd);
}