Linux网络编程-UDP单播服务客户端代码实现
1、服务端
只接收一个字符串
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define BUF_SIZE 88
#define PORT 55555
int main(int argc, char *argv[])
{
//建立套接字
int sock_fd = socket(AF_INET, SOCK_DGRAM, 0); //IPV4,数据报套接字类型,不指定协议
//说明本服务器地址
/* const struct sockaddr_in srvaddr = {
.sin_family = AF_INET, //协议类型IPV4
.sin_port = htons(PORT), //端口号-网络字节序
.sin_addr.s_addr = htonl(INADDR_ANY) //IP地址-任意地址
};*/
struct sockaddr_in srvaddr;
srvaddr.sin_family = AF_INET; //协议类型IPV4
srvaddr.sin_port = htons(PORT); //端口号-网络字节序
srvaddr.sin_addr.s_addr = htonl(INADDR_ANY); //IP地址-任意地址
//绑定地址
bind(sock_fd, (const struct sockaddr *)&srvaddr, sizeof(srvaddr));
//接收数据
char buf[BUF_SIZE] = { 0 };
struct sockaddr_in cliaddr;
socklen_t cliaddrlen = sizeof(cliaddr);
while (1)
{
bzero(buf, BUF_SIZE);
bzero(&cliaddr, cliaddrlen);
recvfrom(sock_fd, buf, BUF_SIZE, 0, (struct sockaddr *)&cliaddr, &cliaddrlen);
printf("udp server from [%s - %hu]:%s\n",inet_ntoa(cliaddr.sin_addr),cliaddr.sin_port,buf);
}
//关闭套接字
close(sock_fd);
return 0;
}
2、客户端
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define BUF_SIZE 88
#define PROT 55555
#define ADDR "192.168.111.213"
int main(int argc, char *argv[])
{
//建立套接字
int sock_fd = socket(AF_INET, SOCK_DGRAM, 0); //IPV4,数据报套接字类型,不指定协议
//声明将连接地址
/* const struct sockaddr_in srvaddr = {
.sin_family = AF_INET, //协议类型IPV4
.sin_port = htons(PROT), //端口号-网络字节序
.sin_addr.s_addr = inet_addr(ADDR) //IP地址-字符串转IP
};*/
//声明将连接地址
struct sockaddr_in srvaddr;
srvaddr.sin_family = AF_INET; //协议类型IPV4
srvaddr.sin_port = htons(PROT); //端口号-网络字节序
srvaddr.sin_addr.s_addr = inet_addr(ADDR); //IP地址-字符串转IP
//发送数据
char buf[BUF_SIZE] = { 0 };
int count = 0;
while (1)
{
memset(buf,0, BUF_SIZE);
sprintf(buf, "%d",count);//每次发一个字符串
printf("udp client send:[%s - %d]:%s\n",ADDR,PROT,buf);
sendto(sock_fd, buf, strlen(buf), 0, (const struct sockaddr*)&srvaddr, sizeof(srvaddr));
count++;
sleep(1);
}
//关闭套接字
close(sock_fd);
return 0;
}