本次实现的是面向非连接的socket通信方式。其流程为:
1、服务器代码
(1)代码:
/**
* @file: udpserver.c
* @brief: A simple Udp server
* @author: ToakMa <mchgloak1120@163.com>
* @date: 2014/10/09
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#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)程序理解:
程序创建了一个套接字,并绑定在UDP端口9988上。接着recvfrom()系统调用阻塞等待进入的数据包。此时的任何网络设备都可以发送数据给本服务器的UDP9988端口,因为套接字并没有连接到一个特定的主机。当数据到达时,服务器提示发送者的IP和内容。最后关闭套接字。
2、客户端程序
(1)代码:
/**
* @file: udpclient.c
* @brief: A simple Udp server
* @author: ToakMa <mchgloak1120@163.com>
* @date: 2014/10/09
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#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;
}
(2)程序理解:
程序创建一个套接字,并通过sendto()系统调用发送到指定的UDP端口。
3、测试
当然,程序也可以通过send()和recv()系统调用来实现。
写这些没有讲解原理,因为有很多书写的很好了,可以去看下先关的书籍。分享,沉淀。
程序源代码:http://www.oschina.net/code/snippet_1241861_39182