免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1565 | 回复: 1
打印 上一主题 下一主题

[网络] Linux下简单的IPV6实现socket通信,程序报“段错误”求大牛帮忙看一下? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2013-12-01 15:40 |只看该作者 |倒序浏览
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;
}

论坛徽章:
0
2 [报告]
发表于 2013-12-06 16:38 |只看该作者
buffer应该初始化下,memset(buffer, 0x00, sizeof(buffer));
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP