C# · 12月 19, 2021

学习UDP – udp的小程序

参考博客:https://www.cnblogs.com/skyfsm/p/6287787.html

简单编写了 udp的小程序,udp_client 端通过终端输入字符,然后发送给udp_server。udp_server 接收到后,给udp_client一个响应。

//socket udp 客户端

#include

#include

#include

#include

#include

#include

int main()

{

//创建socket对象

int sockfd=socket(AF_INET,SOCK_DGRAM,0);

if(-1 == sockfd)

{

printf(“socket Failed.n”);

}

//创建网络通信对象

struct sockaddr_in ser_addr;

memset(&ser_addr,sizeof(ser_addr));

ser_addr.sin_family =AF_INET;

ser_addr.sin_port = htons(8888);//htons(1324);

ser_addr.sin_addr.s_addr = inet_addr(“192.168.7.224”); // inet_addr(“127.0.0.1”);

while(1)

{

printf(“Please input a char:”);

char cChar;

int num = 0;

char buf[1024];

scanf(“%c”,&cChar);

getchar();

num = sendto(sockfd,&cChar,sizeof(char),(struct sockaddr*)&ser_addr,sizeof(ser_addr));

printf(“client send %d bytes: %c.n”,num,cChar);

memset(buf,sizeof(buf));

num = recvfrom(sockfd,buf,sizeof(buf),NULL,NULL);

printf(“client recv %d bytes: %s.nn”,buf);

}

close(sockfd);

}

//socket udp 服务端

#include

#include

#include

#include

#include

#include

#define INVALID_VALUE -1

#define INVALID_SOCKET -1

int main()

{

int ret = -1;

//创建socket对象

int sockfd=socket(AF_INET,0); // AF_INET:IPV4;SOCK_DGRAM:UDP

if(INVALID_SOCKET == sockfd)

{

printf(“socket Failed.n”);

}

//创建网络通信对象

struct sockaddr_in ser_addr;

bzero(&ser_addr,sizeof(ser_addr));

ser_addr.sin_family =AF_INET;

ser_addr.sin_port = htons(8888); //端口号,需要网络序转换

ser_addr.sin_addr.s_addr= htonl(INADDR_ANY); //IP地址,需要进行网络序转换,INADDR_ANY:本地地址

//绑定socket对象与通信链接

ret =bind(sockfd,sizeof(ser_addr));

if(0>ret)

{

printf(“bind error n”);

return -1;

}

char buf[1024]; //接收缓冲区,1024字节

int count;

struct sockaddr_in clent_addr; //clent_addr用于记录发送方的地址信息

socklen_t len = sizeof(clent_addr);;

while(1)

{

memset(buf,sizeof(buf));

count = recvfrom(sockfd,(struct sockaddr*)&clent_addr,&len); //recvfrom是拥塞函数,没有数据就一直拥塞

printf(“server recv %d bytes: %s n”,count,buf);

memset(buf,sizeof(buf));

snprintf(buf,”%s %d %s”,”recive”,”bytes”);

printf(“server send string:%s n”,buf);

sendto(sockfd,len); //发送信息给client,注意使用了clent_addr结构体指针

}

close(sockfd);

return 0;

}