#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
//前言
// 服务器和客户端直接传输数据
// 套接字
//主题:搭建服务器
//流程:1.创建流式套接字 socket()
// 2.绑定IP地址和端口号 bind()
// 3.接受数据,并获取对方信息 recvfrom()
// 4.发送数据,要指定发送的人 sendto()
// 5.关闭套接字,释放资源 close()
//【一】创建流式套接字
/* int socket(int domain, int type, int protocol);*/
//参数:
// domain:网域名称--------常见:AF_INET --->> IPV4
// type:socket通信类型-----常见:SOCK_STREAM --->>流式 SOCK_DGRAM --->>
// protocol:协议-----------常见:填写0
// 返回值:
// 成功:返回套接字文件描述符
// 失败:返回-1
int clientSocket=socket(AF_INET,SOCK_DGRAM,0);
if (clientSocket==-1)
{
perror("socket error");
return -1;
}
printf("sfd=%d__%d__\n",clientSocket,__LINE__);
//定义服务器地址信息结构体
struct sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(69);
sin.sin_addr.s_addr =inet_addr("192.168.2.163");
//请求数据
char buf[516];
/*
short *ptr1=(short*)buf;
*ptr1=htons(1);
char * ptr2=buf+2;
strcpy(ptr2,"1_armcli.c");
char *ptr3=ptr2+strlen(ptr2);
*ptr3=0;
char *ptr4=ptr3+1;
strcpy(ptr4,"octet");
int len=2+strlen(ptr2)+7;
printf("%d",len);
*/
int size=sprintf(buf,"%c%c%s%c%s%c",0,1,"1_armcli.c",0,"octet",0);
if(sendto(clientSocket,buf,size,0,(struct sockaddr*)&sin,sizeof(sin))<0)
{
perror("sendto error");
return -1;
}
printf("发送成功:%d\n",size);
struct sockaddr_in from;
socklen_t addrlen=sizeof(from);
int fd;
int count=0;
int writesize=1;
ssize_t sizerecv=516;
int port;
fd=open("./1_armcli.c", O_WRONLY|O_CREAT|0664);
if(fd<0)
{
perror("open error\n");
return -1;
}
short *N=(short*)buf;
while(1)
{
bzero(buf,sizeof(buf));
int len=sizeof(struct sockaddr);
if((sizerecv=(recvfrom(clientSocket,buf,sizeof(buf),0,(struct sockaddr*)&from,&addrlen)))<0)
{
perror("recvfrom error");
return -1;
}
printf("临时端口:%d",htons(from.sin_port));
writesize=write(fd, buf+4, sizeof(buf)-4);
if(writesize<0)
{
perror("write error");
return -1;
}
count++;
*N=htons(4);
printf("已完成第%d轮传输\n",count);
if(sendto(clientSocket,buf,4,0,(struct sockaddr*)&from,sizeof(from))<0)
{
perror("sendto error");
return -1;
}
if(sizerecv<516)
break;
}
printf("完成传输\n");
close(clientSocket);
close(fd);
return 0;
}