udp socket服务端客户端示例

创建UDP服务端监听

客户端发送数据

 

服务端

 

#include <stdio.h>
#include <sys/select.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>


#define PORT 12345
#define BUF_SIZE 65536

void
buf_dump(char *buf, int len)
{
#define PER_LINE 32
	printf("--------------------------------\n");
	int i;
	for (i = 0; i < len; i++) {
		printf("%02x ", (unsigned char)buf[i]);
		if (((i + 1) % PER_LINE) == 0) {
			printf("\n");
		}
	}
	printf("\n--------------------------------\n");
#undef PER_LINE
}

int
main(void)
{
	printf("server start\n");

	int ret = -1;
	int sockfd = -1;
	sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	if (sockfd < 0) {
		perror("socket()");
	}

	struct sockaddr_in server_addr;
	memset(&server_addr, 0, sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(PORT);
	server_addr.sin_addr.s_addr = htons(INADDR_ANY);

	ret = bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr));
	if (ret < 0) {
		perror("bind()");
	}

	int max_fd = sockfd + 1;
	fd_set rfds;
	char buf[BUF_SIZE];
	int n = 0;

	while (1) {
		FD_ZERO(&rfds);
		FD_SET(sockfd, &rfds);

		ret = select(max_fd, &rfds, NULL, NULL, NULL);
		if (ret > 0) {
			if (FD_ISSET(sockfd, &rfds)) {
				memset(buf, 0, sizeof(buf));
				n = recvfrom(sockfd, buf, sizeof(buf), 0, NULL, NULL);
				if (n > 0) {
					buf_dump(buf, n);
				} else {
					perror("recvfrom()");
				}
			}
		} else {
			perror("select()");
		}

	}

	return 0;
}

 

 

客户端
 

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

#define PORT 12345
#define BUF_SIZE 65536

int
main(void)
{
	printf("client start\n");

	int ret = -1;
	int sockfd = -1;
	sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	if (sockfd < 0) {
		perror("socket()");
	}

	struct sockaddr_in server_addr;
	memset(&server_addr, 0, sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(PORT);
	server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");

	while (1) {
		ret = sendto(sockfd, "hello", 5, 0, (struct sockaddr *)&server_addr, sizeof(server_addr));
		if (ret < 0) {
			perror("sendto()");
		}
		sleep(2);
	}

	return 0;
}


 

你可能感兴趣的:(socket,server,client,UDP)