资源描述:
《实验9:unix socket编程_password_removed》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、实验9:UNIXSocket编程1、实验目的(1)掌握UNIXSocket工作机制和程序设计方法;(2)掌握UINIX环境C/S、C/M/S结构与工作模式;(3)掌握服务器程序的设计方法;(4)掌握C/S结构程序的设计方法;(5)了解与通过相关文件/etc/hosts,/etc/services,/etc/network。2、实现设备一台装有Windows操作系统和Linux机系统的微机或服务器。3、实验方法与注意事项实验室内的实验环境与系统是共用设施,请不要在系统内做对系统或对其他用户不安全的事情。要求每个同学登录后系统后,要在自己的家目录内容以自己(拼音)
2、名字或学号,创建一个子目录(已有者可以不再创建)。以后所有工作都要在自己的目录内进行。建议以后的实验都在同台计算机上做,这样可以保持连续性。用户要按通常实验要认真书写实验报告。4、实验过程示例1:客户端程序设计#include#include#include#include#include#definerec_length20main(intargc,char**argv){structhostent*hp;structsockaddr_ins
3、in;structservent*sp;charbuf[50];ints,pid;char*service,*dest;if(argc!=1){service=argv[1];dest=argv[2];}else{fprintf(stderr,"NOserviceassigned!Usage:");fprintf(stderr,"%sservice_namedestination!",argv[0]);fprintf(stderr,"Note:service_nameisdefinedin/etc/services");fprintf(stderr
4、,"destinationisdefinedin/etc/hosts");exit(-1);}if((sp=getservbyname(service,"tcp"))==NULL){fprintf(stderr,"Error:getservbyname");exit(-5);}if((hp=gethostbyname(dest))==0){fprintf(stderr,"Error:gethostbyname");exit(-6);}bzero(&sin,sizeof(sin));bcopy(hp->h_addr,&sin.sin_addr,hp->h_l
5、ength);sin.sin_family=hp->h_addrtype;sin.sin_port=sp->s_port;if((s=socket(AF_INET,SOCK_STREAM,0))==-1){fprintf(stderr,"Error:socket");exit(-6);}if(connect(s,&sin,sizeof(sin))==-1){fprintf(stderr,"Error:connect");close(s);exit(-6);}//next2Linebuildrequestmessagepid=getpid();sprintf(b
6、uf,"%5.5d%5.5d%5.5d%5.5d",pid,pid*2,pid*3,pid*4);fprintf(stderr,"%sissendingrequestmessage:%s",argv[0],buf);if(write(s,buf,rec_length)!=rec_length){//toserverfprintf(stderr,"WriteSocketsERROR!");close(s);exit(-1);}if(read(s,buf,rec_length)==0){//getreplayfromserverfprintf(stde
7、rr,"ReadSocketsError");close(s);exit(-2);}printf("%sgetreply:%s",argv[0],buf);close(s);exit(0);}示例2:服务器程序设计。#include#include#include#include#include#definerec_length20main(intargc,char**argv){structsockaddr_insin;structs
8、ervent*sp;ints,ns,p