1.仿照 togglesi.c 和 togglec.c,编写一个网络通信程序,服务器端为 task43s.c,客户端 为 task43c.c,客户端将从服务器下载指定文件,并显示输出
task43c.c
#include "wrapper.h"
char* getname(char *str);
int main(int argc, char **argv)
{
int client_sock, port;
char *host, buf[MAXLINE],*file_name, *name;
rio_t rio;
if (argc != 4) {
fprintf(stderr, "usage: %s \n" , argv[0]);
exit(1);
}
host = argv[1];
port = atoi(argv[2]);
file_name = argv[3];
client_sock = open_client_sock(host, port);
send(client_sock, file_name, strlen(file_name),0);
FILE* file;
name=getname(argv[3]);
while(recv(client_sock, buf, MAXLINE,0)!=0){
if((file=fopen(name,"wb"))==NULL)
{
break;
}
fputs(buf, file);
fputs(buf, stdout);
}
if(file!=NULL){
fclose(file);
printf("file %s download succeed\n",name);
}
else{
printf("file %s download fail\n",name);
}
close(client_sock);
exit(0);
}
char* getname(char *str){
char *p,*tmp;
p = strtok(str, "/");
tmp = p;
while(tmp)
{
p = tmp;
tmp = strtok(NULL, "/");
}
return p;
}
task43s.c
#include "wrapper.h"
void toggle(int conn_sock);
int main(int argc, char **argv)
{
int listen_sock, conn_sock, port, clientlen;
struct sockaddr_in clientaddr;
struct hostent *hp;
char *haddrp;
if (argc != 2) {
fprintf(stderr, "usage: %s \n" , argv[0]);
exit(1);
}
port = atoi(argv[1]);
listen_sock = open_listen_sock(port);
while (1) {
clientlen = sizeof(clientaddr);
conn_sock = accept(listen_sock, (SA *)&clientaddr, &clientlen);
/* determine the domain name and IP address of the client */
hp = Gethostbyaddr((const char *)&clientaddr.sin_addr.s_addr,
sizeof(clientaddr.sin_addr.s_addr), AF_INET);
haddrp = inet_ntoa(clientaddr.sin_addr);
printf("server connected to %s (%s)\n", hp->h_name, haddrp);
toggle(conn_sock);
close(conn_sock);
}
exit(0);
}
void toggle(int conn_sock)
{
int n;
char buf[MAXLINE];
if((n=recv(conn_sock,buf,MAXLINE,0))>0){
printf("downlowd the file %s ",buf);
FILE * file;
memset(buf,sizeof(buf),0);
if((file=fopen(buf,"rb"))!=NULL){
while (!feof(file)) {
fgets(buf, sizeof(buf), file);
send(conn_sock,buf,sizeof(buf),0);
}
printf("succeed\n");
fclose(file);
}
else{
printf("fail\n");
send(conn_sock,"",0,0);
}
}
memset(buf,0,sizeof(buf));
}
gcc task43s.c -o task43s -L. -lwrapper
./task43s 12345
gcc task43c.c -o task43c -L. -lwrapper
./task43c localhost 12345 文件路径