我正在尝试在 C 中创建一个客户端/服务器程序(两个程序位于不同的机器上而不是本地主机上),但使用的协议仅是 IPv6。当我运行客户端时,它会在 connect() 处暂停一段时间然后失败。为什么 connect() 失败?
服务器代码:
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<unistd.h>
#include<netdb.h>
int main()
{
int sockfd,connfd,rv;
struct addrinfo hints,*servinfo,*p;
struct sockaddr_in6 client_addr;
memset(&hints,0,sizeof hints);
hints.ai_family=AF_INET6;
hints.ai_socktype=SOCK_STREAM;
hints.ai_flags=AI_PASSIVE;
if((rv=getaddrinfo(NULL,"8888",&hints,&servinfo))!=0)
{ printf("\n Error 1 \n"); return 0; }
for(p=servinfo;p!=NULL;p=p->ai_next)
{
if((sockfd=socket(servinfo->ai_family,servinfo->ai_socktype,0))==-1)
{ perror("socket"); continue;}
if(bind(sockfd,servinfo->ai_addr,servinfo->ai_addrlen)==-1)
{ close(sockfd); perror("bind"); continue;}
break;
}
if(p==NULL)
{
fprintf(stderr,"failed to bind");
return 0;
}
listen(sockfd,8);
printf("\n\n Waiting for connection....\n");
socklen_t size=sizeof(client_addr);
if((connfd=accept(sockfd,(struct sockaddr *)&client_addr,&size))<0)
{ printf("\n Error 4 \n"); return 0; }
else
{
char ch[50];
inet_ntop(AF_INET6,&(client_addr.sin6_addr),ch,50);
printf("\n Connected to %s \n",ch);
}
close(sockfd);
close(connfd);
return 0;
}
客户代码:
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<unistd.h>
#include<netdb.h>
int main()
{
int i,s;
struct addrinfo hints,*res,*p;
memset(&hints,0,sizeof (hints));
hints.ai_family=AF_INET6;
hints.ai_socktype=SOCK_STREAM;
i=getaddrinfo("fe80::20c:29ff:fe60:7593%eth0","8888",&hints,&res);//because the system in which server code is has IPv6 address fe80::20c:29ff:fe60:7593
if(i!=0)
{ printf("\n Fail 1 \n"); return 0;}
for(p=res;p!=NULL;p=p->ai_next)
{
if((s=socket(res->ai_family,res->ai_socktype,0))==-1)
{perror("socket"); continue;}
if(connect(s,p->ai_addr,p->ai_addrlen)==-1)
{ close(s); perror("connect"); continue;}
break;
}
if(p==NULL)
{
fprintf(stderr,"failed to connect\n");
return 0;
}
close(s);
return 0;
}