Linux IPv6网络编程之UDP实例

本文简单介绍了IPv6中的UDP socket编程,包括IPv6协议、地址在编程中的使用及转换。


server.c:
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define DEFAULT_IP "::1" //本地环回地址
#define DEFAULT_PORT 9000


int main(int argc, char *argv[])
{
	int sock = -1;
	int ret  = -1;
	int addr_len = 0;
	struct sockaddr_in6 server_addr;
	struct sockaddr_in6 client_addr;
	
	sock = socket(AF_INET6, SOCK_DGRAM, 0);
	if (sock < 0) {
		perror("Fail to socket");
		exit(1);
	}

	memset(&server_addr, 0, sizeof(server_addr));
	memset(&client_addr, 0, sizeof(client_addr));
	
	server_addr.sin6_family = AF_INET6; //IPv6 协议簇
	server_addr.sin6_port = htons(DEFAULT_PORT);
	inet_pton(AF_INET6, DEFAULT_IP, &(server_addr.sin6_addr.s6_addr)); //地址转换函数,这是一个通用函数,在IPv4中也可以使用,另外还有一个inet_ntop(),用于相反操作

	addr_len = sizeof(server_addr);

	if (bind(sock, (struct sockaddr *)&server_addr, addr_len) < 0) {
		perror("Fail to bind");
		exit(1);
	}

	char buf[1024];

	while (1) {
		addr_len = sizeof(client_addr);
		ret = recvfrom(sock, buf, 1024, 0, (struct sockaddr *)&client_addr, &addr_len);
		if (ret < 0) {
			perror("Fail to recvfrom");
			exit(1);
		}

		printf("Receive data: %s\n", buf);
	}
	return 0;
}

client.c:
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define SERVER_IP "::1"
#define SERVER_PORT 9000


int main(int argc, char *argv[])
{
	int sock = -1;
	int ret  = -1;
	int addr_len = 0;
	struct sockaddr_in6 server_addr;
	
	sock = socket(AF_INET6, SOCK_DGRAM, 0);
	if (sock < 0) {
		perror("Fail to socket");
		exit(1);
	}

	memset(&server_addr, 0, sizeof(server_addr));
	
	server_addr.sin6_family = AF_INET6;
	server_addr.sin6_port = htons(SERVER_PORT);
	inet_pton(AF_INET6, SERVER_IP, &(server_addr.sin6_addr.s6_addr));

	addr_len = sizeof(server_addr);

	char buf[] =  "hello";

	while (1) {
		addr_len = sizeof(server_addr);
		ret = sendto(sock, buf, strlen(buf), 0, (struct sockaddr *)&server_addr, addr_len);
		if (ret < 0) {
			perror("Fail to recvfrom");
			exit(1);
		}

		printf("Send data successfully\n");
		sleep(2);
	}
	return 0;
}

Makefile:
all:client server

client: client.c
    gcc -o client client.c
server: server.c
    gcc -o server server.c


你可能感兴趣的:(学习)