服务器
1、建立连接
socket(),分配文件描述符,即监听套接字
bind(),将套接字与本地IP地址和端口绑定
2、数据收发
recvfrom()阻塞等待客户端发送数据
sendto()将处理结果发送给客户端
3、关闭连接
close()关闭套接字
客户端
1、建立连接
socket(),分配文件描述符
2、数据收发
sendto()发送信息给服务端
recvfrom()阻塞等待服务端返回送数据
3、关闭连接
close()关闭套接字
UDP通信
示例代码
头文件:header.h
#ifndef _STD_
#define _STD_
// 头文件 //
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
//tcp//
#include
#include
#include
#include
#include
//错误提示//
#define err_exit(function) \
do { \
fprintf(stderr, "in %s at %s %d:\n%s : %s\n", __FUNCTION__, __FILE__, __LINE__ - 1, function, strerror(errno)); \
exit(EXIT_FAILURE); \
} while(0)
#endif
服务端:test_udp_server.c
#include "header.h"
int main(int argc, char *argv[])
{
int sockfd = -1;
struct sockaddr_in server,client;
char buf[BUFSIZ];
//初始化套接字地址结构体
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;//IPv4
server.sin_port = htons(888);//设置端口号
server.sin_addr.s_addr = htonl(INADDR_ANY);//INADDR_ANY接收任意IP的请求
//创建套接字
if (0 > (sockfd = socket(AF_INET, SOCK_DGRAM, 0)))
err_exit("socket");
//绑定套接字和本地IP地址和端口
if(0 > bind(sockfd, (struct sockaddr *)&server, sizeof(server)))
err_exit("bind");
//初始化客户端套接字地址
bzero(&client, sizeof(client));
socklen_t len = sizeof(client);
while(1)
{
//接受客户端发来的信息
memset(buf, 0, sizeof(buf));
recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&client, &len);
printf("client's ip is: %s, port is: %d\n", inet_ntoa(client.sin_addr), ntohs(client.sin_port));
printf("client:%s\n", buf);
//向客户端发送信息
memset(buf, 0, sizeof(buf));
fgets(buf, sizeof(buf), stdin);
sendto(sockfd, buf, strlen(buf) + 1, MSG_NOSIGNAL, (struct sockaddr *)&client, sizeof(client));
}
close(sockfd);
exit(0);
}
客户端:test_udp_client.c
#include "header.h"
int main(int argc, char *argv[])
{
int sockfd = -1;
struct sockaddr_in server;
char buf[BUFSIZ];
//初始化服务器套接字地址
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;//IPv4
server.sin_port = htons(888);//服务器端口
server.sin_addr.s_addr = inet_addr("192.168.1.50");//指定服务器IP地址
//server.sin_addr.s_addr = htonl(INADDR_ANY);//INADDR_ANY接收任意IP的请求
socklen_t len = sizeof(server);
//创建套接字
if (0 > (sockfd = socket(AF_INET, SOCK_DGRAM, 0)))
err_exit("socket");
while(1)
{
//向服务器发送信息
memset(buf, 0, sizeof(buf));
fgets(buf, sizeof(buf), stdin);
sendto(sockfd, buf, strlen(buf) + 1, MSG_NOSIGNAL, (struct sockaddr *)&server, sizeof(server));
//接收服务器信息
recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&server, &len);
printf("server's ip is: %s, port: is %d\n", inet_ntoa(server.sin_addr), ntohs(server.sin_port));
printf("server:%s\n", buf);
}
close(sockfd);
exit(0);
}