通过C语言实现一个简单的Udp服务器,使用与Linux平台。
1.[文件] udpserver.c ~ 1KB 下载(38)
/**
*@file: udpserver.c
*@brief: A simple Udp server
*@author: ToakMa
*@date:2014/10/09
*/
#include
#include
#include
#include
#include
#include
#include
#include
#define PORT 9988
#define BUFF_SIZE 1024
int main(int argc, char *argv[])
{
int sockfd;
int sin_len;
struct sockaddr_in saddr;
struct sockaddr_in remote_addr;
char buff[BUFF_SIZE];
int res, len;
//1. create socket
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (-1 == sockfd)
{
perror("Udp server socket: ");
return -1;
}
printf("Udp server socket create succ!\n");
//2. prepare IP and port
memset(&saddr, 0, sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_port = htons(PORT);
saddr.sin_addr.s_addr = INADDR_ANY;
bzero(saddr.sin_zero, 8);
//3. bind
res = bind(sockfd, (struct sockaddr *)&saddr, sizeof(saddr));
if (-1 == res)
{
perror("udp server bind: ");
return -1;
}
//4. recvfrom
printf("Wait for a packet ...\n");
sin_len = sizeof(struct sockaddr_in);
len = recvfrom(sockfd, buff, BUFF_SIZE, 0, (struct sockaddr *)&remote_addr, &sin_len);
if (-1 == len)
{
perror("udp server recvform: ");
return -1;
}
buff[len] = '\0';
printf("Recived packet from %s, contents is: %s \n", \
inet_ntoa(remote_addr.sin_addr), buff);
//5. close
close(sockfd);
return 0;
}
2.[文件] udpclient.c ~ 1KB 下载(35)
/**
*@file: udpclient.c
*@brief: A simple Udp server
*@author: ToakMa
*@date:2014/10/09
*/
#include
#include
#include
#include
#include
#include
#include
#include
#define BUFF_SIZE 1024
#define PORT 9988
int main(int argc, char *argv[])
{
int sockfd;
struct sockaddr_in remote_addr;
int len;
char buff[BUFF_SIZE];
//1. create a socket
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (-1 == sockfd)
{
perror("udp client socket: ");
return -1;
}
//2. prepare ip and port
memset(&remote_addr, 0, sizeof(remote_addr));
remote_addr.sin_family = AF_INET;
remote_addr.sin_port = htons(PORT);
remote_addr.sin_addr.s_addr = inet_addr(argv[1]);
bzero(&(remote_addr.sin_zero), 8);
//3. sendto
strcpy(buff, "this a test\n");
printf("sending : %s\n", buff);
len = sendto(sockfd, buff, strlen(buff), 0, (struct sockaddr *)&remote_addr, sizeof(remote_addr));
if (len < 0)
{
perror("udp client sendto :");
return -1;
}
//4. close
close(sockfd);
return 0;
}