/*
============================================================================
Name : UDPserver.c
Author : vestinfo
Version : 1.1
Copyright : www.cnblogs.com/vestinfo
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
#define MAXLENGTH 256
int main(int argc,char *argv[])
{
int sockfd;
char msg[MAXLENGTH];
struct sockaddr_in servaddr;
struct sockaddr_in cliaddr;
socklen_t addr_len;
addr_len = sizeof(cliaddr);
/* 创建套接字 */
if((sockfd = socket(AF_INET,SOCK_DGRAM,0)) < 0)
{
perror("error");
exit(1);
}
/* 绑定server的端口 */
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(LOCALPORT);
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
{
perror("error");
exit(1);
}
printf("UDP server waiting for client...\n");
while(1)
{
bzero(msg, MAXLENGTH);
recvfrom(sockfd, msg, MAXLENGTH, 0, (struct sockaddr *)&cliaddr, &addr_len); //接收来自client的msg
printf("Received message from:%s\n",inet_ntoa(cliaddr.sin_addr));
printf("The message Received from client:%s",msg);
sendto(sockfd, msg, sizeof(msg), 0, (struct sockaddr *)&cliaddr, addr_len); //发送msg给client
}
}