1. 程式人生 > >udp實現c/s服務器模型

udp實現c/s服務器模型

net true return include htonl lose class highlight for

server

#include<stdio.h>
#include<unistd.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<ctype.h>
#include<strings.h>
#include<arpa/inet.h>
#include<string.h>

#define port 8000
#define buflen 1024

int main(void){
	int sfd;
	char buf[buflen];
	char client_ip[128];
	socklen_t addrlen;
	struct sockaddr_in serv_addr ,client_addr;
	int i;
	int len ;

	sfd = socket(AF_INET,SOCK_DGRAM,0);
	bzero(&serv_addr,sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(port);
	serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);

	bind(sfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));

	while(1){
		addrlen = sizeof(client_addr);
		len = recvfrom(sfd,buf,sizeof(buf),0,(struct sockaddr*)&client_addr,&addrlen);
		printf("client ip:%s\t port:%d\n",inet_ntop(AF_INET,&client_addr.sin_addr.s_addr,client_ip,sizeof(client_ip)),ntohs(client_addr.sin_port));

		for(i = 0;i<len;i++){
			buf[i] = toupper(buf[i]);
		}

		sendto(sfd,buf,len,0,(struct sockaddr*)&client_addr,addrlen);
	}
	close(sfd);
	return 0;
}

  client:

#include<stdio.h>
#include<unistd.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<ctype.h>
#include<strings.h>
#include<arpa/inet.h>
#include<string.h>

#define port 8000
#define buflen 1024
#define IP "127.0.0.1"
int main(int argc,char* argv[]){
	int sfd;
	char buf[buflen];
	struct sockaddr_in serv_addr;
	socklen_t addrlen;
	int i,len;

	sfd = socket(AF_INET,SOCK_DGRAM,0);
	bzero(&serv_addr,sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(port);
	inet_pton(AF_INET,IP,&serv_addr.sin_addr.s_addr);
	//serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	
	while(1){
		fgets(buf,sizeof(buf),stdin);
		addrlen = sizeof(serv_addr);

		sendto(sfd,buf,strlen(buf),0,(struct sockaddr*)&serv_addr,addrlen);

		len = recvfrom(sfd,buf,sizeof(buf),0,NULL,0);
		buf[len] = "\0";
		printf("%s",buf);
	}
	close(sfd);

	return 0;
}

  

udp實現c/s服務器模型