我正在尝试将一个字符串的一部分复制到另一个字符串中。 我知道开始和结束子字符串的 2 个标识符。
我正在尝试从此字符串复制 IP:
0x200085f6 <memp_memory+4502> "GET / HTTP/1.1\r\nHost: 192.168.1.200\r\nConnection
字符串的开头将是“主机:”或 192 结尾将是“\r\nC”或“\r\n”的第二次出现 所以期望的输出是:
192.168.1.200
我尝试使用 strcpy 和 memcpy,但 IP 必须是可变的,所以我不知道它会持续多长时间或会是多少,最少为 11 个字符,最多为 15 个字符。
我希望你能进一步帮助我。
最佳答案
您将需要一个 16 字节的缓冲区(每个八位字节最多 3 个字节,总共 12 个,加上三点是 15,加上零终止符)。
然后,正如您所说,您需要精确定位您的阅读:
host = strstr(string, "Host: ");
if (!host) {
// Problem. Cannot continue, the string has not the format expected.
}
host += strlen("Host: ");
end = strstr(host, "\r\n");
if (!end) {
// Problem
}
// Sanity check: end - host must be less than 16. Someone could send you
// Host: 192.168.25.12.Hello.I.Am.Little.Bobby.Headers\r\n
if ((end - host) > 15) {
// Big problem
}
// We now know where the address starts, and where it ends.
// Copy the string into address
strncpy(address, host, (end-host));
// Add zero terminator to make this a C string
address[end-host] = 0x0;
关于复制字符串的子部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47730403/