UDP编程
本文内容来源于《TCP/IP网络编程第六章》。主要需要了解UDP常用两个函数:sendto()和recvfrom(),其中两个函数调用次数要相同,如下面例子所示: server端
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#define BUF_SIZE 30
void error_handling(char * message);
int main(int argc,char *argv[]){
int sock;
char message[BUF_SIZE];
int str_len,i;
socklen_t adr_sz;
struct sockaddr_in my_adr,your_adr;
if(argc!=2){
printf("usage : %s <port>\n",argv[0]);
exit(1);
}
sock = socket(PF_INET,SOCK_DGRAM,0);
if(sock == -1)
error_handling("UDP socket creation error");
memset(&my_adr,0,sizeof(my_adr));
my_adr.sin_family = AF_INET;
my_adr.sin_addr.s_addr=htonl(INADDR_ANY);
my_adr.sin_port=htons(atoi(argv[1]));
if(bind(sock,(struct sockaddr*)&my_adr,sizeof(my_adr))==-1)
error_handling("bind() error");
for(i=0;i<3;i++){
sleep(5);
adr_sz = sizeof(your_adr);
str_len=recvfrom(sock,message,BUF_SIZE,0,(struct sockaddr*)&your_adr,&adr_sz);
printf("message %d: %s\n",i+1,message);
}
close(sock);
return 0;
}
void error_handling(char *message){
fputs(message,stderr);
fputc('\n',stderr);
exit(1);
}
客户端
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#define BUF_SIZE 30
void error_handling(char * message);
int main(int argc,char *argv[]){
int sock;
char msg1[] = "Hi!";
char msg2[]="I 'm zzy";
char msg3[] = "Nicw to meet you";
socklen_t your_adr_sz;
struct sockaddr_in your_adr;
if(argc!=3){
printf("usage : %s <port>\n",argv[0]);
exit(1);
}
sock = socket(PF_INET,SOCK_DGRAM,0);
if(sock == -1)
error_handling("socket() error");
memset(&your_adr,0,sizeof(your_adr));
your_adr.sin_family = AF_INET;
your_adr.sin_addr.s_addr=inet_addr(argv[1]);
your_adr.sin_port=htons(atoi(argv[2]));
sendto(sock,msg1,sizeof(msg1),0,(struct sockaddr*)&your_adr,sizeof(your_adr));
sendto(sock,msg2,sizeof(msg2),0,(struct sockaddr*)&your_adr,sizeof(your_adr));
sendto(sock,msg3,sizeof(msg3),0,(struct sockaddr*)&your_adr,sizeof(your_adr));
close(sock);
return 0;
}
void error_handling(char *message){
fputs(message,stderr);
fputc('\n',stderr);
exit(1);
}
|