UDP 程序设计典例

UDP 服务端:

#include<sys/socket.h>
#include<sys/unistd.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdio.h>

#define SIZE 1024
#define portno 8888

void udp_responds(int sockfd)
{
	struct sockaddr_in addr;
	int addrlen,nbytes;
	char buf[SIZE];
	while(1)
	{
		bzero(buf,SIZE);
		addrlen=sizeof(struct sockaddr);
		nbytes=recvfrom(sockfd,buf,SIZE,0,(struct sockaddr *)(&addr),&addrlen);
		buf[nbytes]='\0';
		printf("Server received:%s\n",buf);
	}
}

int main()
{
	int sockfd;
	struct sockaddr_in addr;
	
	sockfd=socket(AF_INET,SOCK_DGRAM,0);
	if(sockfd==-1)
	{
		printf("create sock failed\n");
		return -1;
	}
	
	bzero(&addr,sizeof(addr));
	addr.sin_family=AF_INET;
	addr.sin_port=htons(portno);
	addr.sin_addr.s_addr=htonl(INADDR_ANY);
	
	if(bind(sockfd,(struct sockaddr *)(&addr),sizeof(struct sockaddr_in))==-1)
	{
		printf("bind failed\n");
		return -1;
	}
	
	udp_responds(sockfd);
	close(sockfd);
	
	return 1;
}




 

UDP客户端:

#include<sys/socket.h>
#include<sys/unistd.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdio.h>

#define SIZE 1024
#define portno 8888

void udp_requ(int sockfd,struct sockaddr_in *paddr,int addrlen)
{
	char buf[SIZE];
	while(1)
	{
		printf("please input what you want to say:\n");
		fgets(buf,SIZE,stdin);
		sendto(sockfd,buf,SIZE,0,(struct sockaddr *)paddr,addrlen);
		bzero(buf,SIZE);
	}
}

int main(int argc,char *argv[])
{
	int sockfd;
	struct sockaddr_in addr;
	
	if(argc!=2)
	{
		printf("arguments error\n");
		return -1;
	}
	
	sockfd=socket(AF_INET,SOCK_DGRAM,0);
	if(sockfd==-1)
	{
		printf("create sock failed\n");
		return -1;
	}
	
	bzero(&addr,sizeof(addr));
	addr.sin_family=AF_INET;
	addr.sin_port=htons(portno);
	
	if(inet_aton(argv[1],&(addr.sin_addr))<0)
	{
		printf("transmit error\n");
		return -1;
	}
	
	//if(bind(sockfd,(struct sockaddr *)(&addr),sizeof(struct sockaddr_in))==-1)
	//{
	//	printf("bind failed\n");
	//	return -1;
	//}
	
	udp_requ(sockfd,&addr,sizeof(struct sockaddr_in));
	
	close(sockfd);
	return -1;
}



 

 

你可能感兴趣的:(linux,UDP,tcpip)