http://blog.csdn.net/liang890319/article/details/8372744
代码来自《linux c编程从入门到精通》
代码分为服务器和客户机 基本的操作都有了
服务器建立sock并绑定后等待接收
客户端接受用户输入并发给服务器 服务器收到后返回给客户端
使用时先运行server 然后运行client 在client端输入字符串 并回车就能看到效果了
服务器
外加unistd.h和 string.h
- /*ex8-7.c*/
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <stdio.h>
- #define MAXMSG 1024
- int main()
- {
- int sockfd,nbytes;
- struct sockaddr_in addr;
- socklen_t size;
- char message[MAXMSG];
- sockfd=socket(AF_INET,SOCK_DGRAM,0);
- if(sockfd<0)
- {
- printf("Socket created failed.\n");
- return -1;
- }
- bzero(&addr,sizeof(addr));
- addr.sin_family=AF_INET;
- addr.sin_port=htons(6666);
- addr.sin_addr.s_addr=htonl(INADDR_ANY);
- if(bind(sockfd, (struct sockaddr *)&addr, sizeof(addr))<0)
- {
- printf("bind failed.\n");
- return -1;
- }
- while(1)
- {
- size=sizeof(addr);
- nbytes=recvfrom(sockfd,message,MAXMSG,0,(struct sockaddr *)&addr,&size);
- if(nbytes<0)
- {
- printf("recvfrom(server) failed.\n");
- return -1;
- }
- printf("Server got message %s \n",message);
- nbytes=sendto(sockfd,message,nbytes,0,(struct sockaddr*)&addr,size);
- if(nbytes<0)
- {
- printf("sendto(server) failed.\n");
- return -1;
- }
- }
- }
客户机
- /*ex8-8.c*/
- #include <stdio.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <netdb.h>
- #define MAXMSG 512
- int main()
- {
- int sockfd,n;
- char recvbuff[MAXMSG],sndbuff[MAXMSG];
- struct sockaddr_in servaddr;
- sockfd=socket(AF_INET,SOCK_DGRAM,0);
- if(sockfd<0)
- {
- printf("Socket created failed.\n");
- return -1;
- }
- servaddr.sin_family=AF_INET;
- servaddr.sin_port=htons(6666);
- servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
- while(fgets(sndbuff,MAXMSG,stdin)!=NULL)
- {
- if(sendto(sockfd,sndbuff,sizeof(sndbuff),0,(struct sockaddr*)&servaddr,sizeof(servaddr))<0)
- {
- printf("(client)sending error.\n");
- return -1;
- }
- if((n=recvfrom(sockfd,recvbuff,MAXMSG,0,NULL,NULL))<0)
- {
- printf("(client)receiving error.\n");
- return -1;
- }
- recvbuff[n]=0;
- printf("Client received message: %s",recvbuff);
- }
- close(sockfd);
- return 0;
- }