资源描述:
《TCP协议网络编程实例.doc》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、服务器端程序CODE: [Copytoclipboard]--------------------------------------------------------------------------------/*******服务器程序 (server.c)************/#include#include#include#include#include#include#include#include#incl
2、ude#includeintmain(intargc,char*argv[]){ intsockfd,new_fd; structsockaddr_inserver_addr; structsockaddr_inclient_addr; intsin_size,portnumber; charhello[]="Hello!AreYouFine?"; if(argc!=2) { fprintf(stderr,"Usage:%spo
3、rtnumbera",argv[0]); exit(1); } if((portnumber=atoi(argv[1]))<0) { fprintf(stderr,"Usage:%sportnumbera",argv[0]); exit(1); } /*服务器端开始建立socket描述符*/ if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1) {
4、 fprintf(stderr,"Socketerror:%sa",strerror(errno)); exit(1); } /*服务器端填充sockaddr结构 */ bzero(&server_addr,sizeof(structsockaddr_in)); server_addr.sin_family=AF_INET; server_addr.sin_addr.s_addr=htonl(INADDR_ANY); server_addr.sin_port=htons(portnumbe
5、r); /*捆绑sockfd描述符 */ if(bind(sockfd,(structsockaddr*)(&server_addr),sizeof(structsockaddr))==-1) { fprintf(stderr,"Binderror:%sa",strerror(errno)); exit(1); } /*监听sockfd描述符 */ if(listen(sockfd,5)==-1) { fprintf(st
6、derr,"Listenerror:%sa",strerror(errno)); exit(1); } while(1) { /*服务器阻塞,直到客户程序建立连接 */ sin_size=sizeof(structsockaddr_in); if((new_fd=accept(sockfd,(structsockaddr*)(&client_addr),&sin_size))==-1) {
7、 fprintf(stderr,"Accepterror:%sa",strerror(errno)); exit(1); } fprintf(stderr,"Servergetconnectionfrom%s", inet_ntoa(clien