简单的UDP套接字编程例子
UDP系统调用时序图
简单的UDP例子
-
/*
-
============================================================================
-
Name : UDPserver.c
-
Author : vestinfo
-
Version : 1.1
-
Copyright : Your copyright notice
-
Description : A simple UDP server, Ansi-style
-
============================================================================
-
*/
-
#include <stdio.h>
-
#include <stdlib.h>
-
#include <string.h>
-
#include <netinet/in.h>
-
#include <arpa/inet.h>
-
#include <unistd.h>
-
#include <sys/stat.h>
-
#include <sys/types.h>
-
#include <sys/socket.h>
-
#define LOCALPORT 8888
-
int main(int argc,char *argv[])
-
{
-
int sockfd;
-
struct sockaddr_in addr;
-
char msg[256];
-
int addr_len;
-
if((sockfd=socket(AF_INET,SOCK_DGRAM,0)) < 0)
-
{
-
perror("error");
-
exit(1);
-
}
-
addr_len=sizeof(struct sockaddr);
-
bzero(&addr,sizeof(addr));
-
addr.sin_family = AF_INET;
-
addr.sin_port = htons(LOCALPORT);
-
addr.sin_addr.s_addr = htonl(INADDR_ANY);
-
if(bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
-
{
-
perror("error");
-
exit(1);
-
}
-
printf("UDP server waiting for client...\n");
-
while(1)
-
{
-
bzero(msg,sizeof(msg));
-
recvfrom(sockfd,msg,sizeof(msg),0,(struct sockaddr *)&addr,&addr_len);
-
printf("Received message from:%s\n",inet_ntoa(addr.sin_addr));
-
printf("The message Received from client:%s",msg);
-
sendto(sockfd,msg,sizeof(msg),0,(struct sockaddr *)&addr,addr_len);
-
}
-
}