资源描述:
《udp socket 通信案例》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、#include#include#include#include#include#include#include#include#defineNOR3#defineQUIT2#defineLOG1typedefstructnode{structsockaddr_inaddrc;structnode*next;}linknode,*linklist;typedefstruct{inttype;
2、charname[20];charbuf[1024];}message;linklistCREAT();intmain(intargc,char*argv[]){messagemsg;intsockfd;socklen_tslen;structsockaddr_inaddrs,addrc;linklisth,p,q;h=CREAT();if((sockfd=socket(PF_INET,SOCK_DGRAM,0))<0){perror("socket");exit(-1);}memset(&addrs,0,sizeof(addrs));addrs.sin_family=PF
3、_INET;addrs.sin_addr.s_addr=inet_addr("192.168.0.143");addrs.sin_port=htons(8888);if(bind(sockfd,(structsockaddr*)&addrs,sizeof(addrs))<0){perror("bind");exit(-1);}while(1){slen=sizeof(addrc);recvfrom(sockfd,&msg,sizeof(msg),0,(structsockaddr*)&addrc,&slen);printf("msg.buf=%s,msg.name=%s",
4、msg.buf,msg.name);if(msg.type==LOG){linklistm;m=h->next;p=CREAT();h->next=p;p->next=m;p->addrc=addrc;printf("connectiongfrom%s%d",inet_ntoa(p->addrc.sin_addr),ntohs(p->addrc.sin_port));q=h->next;while(q!=NULL){strcpy(msg.buf,msg.name);strcat(msg.buf,"iscoming");sendto(sockfd,&msg,sizeof(
5、msg),0,(structsockaddr*)&q->addrc,sizeof(q->addrc));q=q->next;}}if(msg.type==NOR){q=h->next;while(q!=NULL){sendto(sockfd,&msg,sizeof(msg),0,(structsockaddr*)&q->addrc,sizeof(q->addrc));q=q->next;}}if(msg.type==QUIT){strcpy(msg.buf,"seeyoulater");sendto(sockfd,&msg,sizeof(msg),0,(structsock
6、addr*)&addrc,sizeof(addrc));delete(addrc,h);strcpy(msg.buf,msg.name);strcat(msg.buf,"isoutline");q=h->next;while(q!=NULL){sendto(sockfd,&msg,sizeof(msg),0,(structsockaddr*)&q->addrc,sizeof(q->addrc));q=q->next;}}}return0;}linklistCREAT(){linklistp;p=(linklist)malloc(sizeof(linknode));p->ne
7、xt=NULL;returnp;}intdelete(structsockaddr_inaddrc,linklistls){linklistm,n,p;m=ls->next;p=ls;if(memcmp(&m->addrc,&addrc,sizeof(addrc))==0){n=m->next;p->next=n;free(m);}m=m->next;p=p->next;}#include#include#include#include#