udp的客户端
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc,const char* argv[])
{
if(argc!=3)
{
printf("error:try again!\n");
}
int sockfd=0;
sockfd = socket(AF_INET,SOCK_DGRAM,0);
if(sockfd==-1)
{
perror("socket");
exit(1);
}
else
{
printf("sockfd:%d\n",sockfd);
}
int flag=0;
struct sockaddr_in seraddr;
bzero(&seraddr,sizeof(seraddr));
seraddr.sin_family =AF_INET;
seraddr.sin_port=htons(atoi(argv[2]));
seraddr.sin_addr.s_addr =inet_addr(argv[1]);
socklen_t len=sizeof(seraddr);
//
while(1)
{
char buf[100] ={0};
scanf("%s",buf);
size_t rv=sendto(sockfd,buf,sizeof(buf),0,(struct sockaddr*)&seraddr,len);
if(rv==-1)
{
perror("sendto");
exit(1);
}
else
{
printf("buf:%s\n",buf);
size_t from=recvfrom(sockfd,buf,sizeof(buf),0,(struct sockaddr*)&seraddr,&len);
if(from==-1)
{
perror("recvfrom");
exit(1);
}
else
{
printf("buf:%s\n",buf);
}
}
}
return 0;
}
udp的服务端
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc,const char* argv[])
{
if(argc!=3)
{
printf("error:try again!\n");
}
int sockfd=0;
sockfd = socket(AF_INET,SOCK_DGRAM,0);
if(sockfd==-1)
{
perror("socket");
exit(1);
}
else
{
printf("sockfd:%d\n",sockfd);
}
//bind 绑定ip+port
int flag=0;
struct sockaddr_in seraddr;
bzero(&seraddr,sizeof(seraddr));
seraddr.sin_family =AF_INET;
seraddr.sin_port=htons(atoi(argv[2]));
seraddr.sin_addr.s_addr =inet_addr(argv[1]);
socklen_t len=sizeof(seraddr);
flag=bind(sockfd,(struct sockaddr*)&seraddr,len);
if(flag ==-1)
{
perror("bind");
exit(1);
}
else
{
printf("--------init success-------\n");
}
//接收客户端消息
char buf[100] ={0};
struct sockaddr_in cliaddr;
while(1)
{
bzero(&cliaddr,sizeof(cliaddr));
bzero(buf,sizeof(buf));
size_t rv=recvfrom(sockfd,buf,sizeof(buf),0,(struct sockaddr*)&cliaddr,&len);
if(rv==-1)
{
perror("recvfrom");
exit(1);
}
else
{
printf("[%s:%d]:%s\n",inet_ntoa(cliaddr.sin_addr),ntohs(cliaddr.sin_port),buf);
sendto(sockfd,"OK",sizeof("ok"),0,(struct sockaddr*)&cliaddr,len);
}
}
return 0;
}