欢迎来到淘文阁 - 分享文档赚钱的网站! | 帮助中心 好文档才是您的得力助手!
淘文阁 - 分享文档赚钱的网站
全部分类
  • 研究报告>
  • 管理文献>
  • 标准材料>
  • 技术资料>
  • 教育专区>
  • 应用文书>
  • 生活休闲>
  • 考试试题>
  • pptx模板>
  • 工商注册>
  • 期刊短文>
  • 图片设计>
  • ImageVerifierCode 换一换

    Linux网络编程example.pdf

    • 资源ID:70010767       资源大小:84.64KB        全文页数:32页
    • 资源格式: PDF        下载积分:15金币
    快捷下载 游客一键下载
    会员登录下载
    微信登录下载
    三方登录下载: 微信开放平台登录   QQ登录  
    二维码
    微信扫一扫登录
    下载资源需要15金币
    邮箱/手机:
    温馨提示:
    快捷下载时,用户名和密码都是您填写的邮箱或者手机号,方便查询和重复下载(系统自动生成)。
    如填写123,账号就是123,密码也是123。
    支付方式: 支付宝    微信支付   
    验证码:   换一换

     
    账号:
    密码:
    验证码:   换一换
      忘记密码?
        
    友情提示
    2、PDF文件下载后,可能会被浏览器默认打开,此种情况可以点击浏览器菜单,保存网页到桌面,就可以正常下载了。
    3、本站不支持迅雷下载,请使用电脑自带的IE浏览器,或者360浏览器、谷歌浏览器下载即可。
    4、本站资源下载后的文档和图纸-无水印,预览文档经过压缩,下载后原文更清晰。
    5、试题试卷类文档,如果标题没有明确说明有答案则都视为没有答案,请知晓。

    Linux网络编程example.pdf

    Below is the example source code from TCP/IP Sockets in C:Practical Guide for Programmers by Michael J.Donahoo and Kenneth L.Calvert.This book can be ordered at your favorite local bookstore or online.Official Book WebsiteDisclaimer:Disclaimer:The purpose of this book is to provide general information about network programming as of the books publication date.The authors have included sample code that is intended for the sole purpose of illustrating the use of the sockets API.Neither the authors nor the publisher are aware of any third party patents or proprietary rights that may cover any sample of any kind.The authors and the Publisher DISCLAIM ALL EXPRESS AND IMPLIED WARRANTIES,including warranties of merchantability and fitness for any particular purpose.Your use or reliance upon any sample code or other information in this book will be at your own risk.No one should use any sample code(or illustrations)from this book in any software application without first obtaining competent legal advice.Example code:TCPEchoClient.cDieWithError.cTCPEchoServer.cHandleTCPClient.cUDPEchoClient.cUDPEchoServer.cSigAction.cUDPEchoServer-SIGIO.cUDPEchoClient-Timeout.cTCPEchoServer-Fork.c(without SIGCHLD)TCPEchoServer-Fork-SIGCHLD.c(with SIGCHLD)TCPEchoServer.hCreateTCPServerSocket.cAcceptTCPConnection.cTCPEchoServer-Thread.cTCPEchoServer-ForkN.cTCPEchoServer-Select.cBroadcastSender.cBroadcastReceiver.cMulticastSender.cMulticastReceiver.cResolveName.cResolveService.c Generally,compilation is as follows:Linux:gcc-o TCPEchoClient TCPEchoClient.c DieWithError.c Solaris:gcc-o TCPEchoClient TCPEchoClient.c DieWithError.c-lsocket-lnsl Both:Add-lpthread to both Linux and Solaris for the threads example Note for older machines(e.g.,SVR4 variants such as Solaris 2.5 and before):A few more include files may be necessary.If you get compile errors about u_short,try editing the include files as follows(order mattersorder matters):#include /*for printf()and fprintf()*/#include /*for Socket data types*/#include /*for socket(),connect(),send(),and recv()*/#include /*for IP Socket data types*/#include /*for sockaddr_in and inet_addr()*/#include /*for atoi()*/#include /*for memset()*/#include /*for close()*/#include /*for printf()*/#include /*for accept()*/#include /*for sockaddr_in and inet_ntoa()*/void DieWithError(char*errorMessage);/*Error handling function*/int AcceptTCPConnection(int servSock)int clntSock;/*Socket descriptor for client*/struct sockaddr_in echoClntAddr;/*Client address*/unsigned int clntLen;/*Length of client address data structure*/*Set the size of the in-out parameter*/clntLen=sizeof(echoClntAddr);/*Wait for a client to connect*/if(clntSock=accept(servSock,(struct sockaddr*)&echoClntAddr,&clntLen)0)DieWithError(accept()failed);/*clntSock is connected to a client!*/printf(Handling client%sn,inet_ntoa(echoClntAddr.sin_addr);return clntSock;#include /*for printf()and fprintf()*/#include /*for socket(),connect(),sendto(),and recvfrom()*/#include /*for sockaddr_in and inet_addr()*/#include /*for atoi()and exit()*/#include /*for memset()*/#include /*for close()*/#define MAXRECVSTRING 255 /*Longest string to receive*/void DieWithError(char*errorMessage);/*External error handling function*/int main(int argc,char*argv)int sock;/*Socket*/struct sockaddr_in broadcastAddr;/*Broadcast Address*/unsigned short broadcastPort;/*Port*/char recvStringMAXRECVSTRING+1;/*Buffer for received string*/int recvStringLen;/*Length of received string*/if(argc!=2)/*Test for correct number of arguments*/fprintf(stderr,Usage:%s n,argv0);exit(1);broadcastPort=atoi(argv1);/*First arg:broadcast port*/*Create a best-effort datagram socket using UDP*/if(sock=socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP)0)DieWithError(socket()failed);/*Construct bind structure*/memset(&broadcastAddr,0,sizeof(broadcastAddr);/*Zero out structure*/broadcastAddr.sin_family=AF_INET;/*Internet address family*/broadcastAddr.sin_addr.s_addr=htonl(INADDR_ANY);/*Any incoming interface*/broadcastAddr.sin_port=htons(broadcastPort);/*Broadcast port*/*Bind to the broadcast port*/if(bind(sock,(struct sockaddr*)&broadcastAddr,sizeof(broadcastAddr)0)DieWithError(bind()failed);/*Receive a single datagram from the server*/if(recvStringLen=recvfrom(sock,recvString,MAXRECVSTRING,0,NULL,0)0)DieWithError(recvfrom()failed);recvStringrecvStringLen=0;printf(Received:%sn,recvString);/*Print the received string*/close(sock);exit(0);#include /*for printf()and fprintf()*/#include /*for socket()and bind()*/#include /*for sockaddr_in*/#include /*for atoi()and exit()*/#include /*for memset()*/#include /*for close()*/void DieWithError(char*errorMessage);/*External error handling function*/int main(int argc,char*argv)int sock;/*Socket*/struct sockaddr_in broadcastAddr;/*Broadcast address*/char*broadcastIP;/*IP broadcast address*/unsigned short broadcastPort;/*Server port*/char*sendString;/*String to broadcast*/int broadcastPermission;/*Socket opt to set permission to broadcast*/unsigned int sendStringLen;/*Length of string to broadcast*/if(argc 4)/*Test for correct number of parameters*/fprintf(stderr,Usage:%s n,argv0);exit(1);broadcastIP=argv1;/*First arg:broadcast IP address*/broadcastPort=atoi(argv2);/*Second arg:broadcast port*/sendString=argv3;/*Third arg:string to broadcast*/*Create socket for sending/receiving datagrams*/if(sock=socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP)0)DieWithError(socket()failed);/*Set socket to allow broadcast*/broadcastPermission=1;if(setsockopt(sock,SOL_SOCKET,SO_BROADCAST,(void*)&broadcastPermission,sizeof(broadcastPermission)0)DieWithError(setsockopt()failed);/*Construct local address structure*/memset(&broadcastAddr,0,sizeof(broadcastAddr);/*Zero out structure*/broadcastAddr.sin_family=AF_INET;/*Internet address family*/broadcastAddr.sin_addr.s_addr=inet_addr(broadcastIP);/*Broadcast IP address*/broadcastAddr.sin_port=htons(broadcastPort);/*Broadcast port*/sendStringLen=strlen(sendString);/*Find length of sendString*/for(;)/*Run forever*/*Broadcast sendString in datagram to clients every 3 seconds*/if(sendto(sock,sendString,sendStringLen,0,(struct sockaddr*)&broadcastAddr,sizeof(broadcastAddr)!=sendStringLen)DieWithError(sendto()sent a different number of bytes than expected);sleep(3);/*Avoids flooding the network*/*NOT REACHED*/#include /*for socket(),bind(),and connect()*/#include /*for sockaddr_in and inet_ntoa()*/#include /*for memset()*/#define MAXPENDING 5 /*Maximum outstanding connection requests*/void DieWithError(char*errorMessage);/*Error handling function*/int CreateTCPServerSocket(unsigned short port)int sock;/*socket to create*/struct sockaddr_in echoServAddr;/*Local address*/*Create socket for incoming connections*/if(sock=socket(PF_INET,SOCK_STREAM,IPPROTO_TCP)0)DieWithError(socket()failed);/*Construct local address structure*/memset(&echoServAddr,0,sizeof(echoServAddr);/*Zero out structure*/echoServAddr.sin_family=AF_INET;/*Internet address family*/echoServAddr.sin_addr.s_addr=htonl(INADDR_ANY);/*Any incoming interface*/echoServAddr.sin_port=htons(port);/*Local port*/*Bind to the local address*/if(bind(sock,(struct sockaddr*)&echoServAddr,sizeof(echoServAddr)0)DieWithError(bind()failed);/*Mark the socket so it will listen for incoming connections*/if(listen(sock,MAXPENDING)0)DieWithError(listen()failed);return sock;#include /*for perror()*/#include /*for exit()*/void DieWithError(char*errorMessage)perror(errorMessage);exit(1);#include /*for printf()and fprintf()*/#include /*for recv()and send()*/#include /*for close()*/#define RCVBUFSIZE 32 /*Size of receive buffer*/void DieWithError(char*errorMessage);/*Error handling function*/void HandleTCPClient(int clntSocket)char echoBufferRCVBUFSIZE;/*Buffer for echo string*/int recvMsgSize;/*Size of received message*/*Receive message from client*/if(recvMsgSize=recv(clntSocket,echoBuffer,RCVBUFSIZE,0)0)/*zero indicates end of transmission*/*Echo message back to client*/if(send(clntSocket,echoBuffer,recvMsgSize,0)!=recvMsgSize)DieWithError(send()failed);/*See if there is more data to receive*/if(recvMsgSize=recv(clntSocket,echoBuffer,RCVBUFSIZE,0)0)DieWithError(recv()failed);close(clntSocket);/*Close client socket*/#include /*for printf()and fprintf()*/#include /*for socket(),connect(),sendto(),and recvfrom()*/#include /*for sockaddr_in and inet_addr()*/#include /*for atoi()and exit()*/#include /*for memset()*/#include /*for close()*/#define MAXRECVSTRING 255 /*Longest string to receive*/void DieWithError(char*errorMessage);/*External error handling function*/int main(int argc,char*argv)int sock;/*Socket*/struct sockaddr_in multicastAddr;/*Multicast Address*/char*multicastIP;/*IP Multicast Address*/unsigned short multicastPort;/*Port*/char recvStringMAXRECVSTRING+1;/*Buffer for received string*/int recvStringLen;/*Length of received string*/struct ip_mreq multicastRequest;/*Multicast address join structure*/if(argc!=3)/*Test for correct number of arguments*/fprintf(stderr,Usage:%s n,argv0);exit(1);multicastIP=argv1;/*First arg:Multicast IP address(dotted quad)*/multicastPort=atoi(argv2);/*Second arg:Multicast port*/*Create a best-effort datagram socket using UDP*/if(sock=socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP)0)DieWithError(socket()failed);/*Construct bind structure*/memset(&multicastAddr,0,sizeof(multicastAddr);/*Zero out structure*/multicastAddr.sin_family=AF_INET;/*Internet address family*/multicastAddr.sin_addr.s_addr=htonl(INADDR_ANY);/*Any incoming interface*/multicastAddr.sin_port=htons(multicastPort);/*Multicast port*/*Bind to the multicast port*/if(bind(sock,(struct sockaddr*)&multicastAddr,sizeof(multicastAddr)0)DieWithError(bind()failed);/*Specify the multicast group*/multicastRequest.imr_multiaddr.s_addr=inet_addr(multicastIP);/*Accept multicast from any interface*/multicastRequest.imr_interface.s_addr=htonl(INADDR_ANY);/*Join the multicast address*/if(setsockopt(sock,IPPROTO_IP,IP_ADD_MEMBERSHIP,(void*)&multicastRequest,sizeof(multicastRequest)0)DieWithError(setsockopt()failed);/*Receive a single datagram from the server*/if(recvStringLen=recvfrom(sock,recvString,MAXRECVSTRING,0,NULL,0)0)DieWithError(recvfrom()failed);recvStringrecvStringLen=0;printf(Received:%sn,recvString);/*Print the received string*/close(sock);exit(0);#include /*for fprintf()*/#include /*for socket(),connect(),send(),and recv()*/#include /*for sockaddr_in and inet_addr()*/#include /*for atoi()and exit()*/#include /*for memset()*/#include /*for sleep()*/void DieWithError(char*errorMessage);/*External error handling function*/int main(int argc,char*argv)int sock;/*Socket*/struct sockaddr_in multicastAddr;/*Multicast address*/char*multicastIP;/*IP Multicast address*/unsigned short multicastPort;/*Server port*/char*sendString;/*String to multicast*/unsigned char multicastTTL;/*TTL of multicast packets*/unsigned int sendStringLen;/*Length of string to multicast*/if(argc 5)/*Test for correct number of parameters*/fprintf(stderr,Usage:%s n,argv0);exit(1);multicastIP=argv1;/*First arg:multicast IP address*/multicastPort=atoi(argv2);/*Second arg:multicast port*/sendString=argv3;/*Third arg:String to multicast*/if(argc=5)/*Is TTL specified on command-line?*/multicastTTL=atoi(argv4);/*Command-line specified TTL*/else multicastTTL=1;/*Default TTL=1*/*Create socket for sending/receiving datagrams*/if(sock=socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP)0)DieWithError(socket()failed);/*Set TTL of multicast packet*/if(setsockopt(sock,IPPROTO_IP,IP_MULTICAST_TTL,(void*)&multicastTTL,sizeof(multicastTTL)0)DieWithError(setsockopt()failed);/*Construct local address structure*/memset(&multicastAddr,0,sizeof(multicastAddr);/*Zero out structure*/multicastAddr.sin_family=AF_INET;/*Internet address family*/multicastAddr.sin_addr.s_addr=inet_addr(multicastIP);/*Multicast IP address*/multicastAddr.sin_port=htons(multicastPort);/*Multicast port*/sendStringLen=strlen(sendString);/*Find length of sendString*/for(;)/*Run forever*/*Multicast sendString in datagram to clients every 3 seconds*/if(sendto(sock,sendString,sendStringLen,0,(struct sockaddr*)&multicastAddr,sizeof(multicastAddr)!=sendStringLen)DieWithError(sendto()sent a different number of bytes than expected);sleep(3);/*NOT REACHED*/#include /*for fprintf()*/#include /*for gethostbyname()*/#include /*for exit()*/unsigned long ResolveName(char name)struct hostent*host;/*Structure containing host information*/if(host=gethostbyname(name)=NULL)fprintf(stderr,gethostbyname()failed);exit(1);/*Return the binary,network byte ordered address*/return*(unsigned long*)host-h_addr_list0);#include /*for printf()and fprintf()*/#include /*for htons()*/#include /*for getservbyname()*/#include /*for atoi()*/unsigned short ResolveService(char service,char protocol)struct servent*serv;/*Structure containing service information*/unsigned short port;/*Port to return*/if(port=atoi(service)=0)/*Is port numeric?*/*Not numeric.Try to find as name*/if(serv=getservbyname(service,protocol)=NULL)fprintf(stderr,getservbyname()failed);exit(1);else port=serv-s_port;/*Found port(network byte order)by name*/else port=htons(port);/*Convert port to network byte order*/return port;#include /*for printf()*/#include /*for sigaction()*/#include /*for pause()*/#include /*for exit()*/void DieWithError(char*errorMessage);/*Error handling function*/void InterruptSignalHandler(int signalType);/*Interrupt signal handling function*/int main(int argc,char*argv)struct sigaction handler;/*Signal handler specification structure*/*Set InterruptSignalHandler()as handler function*/handler.sa_handler=InterruptSignalHandler;/*Create mask that mask all signals*/if(sigfillset(&handler.sa_mask)0)DieWithError(sigfillset()failed);/*No flags*/handler.sa_flags=0;/*Set signal handling for interrupt signals*/if(sigaction(SIGINT,&handler,0)0)DieWithError(sigaction()failed);for(;)pause();/*suspend program until signal received*/exit(0);void InterruptSignalHandler(int signalType)printf(Interrupt Received.Exiting program.n);exit(1);#include /*for printf()and fprintf()*/#include /*for socket(),connect(),send(),and recv()*/#include /*for sockaddr_in and inet_addr()*/#include /*for atoi()and exit()*/#include /*for memset()*/#include /*for close()*/#define RCVBUFSIZE 32 /*Size of receive buffer*/void DieWithError(char*errorMessage);/*Error handling function*/int main(int argc,char*argv)int sock;/*Socket descriptor*/struct sockaddr_in echoServAddr;/*Echo server address*/unsigned short echoServPort;/*Echo server port*/char*servIP;/*Server IP address(dotted quad)*/char*echoString;/*String to send to echo server*/char echoBufferRCVBUFSIZE;/*Buffer for echo string*/unsigned int echoStringLen;/*Length of string to echo*/int bytesRcvd,totalBytesRcvd;/*Bytes read in single recv()and total bytes read*/if(argc 4)/*Test for correct number of arguments*/fprintf(stderr,Usage:%s n,argv0);exit(1);servIP=argv1;/*First arg:server IP address(dotted quad)*/echoString=argv2;/*Second arg:string to echo*/if(argc=4)echoServPort=atoi(argv3);/*Use given port,if any*/else echoServPort=7;/*7 is the well-known port for the echo

    注意事项

    本文(Linux网络编程example.pdf)为本站会员(qwe****56)主动上传,淘文阁 - 分享文档赚钱的网站仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。 若此文所含内容侵犯了您的版权或隐私,请立即通知淘文阁 - 分享文档赚钱的网站(点击联系客服),我们立即给予删除!

    温馨提示:如果因为网速或其他原因下载失败请重新下载,重复下载不扣分。




    关于淘文阁 - 版权申诉 - 用户使用规则 - 积分规则 - 联系我们

    本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知淘文阁网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

    工信部备案号:黑ICP备15003705号 © 2020-2023 www.taowenge.com 淘文阁 

    收起
    展开