《Linux网络编程example.pdf》由会员分享,可在线阅读,更多相关《Linux网络编程example.pdf(32页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、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 informati
2、on 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 sam
3、ple 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 c
4、ode(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 S
5、IGCHLD)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
6、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 includ
7、e 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*/#inc
8、lude /*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 se
9、rvSock)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,(struc
10、t 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_
11、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 broa
12、dcastAddr;/*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);/*Firs
13、t 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 fami
14、ly*/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 th
15、e 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 /*f
16、or 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 broadc
17、ast 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
18、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);/
19、*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*/broadcas
20、tAddr.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 d
21、atagram 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(
22、),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 sock
23、addr_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;/*Intern
24、et 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 fo
25、r 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()*
26、/#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(clntS
27、ocket,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(
28、)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 /
29、*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 recvStringMAXRE
30、CVSTRING+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(d
31、otted 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*/multicastA
32、ddr.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(bin
33、d()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
34、,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
35、);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
36、 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;/*Len
37、gth 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 spec
38、ified 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_I
39、P,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(
40、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 sockad
41、dr*)&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 co
42、ntaining 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
43、 /*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)fpr
44、intf(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
45、*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=InterruptSig
46、nalHandler;/*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
47、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 mem
48、set()*/#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 po
49、rt*/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)/*Te
50、st 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