下载附件,make一下,具体用法是
tfserver
tfclient
这个程序用于练习socket网络编程
tfserver代码:
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <sys/types.h>
- #include <unistd.h>
- #include <sys/socket.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- const int port=1025;
- const int backlog=5;
- int main(int argc,char **argv){
- int fd,listenfd,connectfd;
- struct sockaddr_in server;
- struct sockaddr_in client;
- socklen_t addrlen;
- if(argc<2){
- fprintf(stderr,"Usage: %s
" ,argv[0]); - exit(1);
- }
- //建立套接字
- if(-1==(listenfd=socket(AF_INET,SOCK_STREAM,0))){
- perror("socket() error\n");
- exit(1);
- }
- int opt=SO_REUSEADDR;
- setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
- bzero(&server,sizeof(server));
- server.sin_family=AF_INET;
- server.sin_port=htons(port);
- server.sin_addr.s_addr=htonl(INADDR_ANY);
- if(-1==bind(listenfd,(struct sockaddr *)&server,sizeof(server))){
- perror("bind() error\n");
- exit(1);
- }
- if(-1==listen(listenfd,backlog)){
- perror("listen() error\n");
- exit(1);
- }
- addrlen=sizeof(client);
- if(-1==(connectfd=accept(listenfd,(struct sockaddr *)&client,&addrlen))){
- perror("accept() error\n");
- exit(1);
- }
- if(-1==(fd=open(argv[1],O_RDONLY))){
- perror("open() error\n");
- close(connectfd);
- close(listenfd);
- exit(1);
- }
- char buf[512];
- int len=0;
- bzero(buf,sizeof(buf));
- while((len=read(fd,buf,sizeof(buf)))>0){
- write(connectfd,buf,len);
- }
- close(fd);
- close(connectfd);
- close(listenfd);
- return 0;
- }
tfclient的代码:
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <sys/socket.h>
- #include <arpa/inet.h>
- #include <netinet/in.h>
- #include <fcntl.h>
- #include <netdb.h>
- const int port= 1025;
- int main(int argc,char **argv){
- struct sockaddr_in server;
- int connectfd,fd;
- struct hostent *he;
- if(argc<3){
- fprintf(stderr,"Usage: %s
" - exit(1);
- }
- if(NULL==(he=gethostbyname(argv[1]))){
- perror("gethostbyname() error\n");
- exit(1);
- }
- if(-1==(connectfd=socket(AF_INET,SOCK_STREAM,0))){
- perror("sock() error\n");
- exit(1);
- }
- bzero(&server,sizeof(server));
- server.sin_family=AF_INET;
- server.sin_port=htons(port);
- server.sin_addr=*((struct in_addr *)he->h_addr);
-
- if(-1==connect(connectfd,(struct sockaddr *)&server,sizeof(server))){
- perror("connect() error\n");
- exit(1);
- }
- if(-1==(fd=open(argv[2],O_CREAT|O_WRONLY,S_IRWXU))){
- perror("open() error\n");
- exit(1);
- }
- int len=0;
- char buf[512];
- bzero(buf,sizeof(buf));
- while((len=read(connectfd,buf,sizeof(buf)))>0){
- write(fd,buf,len);
- }
- close(fd);
- close(connectfd);
- return 0;
- }
![](http://blog.chinaunix.net/blog/image/attachicons/rar.gif)