客户端:
#include <stdio.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, const char *argv[])
{
//创建套接字
//函数原型:int socket(int domain, int type, int protocol);
int sock_fd = socket(AF_INET,SOCK_STREAM,0);
if(sock_fd<0)
{
perror("creat socket failed: ");
return -1;
}
//定义结构体
struct sockaddr_in serve;
serve.sin_family = AF_INET;
serve.sin_port = htons(atoi(argv[2]));
serve.sin_addr.s_addr = inet_addr(argv[1]);
//绑定服务器的IP地址和端口号
//函数原型:int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
int ret = bind(sock_fd,(struct sockaddr *)&serve,sizeof(serve));
if(ret<0)
{
if(errno!=98)
{
perror("bind failed:");
}
}
//发起连接
//函数原型:int connect(int sockfd, const struct sockaddr *addr, socklen_taddrlen);
int ret2 = connect(sock_fd,(struct sockaddr *)&serve,sizeof(serve));
if(ret<0)
{
if(errno != 98)
{
perror("connect failed");
}
}
//打开文件
FILE * fd = fopen("./1.txt","r");
if(NULL == fd)
{
perror("open file failed");
}
char *buf = calloc(2,50);
while(1)
{
bzero(buf,100);
int ret_fd = fread(buf,50,2,fd);
//函数原型:ssize_t send(int sockfd, const void *buf, size_t len, int flags);
send(sock_fd,buf,100,0);
if(ret_fd == 0)
{
break;
}
}
close(sock_fd);
fclose(fd);
return 0;
}
服务端:
#include <stdio.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#define filepath "./2.txt"
int main(int argc, const char *argv[])
{
//创建套接字
//函数原型:int socket(int domain, int type, int protocol);
int sock_fd = socket(AF_INET,SOCK_STREAM,0);
if(sock_fd<0)
{
perror("creat socket failed: ");
return -1;
}
//定义结构体
struct sockaddr_in serve;
serve.sin_family = AF_INET;
serve.sin_port = htons(atoi(argv[2]));
serve.sin_addr.s_addr = inet_addr(argv[1]);
//绑定服务器的IP地址和端口号
//函数原型:int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
int ret = bind(sock_fd,(struct sockaddr *)&serve,sizeof(serve));
if(ret<0)
{
if(errno!=98)
{
perror("bind failed");
}
}
//监听
int lis_fd = listen(sock_fd,4);
printf("等待连接.....\n");
//等待对接端口连接
//函数原型:int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
struct sockaddr_in cin;
socklen_t addrlen = sizeof(cin);
int new_fd = accept(sock_fd,(struct sockaddr *)&cin,&addrlen);
if(new_fd<0)
{
perror("butt-joint failed: ");
return -1;
}
printf("[%s:%d] new_fd=%d 客户端连接成功\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),new_fd);
//打开文件
FILE * fd = fopen(filepath,"a");
if(NULL == fd)
{
perror("open file failed");
}
char buf[100];
while(1)
{
bzero(buf,100);
int res_r = recv(new_fd,buf,100,0);
if(res_r == 0)
break;
fwrite(buf,strlen(buf),1,fd);
//printf("客户端:%s",buf);
}
close(sock_fd);
close(lis_fd);
fclose(fd);
return 0;
}