#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/msg.h>
#include<stdio.h>
#include<sys/ipc.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/stat.h>
#include<fcntl.h>
#define PORT 69
#define IP "192.168.2.144"
#define ERR_MSG(msg) do{\
fprintf(stderr,"line:%d: %s %s",__LINE__,__FILE__,__func__);\
perror(msg);\
}while(0)
int main()
{
//创建套接字
int soketfd=socket(AF_INET,SOCK_DGRAM,0);
if(soketfd<0)
{
ERR_MSG("socket");
return -1;
}
struct sockaddr_in myaddr;
myaddr.sin_family=AF_INET;
myaddr.sin_port=htons(PORT);
myaddr.sin_addr.s_addr=inet_addr(IP);
//绑定端口与套字节
if(bind(soketfd,(struct sockaddr *)&myaddr,sizeof(myaddr))<0)
{
ERR_MSG("bind");
return -1;
}
printf("bind success __%d__\n",__LINE__);
char buf[516]="";
char *sp1;
short blok;
printf("input the filename\n");
scanf("%s",sp1);
int size=sprintf(buf,"%c%c%s%c%s%c",0,1,sp1,0,"octet",0);
if(sendto(soketfd,buf,size,0,(struct sockaddr *)&myaddr,size)<0)
{
ERR_MSG("SENDTO");
return -1;
}
printf("send access __%d__",__LINE__);
struct sockaddr_in cin;
int addrlen=sizeof(cin);
int myopen;
if(recvfrom(soketfd,buf,size,0,(struct sockaddr *)&cin,&addrlen)<0)
{
ERR_MSG("RECSFROM");
return -1;
}
if(buf[2]==5)
{
char *sp2=buf+4;
printf("%s\n",sp2);
}
else if(buf[2]==3)
{
if(myopen==open("./test.txt",O_RDWR|O_APPEND|O_CREAT,0664))
{
ERR_MSG("OPEN");
return -1;
}
while(buf)
{
write(myopen,buf,strlen(buf));
}
buf[0]=4;
char ack[4];
sprintf(ack,"%c%c%s",0,4,buf[2]);
if(sendto(ack,buf,4,0,(struct sockaddr_in *)&cin,sizeof(cin))<0)
{
ERR_MSG("SENDTO");
return -1;
}
close(myopen);
}
close(soketfd);
return 0;
}