linux c基于UDP的网路编程模式(客户端与服务器进行交互)

//utili.h
#include
#include
#include
#include
#include
#define BUF_SIZE 128
#define backlogs 10
//包裹函数
int Socket(int domain,int type,int protocol)
{
	int fd=socket(domain,type,protocol);
	if(fd==-1)
	{
		perror("socket error!\n");
		return -1;
	}
	return fd;
}
int Bind(int sockfd,const struct sockaddr *addr,socklen_t addrlen)
{
	int ret=bind(sockfd,addr,addrlen);
	if(ret==-1)
	{
		perror("bind error!\n");
		return -1;
	}
	return ret;
}
int Start(const char *ip,int port)
{
	int fd=Socket(AF_INET,SOCK_DGRAM,0);
	struct sockaddr_in seraddr;
	seraddr.sin_family=AF_INET;
	seraddr.sin_port=htons(port);
	seraddr.sin_addr.s_addr=inet_addr(ip);
	int on=1;
	setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(int));
	socklen_t addrlen=sizeof(struct sockaddr);
	Bind(fd,(struct sockaddr *)&seraddr,addrlen);
	return fd;
}
////////////////////////////////////////////////////////////////
服务器:ser.c
#include"utili.h"
int main(int argc,char *argv[])
{
	int ser_fd=Start(argv[1],atoi(argv[2]));
	char sendbuf[BUF_SIZE];
	char recvbuf[BUF_SIZE];
	struct sockaddr_in cliaddr;
	socklen_t addrlen=sizeof(struct sockaddr);
	while(1)
	{

		recvfrom(ser_fd,recvbuf,128,0,(struct sockaddr*)&cliaddr,&addrlen);
		printf("Cli:%s",recvbuf);
		printf("Ser:> ");
		scanf("%s",sendbuf);
		sendto(ser_fd,sendbuf,strlen(sendbuf)+1,0,(struct sockaddr*)&cliaddr,addrlen);
	}
	close(ser_fd);
	return 0;
}
/////////////////////////////////////////////////////////////////////
客户端:cli.c
#include"utili.h"
int main(int argc,char *argv[])
{
	int cli_fd=socket(AF_INET,SOCK_DGRAM,0);
	if(cli_fd==-1)
	{
		perror("socket error!\n");
		return -1;
	}
	char sendbuf[BUF_SIZE];
	char recvbuf[BUF_SIZE];
	struct sockaddr_in seraddr;
	seraddr.sin_family=AF_INET;
	seraddr.sin_port=htons(atoi(argv[2]));
	seraddr.sin_addr.s_addr=inet_addr(argv[1]);
	socklen_t addrlen=sizeof(struct sockaddr);
	while(1)
	{
		printf("Cli:> ");
		scanf("%s",sendbuf);
		sendto(cli_fd,sendbuf,strlen(sendbuf)+1,0,(struct sockaddr*)&seraddr,addrlen);
		recvfrom(cli_fd,recvbuf,128,0,(struct sockaddr*)&seraddr,&addrlen);
		printf("Ser:> %s",recvbuf);
	}
	close(cli_fd);
	return 0;
}

 

你可能感兴趣的:(linux c基于UDP的网路编程模式(客户端与服务器进行交互))