unp #1 (reading notes) (file transfer)
最近(准确的来说是昨天)开始看起了Stevens的《Unix Network Programming》,刚看了第一章,觉得那个时间服务器客户端程序有点可玩,于是稍微的把它改写成一个非常简单的文件传输服务器客户端程序,经本地测试传个小小的文本文件没问题,因为刚好有个网络上的服务器可以用,可以也稍微拿来测试一下,结果状况惨不忍睹。
#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <stdio.h> #include <string.h> #include <stdlib.h> int main(int argc, char **argv) { int sockfd, n, i; struct sockaddr_in servaddr; FILE* fp; char buff[100]; if (argc != 3) { printf("Usage: ftc IP FILE\n"); exit(1); } sockfd = socket(AF_INET, SOCK_STREAM, 0); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(8081); inet_pton(AF_INET, argv[1], &servaddr.sin_addr); connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)); fp = fopen(argv[2], "r"); while (fgets(buff, 100, fp) != NULL) write(sockfd, buff, sizeof(buff)); fclose(fp); return 0; }
#include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> int main(int argc, char **argv) { int listenfd, connfd, n; struct sockaddr_in servaddr; FILE *fp; char buff[100]; listenfd = socket(AF_INET, SOCK_STREAM, 0); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(8081); bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr)); listen(listenfd, 1024); for ( ; ; ) { printf("linstening...\n"); if (connfd = accept(listenfd, (struct sockaddr *) NULL, NULL)) printf("handle a request\n"); while (n = read(connfd, buff, sizeof(buff))) { fp = fopen("tmp.txt", "a"); fwrite(buff, sizeof(char), strlen(buff), fp); fclose(fp); } close(connfd); } return 0; }
另外本来昨晚想发的,不料竟然访问不了博客,觉得可能是服务器的周期性抽风也就没太加留意。
然后直到刚才竟然还访问不了,稍微查一查,似乎是电信分配的DNS不解释我的域名了,可恶,果断改DNS为8.8.8.8。