Simple network programming example (Windows and Linux)

Source: Internet
Author: User
Document directory
  • Server:
  • Client:
  • Server:
  • Client:
  • Server:
  • Client:
Windows: TCP communication:

// Client # include <winsock2.h> # include <stdio. h> void main () {word wversionrequested; wsadata; int err; wversionrequested = makeword (1, 1); err = wsastartup (wversionrequested, & wsadata); If (Err! = 0) {return;} If (lobyte (wsadata. wversion )! = 1 | hibyte (wsadata. wversion )! = 1) {wsacleanup (); Return ;}// create Socket socket sockclient = socket (af_inet, sock_stream, 0); sockaddr_in addrsrv; addrsrv. sin_addr.s_un.s_addr = inet_addr ("127.0.0.1"); addrsrv. sin_family = af_inet; addrsrv. sin_port = htons (8000); Connect (sockclient, (sockaddr *) & addrsrv, sizeof (sockaddr); // receives data; char recvbuf [100]; Recv (sockclient, recvbuf, 100,0); printf ("Recv: % s", recvbuf); send (sockclient, "this is the c Lient ", strlen (" this is the client ") + 1, 0); closesocket (sockclient); wsacleanup ();} // server. CPP # include <winsock2.h> # include <stdio. h> void main () {// word wversionreguested; wsadata; int err; wversionreguested = makeword (1, 1); err = wsastartup (wversionreguested, & wsadata ); if (Err! = 0) {return;} If (lobyte (wsadata. wversion )! = 1 | hibyte (wsadata. wversion )! = 1) {wsacleanup (); return;} socket socksrv = socket (af_inet, sock_stream, 0); sockaddr_in addrsrv; addrsrv. sin_addr.s_un.s_addr = htonl (inaddr_any); addrsrv. sin_family = af_inet; addrsrv. sin_port = htons (8000); // bind the socket (socksrv, (sockaddr *) & addrsrv, sizeof (sockaddr); Listen (socksrv, 5); sockaddr_in addrclient; int Len = sizeof (sockaddr); While (1) {// wait for the customer's request to arrive; socket sockconn = accept (socksrv, (so Ckaddr *) & addrclient, & Len); char sendbuf [100]; sprintf (sendbuf, "welcom % s here! \ N ", inet_ntoa (addrclient. sin_addr); // send data (sockconn, sendbuf, strlen (sendbuf) + 100); char recvbuf []; Recv (sockconn, recvbuf, 0 ); printf ("Recv: % s \ n", recvbuf); closesocket (sockconn );}}

UDP Communication Server:

#include <stdio.h>#include "winsock2.h"void server() {WSADATA wsaData;SOCKET RecvSocket;sockaddr_in RecvAddr;int Port = 27015;char RecvBuf[1024];int  BufLen = 1024;sockaddr_in SenderAddr;int SenderAddrSize = sizeof(SenderAddr);//-----------------------------------------------// Initialize WinsockWSAStartup(MAKEWORD(2,2), &wsaData);//-----------------------------------------------// Create a receiver socket to receive datagramsRecvSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);//-----------------------------------------------// Bind the socket to any address and the specified port.RecvAddr.sin_family = AF_INET;RecvAddr.sin_port = htons(Port);RecvAddr.sin_addr.s_addr = htonl(INADDR_ANY);bind(RecvSocket, (SOCKADDR *) &RecvAddr, sizeof(RecvAddr));//-----------------------------------------------// Call the recvfrom function to receive datagrams// on the bound socket.printf("Receiving datagrams...\n");while(1){memset(RecvBuf,0,sizeof(RecvBuf)) ;recvfrom(RecvSocket, RecvBuf, BufLen, 0, (SOCKADDR *)&SenderAddr, &SenderAddrSize);printf("from:%s::%s\n",inet_ntoa(SenderAddr.sin_addr),RecvBuf);}//-----------------------------------------------// Close the socket when finished receiving datagramsprintf("Finished receiving. Closing socket.\n");closesocket(RecvSocket);//-----------------------------------------------// Clean up and exit.printf("Exiting.\n");WSACleanup();return;}

Client:

void client() {WSADATA wsaData;SOCKET SendSocket;sockaddr_in RecvAddr;int Port = 27015;char SendBuf[1024];int BufLen = 1024;//---------------------------------------------// Initialize WinsockWSAStartup(MAKEWORD(2,2), &wsaData);//---------------------------------------------// Create a socket for sending dataSendSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);//---------------------------------------------// Set up the RecvAddr structure with the IP address of// the receiver (in this example case "123.456.789.1")// and the specified port number.RecvAddr.sin_family = AF_INET;RecvAddr.sin_port = htons(Port);RecvAddr.sin_addr.s_addr = inet_addr("10.33.28.230");//---------------------------------------------// Send a datagram to the receiverprintf("Sending a datagram to the receiver...\n");while(1){int n = scanf("%s",SendBuf);int res = sendto(SendSocket, SendBuf, n, 0, (SOCKADDR *) &RecvAddr, sizeof(RecvAddr));if(res==n){printf("send OK\n");}}//---------------------------------------------// When the application is finished sending, close the socket.printf("Finished sending. Closing socket.\n");closesocket(SendSocket);//---------------------------------------------// Clean up and quit.printf("Exiting.\n");WSACleanup();return;}
Linux UDP Server:

#include <stdio.h>#include <sys/types.h>          /* See NOTES */#include <sys/socket.h>#include <netinet/in.h>#include <string.h>#include <errno.h>#include <unistd.h>#include <fcntl.h>typedef struct sockaddr_in sockaddr_in ;typedef struct sockaddr sockaddr ;static inline int nonblock(int fd) {int opt;opt = fcntl(fd, F_GETFL);opt |= O_NONBLOCK;return fcntl(fd, F_SETFL, opt);}static inline int myblock(int fd) {int opt;opt = fcntl(fd, F_GETFL);opt &= ~O_NONBLOCK;return fcntl(fd, F_SETFL, opt);}int main(int argc ,char ** argv){sockaddr_in srv ,cli ;int sfd ;if((sfd=socket(AF_INET ,SOCK_DGRAM,0))==-1){perror("socket error:");return -1 ;}if(argc < 2){printf("please input argc with port num!");return -1 ;}memset(&srv,0,sizeof(srv));srv.sin_port = htons(atoi(argv[1]));srv.sin_family = AF_INET ;srv.sin_addr.s_addr = INADDR_ANY ;int bfd = bind(sfd , (sockaddr*)&srv,sizeof(sockaddr)) ;if(bfd==-1){perror("bind error:");return -1 ;}   char buf[1024] ;int len ,flags;static int count ;flags = MSG_WAITALL ;while(1){memset(buf,0,sizeof(buf));len = sizeof(cli);int rs,sum=0;/*              fcntl(sfd,F_SETFL,O_NONBLOCK);*/flags = 0 ; while((rs = recvfrom(sfd,buf,sizeof(buf)-1,flags,(sockaddr*)&cli,&len))>0){printf("%s",buf);sum+=rs ;nonblock(sfd);}   printf("\n");myblock(sfd);/*fcntl(sfd,F_SETFL,O_NONBLOCK);*/printf("recv size:%d",sum);if(rs<0 && errno!=EAGAIN){perror("recvfrom:");continue ;}   printf("recv %d bytes from %s,contents:%s,count:=%d\n", rs,inet_ntoa(cli.sin_addr),buf,count++);}   close(sfd);    return 0;}

Client:

#include <stdio.h>#include <sys/types.h>          /* See NOTES */#include <sys/socket.h>#include <netinet/in.h>#include <string.h>#include <unistd.h>typedef struct sockaddr_in sockaddr_in ;typedef struct sockaddr sockaddr ;int main(int argc ,char ** argv){sockaddr_in srv ,cli ;int sfd ;if((sfd=socket(AF_INET ,SOCK_DGRAM,0))==-1){perror("socket error:");return -1 ;}if(argc < 3){printf("the argcs like : ./a.out ipaddr serverport  ");return -1 ;}memset(&srv,0,sizeof(srv));srv.sin_port = htons(atoi(argv[2]));srv.sin_family = AF_INET ;inet_aton(argv[1],&srv.sin_addr);char buf[1024] ;int len,snu,re;int64_t i ;/*      for(i=0;i<1000*1000*1000;i++){memset(buf,0,sizeof(buf)) ;sprintf(buf,"%d",i);snu = sendto(sfd,buf,strlen(buf),0,(sockaddr*)&srv,sizeof(sockaddr)) ;     }*/while(1){bzero(buf,sizeof(buf));re = read(STDIN_FILENO ,buf,sizeof(buf));snu = sendto(sfd,buf,re-1,0,(sockaddr*)&srv,sizeof(sockaddr)) ;printf("send %d bytes\n",snu);}close(sfd);return 0;}

TCP Server:

#include <stdio.h>#include <sys/types.h>          /* See NOTES */#include <sys/socket.h>#include <netinet/in.h>#include <fcntl.h>#include <string.h>#include <errno.h>#include <unistd.h>typedef struct sockaddr_in sockaddr_in ;typedef struct sockaddr sockaddr ;static inline int nonblock(int fd) {int opt;opt = fcntl(fd, F_GETFL);opt |= O_NONBLOCK;return fcntl(fd, F_SETFL, opt);}int main(int argc ,char ** argv){sockaddr_in srv ,cli ;int sfd ,sfd2;if((sfd=socket(AF_INET ,SOCK_STREAM,0))==-1){perror("socket error:");return -1 ;}if(argc < 2){printf("please input argc with port num!");return -1 ;}memset(&srv,0,sizeof(srv));srv.sin_port = htons(atoi(argv[1]));srv.sin_family = AF_INET ;srv.sin_addr.s_addr = INADDR_ANY ;int yes = 1;if (-1  == setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &yes,sizeof(int))) {close(sfd);return -1;}   int bfd = bind(sfd , (sockaddr*)&srv,sizeof(sockaddr)) ;if(bfd==-1){perror("bind error:");return -1 ;}   listen(sfd, 20) ;char buf[1024] ;int len ;while(1){len = sizeof(sockaddr);sfd2 = accept(sfd,(sockaddr*)&cli,&len);printf("accept a sock\n");memset(buf,0,sizeof(buf));nonblock(sfd2);while(1){int rs ;while(( rs = recv(sfd2,buf,20,MSG_WAITALL))>0){printf("%s",buf) ;}   if(rs<0&&errno==EAGAIN){continue;}   printf("over\n");if(rs==0 || rs<0 )break;}   }   close(sfd);    return 0;}

Client:

#include <stdio.h>#include <sys/types.h>          /* See NOTES */#include <sys/socket.h>#include <netinet/in.h>#include <string.h>#include <unistd.h>typedef struct sockaddr_in sockaddr_in ;typedef struct sockaddr sockaddr ;int main(int argc ,char ** argv){sockaddr_in srv ,cli ;int sfd ;if((sfd=socket(AF_INET ,SOCK_STREAM,0))==-1){perror("socket error:");return -1 ;}if(argc < 3){printf("the argcs like : ./a.out ipaddr serverport ");return -1 ;}memset(&srv,0,sizeof(srv));srv.sin_port = htons(atoi(argv[2]));srv.sin_family = AF_INET ;inet_aton(argv[1],&srv.sin_addr);char buf[1024] ;int len,i ,snu,re;int sfd2 = connect(sfd,(sockaddr*)&srv,sizeof(sockaddr));if(sfd2 !=0){perror("");return -1;}while(1){bzero(buf,sizeof(buf));re = read(STDIN_FILENO ,buf,sizeof(buf));snu = send(sfd,buf,re-1,0);}close(sfd);return 0;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.