Linux &&UDP通信

客户端

#include <sys/un.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>

#define BUFF_SIZE 1024

int main(void)
{
	int sockfd;                     //句柄
	struct sockaddr_in server_addr; //要绑定得邮箱
	int ret;
	int c;
	char buff[BUFF_SIZE];            //发送数据得缓存位置   
	socklen_t addr_len;              //邮箱长度

	// 创建一个套接字
	sockfd = socket(AF_INET, SOCK_DGRAM, 0);//创建udp 用SOCK_DGRAM

	// 设置服务器地址
	server_addr.sin_family = AF_INET;//ipv4
	server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");//自己主机
	server_addr.sin_port = htons(9000);//端口
	
    // 向服务器发送数据
    strcpy(buff, "hello world");
    ret = sendto(sockfd, buff, strlen(buff) + 1, 0, 
                 (struct sockaddr*)&server_addr, sizeof(server_addr));
	if (ret == -1) {
		perror("sendto");
		exit(errno);
	}

	printf("send %d bytes\n", ret);

    //接收数据
	ret = recv(sockfd, buff, sizeof(buff), 0);
	if (ret == -1) {
		perror("recvfrom");
		exit(errno);
	}

	printf("received %d bytes\n", ret);
	printf("received: %s\n", buff);	
	
	return 0;	
}

服务端

#include <sys/un.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>

#define BUFF_SIZE 1024

static void str2up(char *str)//转成大写
{
	while(*str) {
		if (*str >= 'a'  && *str <= 'z') {
			*str = *str - 'a' + 'A';
		}

		str++;
	}
}

int main(void)
{
	int server_sockfd;//服务端
	int client_sockfd;//客户端
	char ch;
	int ret;
	int recv_len;
	int send_len;
	char buff[BUFF_SIZE];

	//用于UNIX系统内部通信的地址, struct sockaddr_un
	struct sockaddr_in server_addr;//addr服务端
	struct sockaddr_in client_addr;//addr客户端
	int client_addr_len = sizeof(struct sockaddr_in);//addr长度
	
	server_sockfd = socket(AF_INET, SOCK_DGRAM, 0);//创建sock

	// 设置服务器地址
	server_addr.sin_family = AF_INET;  
	//地址的域,相当于地址的类型, AF_UNIX表示地址位于UNIX系统内部
	server_addr.sin_addr.s_addr = INADDR_ANY;  //本机地址
	server_addr.sin_port = htons(9000);//网络字节序

	// 绑定该套接字,使得该套接字和对应的系统套接字文件关联起来。
	ret = bind(server_sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr));
	if (ret == -1) {
		perror("bind");
		exit(1);
	}

	// 循环处理客户端请求
	while (1) {

		printf("server waiting\n");
		
        //UDP服务器用于接收数据
        recv_len = recvfrom(server_sockfd, buff, sizeof(buff) , 0, 
                             (struct sockaddr*)&client_addr, &client_addr_len);
		if (recv_len < 0) {
			perror("recvfrom");
			exit(errno);
		}

		printf("received: %s\n", buff);	

		str2up(buff);//转成大写
		
		//发送数据
		send_len = sendto(server_sockfd, buff, strlen(buff)+1, 0,
			              (struct sockaddr*)&client_addr, client_addr_len);
		if (send_len == -1) {
			perror("sendto");
			exit(errno);
		}

		//printf("send_len=%d\n", send_len);                  
	}

	close(server_sockfd);

	return 0;	
}


已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页