网络编程(三)---数据报套接字
1、sendto函数向数据报套接字发送数据包;
int sendto(int sockfd, void* buffer, size_t size, int flags, struct sockaddr* to, size_t addrlen);
2、recvfrom函数从数据报套接字读数据包,同时报告该包从何而来;
int recvfrom(int sockfd, void * buffer, size_t size, int flags, struct sockaddr * to, size_t * addrlen);
3、流程:
4、例子:
(1) DgramSocketClient.c: 数据包通信客户机程序
/* * DgramSocketClient.c * * Created on: Sep 1, 2013 * Author: root */ #include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <unistd.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; }
(2) DgramSocketServer.c: 数据报通信服务器程序。
/* * DgramSocketServer.c * * Created on: Sep 1, 2013 * Author: root */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <stdio.h> #define MAXMSG 1024 int main(){ int sockfd, size, nbytes; struct sockaddr_in addr; 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; } printf("listening...\n"); 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; } } }
启动服务器程序,然后启动客户端程序,输入信息回车给服务器发送消息;然后启动另外一个客户端,输入信息回车也给服务器发送消息。从服务器程序的输出结果可以看出,它收到了这两个客户发来的消息,并且接收消息的顺序是数据报到达的顺序。具体运行结果如下: