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] .

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

报告相同问题?