douxueke5653 2017-12-31 04:18
浏览 83
已采纳

如何在socks5代理中将2字节的端口号返回给客户端?

I am trying to implement socks5 proxy server. Most things are clear according to the rfc but I'm stuck interpreting client port and writing my port number in bytes.

I made a function that tkes an int and returns 2 bytes. This function first converts number into binary then literally splits the bits as string then converts them back to byte.However this seems wrong because if the right most bits are 0 they are lost. Here is the function

func getBytesOfInt(i int) []byte {
    binary := fmt.Sprintf("%b", i)
    if i < 255 {
        return []byte{byte(i)}
    }
    first := binary[:8]
    last := binary[9:]
    fmt.Println(binary, first, last)
    i1, _ := strconv.ParseInt(first, 2, 64)
    i2, _ := strconv.ParseInt(last, 2, 64)
    return []byte{byte(i1), byte(i2)}
}

Can you please explain me how am i supposed to parse the number and get 2 bytes and most importantly how am i going to cast it back to an integer.

Currently if you give 1024 to this function it will return []byte{0x80, 0x0} which is 128 in decimals but as you see the right bits are lost theres only one 0 which is useless.

  • 写回答

1条回答 默认 最新

  • dryl34156 2017-12-31 04:41
    关注

    Your code has multiple problem. First :8 and 9: miss an element ([8]), see: https://play.golang.org/p/yuhh4ZeJFNL

    And also, you should interept the second byte as lowbyte of the int and the first as highbyte, not literally cut the binary string. for example 4 should be interept as [0x0,0x4] instead of [0x4,0x0] which shoulld be 1024.

    If you want to keep using strconv you should use:

    n := len(binary)
    first := binary[:n-8]
    last := binary[n-8:]
    

    However it is very unefficient.

    I would suggest b[0],b[1] = i >> 8, i & 255, and i = b[0]<<8 + b[1] .

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥15 pyqt信号槽连接写法
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用