linux环境下基于UDP的 客户端服务器模型

客户端

//UDP 客户端
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <fcntl.h>

#define MAXLINE	4096
#define SERVER_PORT	8000	

/* 这里的多有函数没有作出错判断 */

int main(int argc, char *argv[])
{
	struct sockaddr_in serveraddr;
	int confd;
	char ipstr[] = "192.168.1.253";
	char buf[MAXLINE];
	ssize_t len;

	if(argc < 2) {
		printf("./client str\n");
		exit(1);
	}

	//1.创建一个socket
	confd = socket(AF_INET, SOCK_DGRAM, 0);
	//2.初始化服务器地址
	bzero(&serveraddr, sizeof(serveraddr));
	serveraddr.sin_family = AF_INET;

	//"192.168.1.253"
	inet_pton(AF_INET, ipstr, &serveraddr.sin_addr.s_addr);
	serveraddr.sin_port = htons(SERVER_PORT);

	//3.向服务器发送数据
	sendto(confd, argv[1], strlen(argv[1]), 0, (struct sockaddr *)&serveraddr, sizeof(serveraddr));
	len = recvfrom(confd, buf, sizeof(buf), 0, NULL, 0);
	write(STDOUT_FILENO, buf, len);

	close(confd);

	//5.关闭socket
	close(confd);

	return 0;
	
}


服务端

//UDP 服务端
#include <stdio.h>
#include <stdlib.h> 
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <ctype.h>

#define SERVER_PORT	8000
#define MAXLINE		1500	//MTU 最大传输单元

int main(void)
{
	int sockfd, i;
	struct sockaddr_in serveraddr, clientaddr;
	char buf[MAXLINE];
	char ipstr[INET_ADDRSTRLEN]; //16 Bytes 
	socklen_t clientlen;
	ssize_t len;

	/* 构造用于UDP的套接字 */
	sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	bzero(&serveraddr, sizeof(serveraddr));
	serveraddr.sin_family = AF_INET;
	serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); //本地任意IP
	//	printf("%x\n", INADDR_ANY); //这个直为0 

	serveraddr.sin_port = htons(SERVER_PORT);

	bind(sockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr));
	while (1) {
		clientlen = sizeof(clientaddr);
	len =	recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&clientaddr, &clientlen);
		printf("client IP %s\tPORT %d\n",  inet_ntop(AF_INET, &clientaddr.sin_addr.s_addr, ipstr, sizeof(ipstr)), ntohs(clientaddr.sin_port));

		i = 0;
		while (i < len) {
			buf[i] = toupper(buf[i]);
			i++;
		}
		//buf[i] = '\0';

		sendto(sockfd, buf, strlen(buf), 0, (struct sockaddr *)&clientaddr, sizeof(clientaddr));
	}	 
	close(sockfd);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值