- 论坛徽章:
- 5
|
代码如下:- #include <time.h>
- #include <errno.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <string.h>
- #include <net/if.h>
- #include <pthread.h>
- #include <sys/time.h>
- #include <arpa/inet.h>
- #include <sys/timeb.h>
- #include <sys/types.h>
- #include <sys/ioctl.h>
- #include <netinet/in.h>
- #include <sys/socket.h>
- extern int errno;
- void errorPrint()
- {
- char *errMsg= strerror(errno);
- printf("errno:%d,errorMsg:%s\n",errno,errMsg);
- }
- int main(void)
- {
- struct sockaddr_in6 server;
- struct sockaddr_in6 client;
- int sock;
- int val;
- int rc=0;
- char source_ip[40]={0};
- char dest_ip[40]={0};
- short src_port=4484;
- short dest_port=2547;
- memset(&server,0,sizeof(client));
- memset(&client,0,sizeof(client));
- server.sin6_family = AF_INET;
- client.sin6_family = AF_INET;
- server.sin6_port = htons(dest_port);
- client.sin6_port = htons(src_port);
- strcpy(source_ip,"2400:a480:aaaa:200::159");
- strcpy(dest_ip,"2400:a480:aaaa:200::159");
- rc=inet_pton(AF_INET6, source_ip,&client.sin6_addr);
- if(rc!=1)
- {
- printf("open_udp_socket_v6 error,inet_pton error!\n");
- return -1;
- }
- rc=inet_pton(AF_INET6,dest_ip,&server.sin6_addr);
- if(rc!=1)
- {
- printf("open_udp_socket_v6 error,inet_pton error!\n");
- return -1;
- }
- if((sock = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP)) < 0)
- {
- printf("open_udp_socket_v6 error(socket error)\n");
- return -1;
- }
- val = 1;
- /*bind过程中本地地址可重复使用*/
- if(setsockopt (sock, SOL_SOCKET, SO_REUSEADDR, (char *)&val,sizeof(val)) < 0)
- {
- close(sock);
- printf("open_udp_socket_v6 error(setsockopt error)\n");
- return -1;
- }
- if(bind(sock,(struct sockaddr*)&client,sizeof(client)) < 0)
- {
- close(sock);
- printf("open_udp_socket_v6 error(bind error)\n");
- return -1;
- }
- if(connect(sock, (struct sockaddr *)&server, sizeof(server)) == -1)
- {
- errorPrint();
- close(sock);
- printf("open_udp_socket_v6 error(connect error)\n");
- return -1;
- }
- return 0;
- }
复制代码 运行结果:
- errno:97,errorMsg:Address family not supported by protocol
- open_udp_socket_v6 error(connect error)
复制代码 求大神指导~
|
|