- 论坛徽章:
- 0
|
Linux下简单的IPV6实现socket通信Client端,程序报“段错误”,应该是在socket建立时的connect函数,报错“段错误”,
本人刚开始Linux方面的学习,莱鸟一枚,求各路高手帮忙看一下。
调试时采用本机终端地址,即./Client ::1
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<netdb.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<sys/socket.h>
#include<pthread.h>
#define CLIENT_PORT 20000
#define BUFFER_SIZE 1024
int sockfd;
pthread_t recthread;//声明线程
void recmessage(void)
{
while(1)
{
int buffer_length;
char buffer[BUFFER_SIZE];
if( ( buffer_length = recv(sockfd,buffer,BUFFER_SIZE,0) ) == -1 )//接收数据
{
printf("Receive Fials");
exit(1);
}
buffer[buffer_length]='\0';
if( strcmp(buffer,"exit") == 0 )
{
printf("Server is closed\n");
close(sockfd);
exit(1);
}
printf("Server:%s\n",buffer);
}
}
int main(int argc,char *argv[])
{
//struct hostent *he;
struct sockaddr_in6 their_addr;
if(argc != 2)
{
fprintf(stderr,"usage:client hostname\n");
exit(1);
}
//if( (he=gethostbyname(argv[1])) == NULL )
//{
// herror("gethostbyname");
// exit(1);
//}
if( (sockfd = socket(AF_INET6,SOCK_STREAM,0)) == -1 )
{
printf("Create Socket Fails!\n");
exit(1);
}
bzero(&(their_addr),sizeof(their_addr));
their_addr.sin6_family = AF_INET6;
their_addr.sin6_port = htons(CLIENT_PORT);
//their_addr.sin_addr = *((struct in_addr *)he->h_addr);
if ( inet_pton(AF_INET6,argv[1],&their_addr.sin6_addr)<=0 )/*Linux下IP地址转换函数*/
{
error("inet_pton error for %s",argv[1]); /*“点分十进制”和“整数”之间转换*/
exit(1);
}
if( connect(sockfd,(struct sockaddr *)&their_addr,sizeof(their_addr)) == -1 )
//连接
{
printf("Connet Fails");
exit(1);
}
if( (pthread_create(&recthread,NULL,(void *)recmessage,NULL))!=0 )//创建线程
{
printf("Create thread error!\r\n");
exit(1);
}
while(1)
{
char msg[BUFFER_SIZE];
scanf("%s",msg);
if( send(sockfd,msg,strlen(msg),0) == -1 )
{
printf("Send Fails");
close(sockfd);
exit(1);
}
if(strcmp(msg,"exit") == 0)
{
printf("EXIT!\n");
close(sockfd);
exit(1);
}
}
return 0;
}
|
|