从字节缓冲区中提取IP [英] extract IP from a buffer of bytes

查看:184
本文介绍了从字节缓冲区中提取IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个包含此字节的缓冲区:

510175126-94-51080

If I have a buffer containing this bytes:
510175126-94-51080

如何从中提取 75126-94-51 部分(这是ip)并打印正确的IP?
感谢高级。

How can I extract the 75126-94-51 part from it(which is the ip) and print the correct IP ? Thanks in advanced.

for(int i = 0; i< bytes_recv; i ++)

{

cout < static_cast< int>(temp [i]);

}

cout< endl;


edit:这是我的输出:5 1 0 1 75 126 -94 -51 0 80

for(int i = 0; i < bytes_recv; i++)
{
cout << static_cast<int>(temp[i]);
}
cout << endl;

edit: this is my output: 5 1 0 1 75 126 -94 -51 0 80

推荐答案

问题中缺少很多信息。所以,你正在从SOCKS协议读取服务器回复。首先,缓冲区不应该和将不具有10字节的固定大小。它有10个字节,如果你的地址是IPv4(这巧合是几天前耗尽,考虑IPv6的时间)。如果来源具有IPv6地址,则服务器响应的大小不同。

A lot of information is missing from the question. So, you are reading the server reply from the SOCKS protocol. First, the buffer should not and will not have a fixed size of 10 bytes. It has 10 bytes if your address is IPv4 (which coincidently was exhausted a few days ago, time to think about IPv6). If the origin has a IPv6 address, the size of the server response is different.

RFC 1928 ,第6节,服务器回复具有以下格式:

From RFC 1928, section 6, the server reply has this format:


+----+-----+-------+------+----------+----------+
|VER | REP |  RSV  | ATYP | BND.ADDR | BND.PORT |
+----+-----+-------+------+----------+----------+
| 1  |  1  | X'00' |  1   | Variable |    2     |
+----+-----+-------+------+----------+----------+


请注意,地址字段具有可变大小。对于IPv4,具体来说,ATYP == 0x01和BND.ADDR具有大小4,这使得1 + 1 + 1 + 1 + 4 + 2 = 10字节。但你应该考虑其他大小是可能的,特别是如果ATYP == 0x03,这使得BND.ADDR的长度真正变量。

Note that the address field has variable size. For IPv4, specifically, ATYP == 0x01 and BND.ADDR has size 4, which makes 1+1+1+1+4+2 = 10 bytes. But you should consider that other sizes are possible, specially if ATYP == 0x03, which makes BND.ADDR truly variable in length.

所以,回答你的问题,你在 char buffer [] 数组(或指针)中有这些字节,你必须首先检查地址的类型,然后像这样提取:

So, answering your question, considering that you have these bytes in a char buffer[] array (or pointer), you must first check the type of the address, then extract it like this:

#include <arpa/inet.h>

switch (buffer[3]) {
  case 0x01: {    /* IPv4 address */
    char result[INET_ADDRSTRLEN];
    inet_ntop(AF_INET, (void*)(&buffer[4]), result, sizeof result);
    std::cout << "IPv4: " << result << "\n";
    break;
  }

  case 0x04: {    /* IPv6 address */
    char result[INET6_ADDRSTRLEN];
    inet_ntop(AF_INET6, (void*)(&buffer[4]), result, sizeof result);
    std::cout << "IPv6: " << result << "\n";
    break;
  }

  default:
    std::cout << "Unsupported format.\n";
    break;
}

这篇关于从字节缓冲区中提取IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆