c - Linux 套接字/段错误

标签 c linux sockets segmentation-fault

我需要在linux中使用socket发送数据。我使用套接字发送数据,使用管道接收数据。当我尝试在函数 :SendGTSMessage 中发送数据时,我收到的发送数据值为空。 当我尝试访问 SendGTSMessage 中的 Bytessent 时,我也收到 Segmentation failure 错误。

SendGTSMessage 函数是从 HandleGtsMessage 函数调用的。

任何见解都会有帮助,

void* BeginGTSServer(void* arg)
{
   char                 Buffer[1000];
   char                 *interface= NULL;
   unsigned short       port=DEFAULT_PORT;
   int                  retval;
   socklen_t                  fromlen;
   struct sockaddr_in   local;
   struct sockaddr_in  from;
   int                 listen_socket;
   int                  continueMsgs = 1;
   int                  errNumber;
   char                OutputString[255];

   local.sin_family = AF_INET;
  // local.sin_addr.s_addr = (!interface)?INADDR_ANY:inet_addr(interface);
   local.sin_addr.s_addr =INADDR_ANY;    
   local.sin_port = htons(port);

   listen_socket = socket(AF_INET,SOCK_STREAM,0); // TCP socket
   logMessage("Socket Created.\n");   

   if (listen_socket<0)
   {
      sprintf(OutputString,"*** socket() failed with error %d\n",errno);
      perror("Failed to create Socket");
      MsgBox("Failed To create Socket");
           // return;
   }
   if (bind(listen_socket,(struct sockaddr*)&local, sizeof(local)))
   {
      sprintf(OutputString,"*** bind() failed with error %d\n",errno);
      perror("bind() failed with error");
      MsgBox("bindfailed with error");
     // MessageBox(NULL, OutputString,"ERROR", MB_OK );
    //  return;
   }
   logMessage("Socket Binded.\n"); 
   if (listen(listen_socket,5) <0)
   {    
       sprintf(OutputString,"*** listen() failed with error %d\n",errno);
       perror("listen() failed with error");
       MsgBox("listen() failed with error");
      //MessageBox(NULL, OutputString,"ERROR", MB_OK );
      // return;
   }

logMessage("Listen Succeded.\n");  
fromlen =sizeof(from);   
glueDebug = true;
printf("listen_socket",listen_socket); 
msgsock =accept(listen_socket,(struct sockaddr *) &from, &fromlen);  
if (msgsock== -1)
{    
      sprintf(OutputString,"*** accept() error %d\n",errno);
      perror("accept() error");
      MsgBox("accept() error");
      //MessageBox(NULL, OutputString,"ERROR", MB_OK );
      // return;
}    
GTSConnected = true;
logMessage("GTS Connected.\n");
while( 1 )
{    
    retval = recv(msgsock,Buffer,sizeof(Buffer),0 );
    if (retval<0)
    {
        perror("Reading Stream Message Error");
        errNumber = errno;
        if (errno != ECONNREFUSED )
        {
            //fprintf(stderr,"*** recv() failed: error %d\n",errNumber);
        }
    }
    else
    {
         errNumber = 0;
    }
    if (retval == 0 || errNumber == ECONNREFUSED )
    {
         logMessage("GTS connection terminated.\n");
         MsgBox("GTS connection terminated.\n");
         // We are waiting for a connection.
         sprintf( GTSConnectionStatus, GTSNotConnected);
         GTSConnected = false;
         close(msgsock);
         msgsock = accept(listen_socket,(struct sockaddr*)&from,(socklen_t *) &fromlen);

         if (msgsock <0)
         {
            sprintf(OutputString,"*** accept() error %d\n",errno);
            MsgBox("accept() error");
            //MessageBox(NULL, OutputString,"ERROR", MB_OK );
            //return;
         }
         GTSConnected = true;
         continue;
      }
      // Null terminate the string.  Ignore the 0x85 at the end.
      Buffer[retval-1] = 0;
      logMessage("Buffer Message",&Buffer[4]);
      HandleGTSMessages(&Buffer[4]);
      logMessage("Message passed to handle function");
      continue;
   }
}

void HandleGTSMessages(char *Message)
{
   int loop;
   char LocalMsgBuffer[1024];
   char strippedMessage[1024];
//   char Message[1024];
   char *ProgramArgument[9] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
   logMessage("Program:%s\n",Message);       
   if (!strncmp(Message,"IsProgRunning",strlen("IsProgRunning")))
   {
      if (TstProgramConnected)
         sprintf(LocalMsgBuffer, "True:%s",executingVSProgram);
      else
         sprintf(LocalMsgBuffer, "False");

     SendGTSMessage(LocalMsgBuffer, strlen(LocalMsgBuffer), true);
     return;
   }
   else if (!strncmp(Message,"InfoRequest", strlen("InfoRequest")))
   {
      char hostname[255];
      char cwd[1024];
      char stationType[25];

      strcpy(hostname,"unknown");
      gethostname(hostname,254);
      getcwd( cwd, 1023 );
      strcpy(stationType,"Unknown");

      loop = 0;

      while (Station[loop].StationString[0] != 0)
      {
         if (FileExist(Station[loop].FileTest))
         {
            strcpy(stationType,Station[loop].StationString);
            break;
         }
         loop++;
      }
     sprintf(LocalMsgBuffertest,"Version: %s\n,HostName:%s\n,Execution Dir:%s\n,Station Type:%s",

     VERSION,hostname,cwd,stationType);
     logMessage("Info Request:%s\n",LocalMsgBuffertest);
     SendGTSMessage(LocalMsgBuffertest,strlen(LocalMsgBuffertest),true);
     return;
   }
}

int SendGTSMessage(char *MsgToSend, int msgLength, bool forceMsgExactly)
{
   char Buffer[1000];
   int bytesSent;
   int ShiftedMsgLength;
   struct hostent *hp;
   struct sockaddr_in server;
   char dum[40];

  /* local.sin_family = AF_INET;
     local.sin_addr.s_addr =INADDR_ANY;  
      local.sin_port = htons(port);

   sock=socket(AF_INET, SOCK_STREAM, 0);
   connect(sock,(struct sockaddr*)&local, sizeof(local));
   logMessage("connected with send gts",MsgToSend);
GTSConnected =true;*/

int sock;

sock = socket(AF_INET, SOCK_STREAM, 0);
char buffer[256];
char hostname[1024];

server.sin_family = AF_INET;
gethostname(hostname,sizeof(hostname));
hp = gethostbyname(hostname);
memcpy(&server.sin_addr,hp->h_addr,hp->h_length);
server.sin_port = htons(port);

connect(sock,(struct sockaddr *) &server,sizeof(server));
if (GTSConnected == true)
{
   // Overwrite the normal message, if we ran the crmvs program to disable 
   // or enable telemetry.
   if ((ExecutingBuiltInProgram) && (forceMsgExactly == false))    
   {
      HandleGTSMessages("ADV");
      if (strstr(MsgToSend,"PASSED"))
      // Advance the telemetry command.
         MsgToSend = BuiltInPassedMsg;
      else
         MsgToSend = BuiltInFailedMsg;

       msgLength = strlen (MsgToSend);    
      }

     // Copy in the msg to send, and terminate it with a 0x85.
     strncpy(&Buffer[4], MsgToSend, msgLength);
     // logMessage("Message Length  %s\n", msgLength);
     *(Buffer+msgLength+4) = (char)0x55;
     ShiftedMsgLength = (msgLength) << 8;
     memcpy(&Buffer[0], &ShiftedMsgLength, 4);
     *(Buffer) = (char)0xaa;

     bytesSent = send(sock,Buffer,msgLength+5,0);
     logMessage("Message Length  %s\n",Buffer);
     if (bytesSent <0)
     {
         // Just re-use the same buffer for the error message.
         sprintf(Buffer,"*** send() failed: error %d\n",strerror(errno));
         MsgBox("Send() Failed");
        // MessageBox(NULL, Buffer,"ERROR", MB_OK );
      }
   }
   //logMessage("Bytes Sent %s\n",bytesSent);
   // return bytesSent;*/
}

最佳答案

sprintf(GTSConnectionStatus, GTSNotConnected);这不是使用 sprintf 的正确方法。

引用man page

关于c - Linux 套接字/段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31529929/

相关文章:

c - 在没有库和指针的情况下构建 strcat

c 按位取反转换题

c - 在另一个结构中初始化并获取结构变量?

visual-studio-2010 - 将类从 MFC 移植到 C++ 控制台应用程序。使用/MD[d](CRT dll版本)构建MFC应用程序需要

Java套接字编程——请求

linux - 太多持久的 TCP 连接

c++ - 如何为 Roland UM 4 实现 MIDI 驱动程序?

php - shell_exec 不返回与 sudoed 命令行相同的结果

linux - 更新 Babun 时权限被拒绝

c - 是什么导致 linux 中的系统调用以提升的权限运行