使用套接字编程发送和接收3个String缓冲区元素

时间:2014-11-12 20:39:41

标签: c sockets tcp

我正在编写一个程序来发送和接收3个字符串缓冲区的字符串。以下代码使用指针打印缓冲区。我想添加一次发送这些元素3的功能,即每次3个指令以ff开头,使用套接字编程函数send(这是一个TCP连接,因此使用send)

//Write a simple echo server

#include <stdio.h>
#include <stdlib.h>     
#include <string.h>
#include <string>
#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <arpa/telnet.h>
#include <unistd.h>
using namespace std;

string buff1[]= {"0xff , 0xfd, 0x18,0xff,0xfd,0x23","0xff , 0xfd, 0x1e","0xff , 0xfd, 0x1d","0xff ,0xfd,0x17"};

int main()
{
  int sockfd , newsockfd , portno;
  socklen_t clilen;
  char buffer[256];
  struct sockaddr_in serv_addr, cli_addr;
  int n;
  printf("\n=====================================================\nServer Side\n=====================================================\n");
  while(buff1[count].length()>0)
  {
    const unsigned char *ptr = (const unsigned char*)buff1[count].c_str();
    printf("Server Sending message %d of size:%d",count,buff1[count].length());
    for(int i = 0 ; i < buff1[count].length(); i++)
    {
         printf("%c",*ptr);
         ptr++;
    }
        printf("\n");
        count++;
  }
       return(0);
}

输出:

debian:~/sam$ ./single_sample

=====================================================
Server Side
=====================================================
Server Sending message 0 size32 :0xff , 0xfd, 0x18,0xff,0xfd,0x23
Server Sending message 1 size17 :0xff , 0xfd, 0x1e
Server Sending message 2 size17 :0xff , 0xfd, 0x1d
Server Sending message 3 size18 :0xff , 0xfd , 0x17
Segmentation fault

我有以下疑惑: a)为什么输出显示分段错误? b)在何处插入Send()方法,用于发送每条消息的3个元素,即:

Send 1 : 0xff,0xfd,0x18
Send 2 : 0xff,0xfd,0x23

提前致谢

1 个答案:

答案 0 :(得分:0)

你的循环超过buff1数组的末尾,长度为4,所以它应该只从count 0迭代到3.我建议你使用{{1} }循环而不是for循环并设置一个条件,检查以确保它在while到达数组长度的末尾时停止。否则,当您的循环到达count并尝试访问count=4时,它将导致seg错误。

buff1[count].length()
相关问题