UDP网络程序设计
udp_server
#include<stdio.h>
#include<sys/socket.h>
#include<string.h>
#include<netinet/in.h>
#define portnum 3333
void main()
{
int n,addrlen;
char buffer[128];
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
int sockfd;
//1创建套接字
sockfd=socket(AF_INET,SOCK_DGRAM,0)
//2.1设置地址
bzero(&server_addr,sizeof(struct sockaddr_in));
server_addr.sin_family=AF_INET; //IPV4协议族
server_addr.sin_port=htons(portnum);
server_addr.sin_addr.s_addr=htonl(INADDR_ANY);
//2绑定地址
bind(sockfd, (struct sockaddr *)(&server_addr),sizeof(struct sockaddr));
//3接收数据
while(1)
{
addrlen=sizeof(struct sockaddr);
bzero(buffer,sizeof(buffer));
n= recvfrom(sockfd,buffer,128,0,(struct sockaddr *)(&client_addr),&addrlen);
buffer[n]=0; //0是字符串的结束符
printf("server received :%s\n ",buffer);
}
//4结束连接
close(sockfd);
}
udp_client
#include<stdio.h>
#include<sys/socket.h>
#include<string.h>
#include<netinet/in.h>
#define portnum 3333
#define BUF_SIZE 128
int main(int argc, char **argv)
{
char buffer[BUF_SIZE];
struct sockaddr_in server_addr;
int sockfd;
if(argc!=2)
{
printf("usage:%s server_ip\n",argv[0]);
exit(1);
}
//1创建套接字
sockfd=socket(AF_INET,SOCK_DGRAM,0)
//2.1设置地址
bzero(&server_addr,sizeof(struct sockaddr_in));
server_addr.sin_family=AF_INET; //IPV4协议族
server_addr.sin_port=htons(portnum);
server_addr.sin_addr.s_addr=htonl(INADDR_ANY);
inet_aton(argv[1],&server_addr.sin_addr);
//2发送数据
while(1)
{
printf("please input char:\n");
fgets(buffer,128,stdin);
sendto(sockfd,buffer,strlen(buffer),0, (struct sockaddr *)(&server_addr),sizeof(struct sockaddr));
bzero(buffer,sizeof(buffer));
}
//3关闭连接
close(sockfd);
return 0;
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步