UDP 프로토콜 기반 클라이언트 및 서버 측 파일 전송
3550 단어 LinuxC 일반 명령
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define IP "127.0.0.1"
#define PORT 8888
//
int main(int argc, char *argv[])
{
int sockfd;
int ret;
char buf[32] = {0};
if(argc != 2 )
{
printf("fault
");
exit(1);
}
struct sockaddr_in server_addr;
//
sockfd = socket(PF_INET, SOCK_DGRAM, 0);
if(-1 == sockfd)
{
perror("socket");
exit(1);
}
//
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = PF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = inet_addr(IP);
int length = sizeof(server_addr);
int fd = open(argv[1], O_RDONLY);
if(-1 == fd)
{
perror("open");
exit(1);
}
//
// :
// :
ret = sendto(sockfd, argv[1], strlen(argv[1]), 0, (struct sockaddr*)&server_addr, (socklen_t)length);
if(-1 == ret)
{
perror("sendto");
exit(1);
}
while(1)
{
//
ret = read(fd, buf, sizeof(buf)-1);
if(-1 == ret)
{
perror("read");
}
if(0 == ret)
{
printf(" !
");
strcpy(buf, "bye");
sendto(sockfd, buf, strlen(buf), 0, (struct sockaddr*)&server_addr, (socklen_t)length);
close(fd);
break;
}
ret = sendto(sockfd, buf, strlen(buf), 0, (struct sockaddr*)&server_addr, (socklen_t)length);
if(-1 == ret)
{
perror("sendto");
}
bzero(buf, sizeof(buf));
}
close(sockfd);
close(fd);
return 0;
}
02 서버 측
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define PORT 8888
#define IP "127.0.0.1"
//
int main()
{
int sockfd, ret;
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
char buf[32] = {0};
sockfd = socket( PF_INET, SOCK_DGRAM, 0);
if(-1 == sockfd)
{
perror("socket");
exit(1);
}
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = PF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = inet_addr(IP);
ret = bind(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr));
if(-1 ==ret)
{
perror("bind");
exit(1);
}
int length = sizeof(client_addr);
ret = recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr*)&client_addr, (socklen_t*)&length);
if(-1 == ret)
{
perror("recvfrom");
exit(1);
}
printf(" %s, ...
", buf);
int fd = open(buf, O_WRONLY | O_CREAT |O_EXCL, 00700);
if(-1 == fd)
{
perror("open");
exit(1);
}
while(1)
{
bzero(buf, sizeof(buf));
ret = recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr*)&client_addr, (socklen_t*)&length);
if(-1 == ret)
{
perror("recvfrom");
}
if(!strcmp(buf, "bye"))
{
printf(" !
");
close(fd);
break;
}
ret = write(fd, buf, strlen(buf));
if(-1 == ret)
{
perror("write");
}
bzero(buf, sizeof(buf));
}
close(sockfd);
return 0;
}