目录

前言

服务端

客户端

前言

简单的UDP服务器和客户端的收发数据,有错误欢迎指出。

recvfrom、sendto是UDP特有的收发接口,用的时候要注意,要是发送或者接收不成功可以用服务端里面的打印语句打印出ip地址和端口,看看是否是这两个接口的参数用错了。 要是感觉简单可以自己写一下进阶版的,比如UDP聊天室。

服务端

#include

#include

#include

#include

#include

#include

#include

//UDP server

int main()

{

int sockfd = -1;

struct sockaddr_in server, client;

char recv_buf[1024] = "";

char send_buf[1024] = "";

int len = sizeof(client);

sockfd = socket(AF_INET, SOCK_DGRAM, 0);//TCP/IP – IPv4

if(sockfd < 0)

{

printf("sockfd create failed!!\n");

goto udp_err;

}

//实例化一个存储套接字结构体变量

bzero(&server, sizeof(struct sockaddr_in));//每个字节都用0填充,sin_zero表示填充字节,一般情况下该值为0

server.sin_family = AF_INET;//sin_family表示地址类型,对于基于TCP/IP传输协议的通信,该值只能是AF_INET

//AF_INET和P_INET没区别

server.sin_port = htons(6666);//端口

server.sin_addr.s_addr = htonl(INADDR_ANY);//自动获取IP地址

if(bind(sockfd, (struct sockaddr *)&server, sizeof(struct sockaddr)) == -1)

printf("bind failed!!!\n");

else

printf("sock success!!!\n");

while(1)

{

recvfrom(sockfd, recv_buf, sizeof(recv_buf), 0, (struct sockaddr *)&client, &len);

//len的值一定要给,不能是0

printf("recv:%s\n", recv_buf);

printf("client ip:%s client port:%d\n", inet_ntoa(client.sin_addr), ntohs(client.sin_port));

//如果ip和port打印出来是空的 可能是len的值为0

printf("请输入你要返回给客户端的消息:");

scanf("%s", send_buf);

sendto(sockfd, send_buf, sizeof(send_buf), 0, (struct sockaddr *)&client, len);

}

udp_err:

sockfd = -1;

close(sockfd);

}

客户端

#include

#include

#include

#include

#include

#include

#include

#define SERVER_PORT 6666

#define SERVER_IP "127.0.0.1"

//UDP client

int main()

{

printf("this is client\n");

int sockfd = -1;

struct sockaddr_in client_addr, server_addr;

int len = sizeof(client_addr);

int ret = 0;

char send_buf[1024] = "";

char recv_buf[1024] = "";

sockfd = socket(AF_INET, SOCK_DGRAM, 0);

if(sockfd < 0)

{

printf("###sockfd failed!!!");

}

bzero(&client_addr, sizeof(struct sockaddr_in));

client_addr.sin_family = AF_INET;

client_addr.sin_port = htons(SERVER_PORT);

client_addr.sin_addr.s_addr = inet_addr(SERVER_IP);//这里的ip地址和端口是服务器的

while(1)

{

printf("请输入你要发送给服务端的数据:");

scanf("%s", send_buf);

sendto(sockfd, send_buf, sizeof(send_buf), 0, (struct sockaddr *)&client_addr, sizeof(client_addr));

recvfrom(sockfd, recv_buf, sizeof(recv_buf), 0, (struct sockaddr *)&server_addr, &len);

printf("服务端发来的数据:%s\n", recv_buf);

}

client_error:

sockfd = -1;

close(sockfd);

return 0;

}

参考文章

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: