简体   繁体   English

如何从C中的套接字读取整数

[英]How to read an integer from a socket in C

I am trying to read in the char array from the socket and get the integer value which can then be used in a for loop. 我正在尝试从套接字读取char数组,并获取可以在for循环中使用的整数值。 Sadly I am getting a segmentation fault at atoi(). 可悲的是,我在atoi()上遇到了分段错误。 What am I doing wrong? 我究竟做错了什么?

bytesRead = read(sock, buffer, 1024);
buffer[bytesRead] = '\0';
char tmp[bytesRead];                // I suspect creating this shorter 
strncpy(tmp, buffer, bytesRead);    // array is not necessary... but not sure.
int num = atoi(tmp);

To make sure tmp is a C-"string", that is carries the 0 terminator. 确保tmp是C-“字符串”,即带有0终止符。 change the following: 更改以下内容:

char tmp[bytesRead]; 

to be 成为

char tmp[bytesRead + 1] = "";

The modifications above do two things: 上面的修改有两件事:

  1. Allocate one more bytes then you will use. 再分配一个字节,然后您将使用。
  2. Set all bytes to zero. 将所有字节设置为零。

So if you overwrite the 1 st bytesRead bytes by the call to strncpy() the last byte stays untouched and with this continues to be '\\0' , that is it 0 -terminates the char -array and with this make it a C-"string". 所以,如果你覆盖1 bytesRead由呼叫字节strncpy()的最后一个字节保持不变,并与这仍然是'\\0' ,这是它0 -terminates的char -阵列以及与此使其成为C- “串”。


Btw, this line: 顺便说一句,这行:

buffer[bytesRead] = '\0';

requires buffer to refer to at least 1024 + 1 bytes ... 需要buffer引用至少1024 + 1个字节...


Introducing the usage of tmp however isn't necessary. 但是没有必要介绍tmp的用法。 The code also might look like this: 代码也可能如下所示:

char buffer[1024 + 1];
ssize_t result = read(sock, buffer, sizeof buffer - 1);
if (-1 == result) 
{
  perror("read() failed");
}
else
{
  size_t bytesRead = result;
  buffer[bytesRead] = '\0';
  int num = atoi(buffer);
  if (0 == num)
  {
    fprintf(stderr, "atoi() (might have) failed");
  }
  ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM