Java教程

IPv6编程例子

本文主要是介绍IPv6编程例子,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

client侧

/* sudochen@163.com
 *
 *
 */
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/wait.h>
#include <arpa/inet.h>

#define LOCAL_IPV6_ADDR "2222:250:3001:1::1"
#define IPV6_PORT	8888
char msg[] = {"hello world\0"};

int main(int argc, char **argv)
{
	int fd_client, fd_server;
	int ret;
	int size;

	struct sockaddr_in6 server_addr,client_addr;
	
	fd_client = socket(AF_INET6,SOCK_DGRAM,0);
	if (fd_client < 0) {
		printf("socket create for ipv6 failed\n");
		return -1;
	}

	memset(&server_addr,0,sizeof(server_addr));
	server_addr.sin6_family = AF_INET6;
	server_addr.sin6_port = htons(IPV6_PORT);
	inet_pton(AF_INET6,LOCAL_IPV6_ADDR,server_addr.sin6_addr.__in6_u.__u6_addr8);
	ret = sendto(fd_client,msg,strlen(msg),0,
				 (struct sockaddr*)(&server_addr),
				 sizeof(server_addr));
	if (ret < 0) {
		printf("socket send for ipv6 failed\n");
	    close(fd_client);
		return -1;
	}

	close(fd_client);	
}

server侧

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <linux/if_ether.h>
#include <net/if.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <netdb.h>
#include <stdlib.h>
#include <assert.h>
#include <netpacket/packet.h>
#define IPV6_PORT	8888
char msg[] = {"hello world\0"};

int main(int argc, char **argv)
{
	int fd_client, fd_server;
	int ret;
	int size;

	struct ifreq ifr;
	struct sockaddr_in6 server_addr,client_addr;
	memset(msg,0,sizeof(msg))	;
	int i = 0;

	fd_client = socket(AF_INET6,SOCK_DGRAM,0);
	if (fd_client < 0) {
		printf("socket create for ipv6 failed\n");
		return -1;
	}



	memset(&server_addr,0,sizeof(server_addr));
	server_addr.sin6_family = AF_INET6;
	server_addr.sin6_port = htons(IPV6_PORT);
	inet_pton(AF_INET6,"2222:250:3001:1::1",server_addr.sin6_addr.__in6_u.__u6_addr8);
	printf("IP :");
	for (i=0;i<16;i++){
		printf("%02x ",server_addr.sin6_addr.__in6_u.__u6_addr8[i]);
	}
	printf("\n");

	ret = bind(fd_client,(struct sockaddr*)(&server_addr),sizeof(struct sockaddr_in6));
	if (ret < 0) {
		perror("bind error\n");
	}
	size = sizeof(client_addr);
	ret = recvfrom(fd_client,msg,sizeof(msg),0,(struct sockaddr*)(&client_addr),&size);
	if (ret < 0) {
		printf("resvfrom error\n");
	}
	printf("%s\n",msg);
	close(fd_client);
	return 0;

	ret = 

	close(fd_client);
	
}

 

这篇关于IPv6编程例子的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!