Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

icmp的那个实例中checkSum貌似有问题 #17

Open
suhanyujie opened this issue Feb 22, 2019 · 2 comments
Open

icmp的那个实例中checkSum貌似有问题 #17

suhanyujie opened this issue Feb 22, 2019 · 2 comments

Comments

@suhanyujie
Copy link

suhanyujie commented Feb 22, 2019

  • 书中的源代码checkSum实现如下,(位于文件https://github.com/qiniu/gobook/blob/master/chapter5/icmptest.go
func checkSum(msg []byte) uint16 {
	sum := 0
	for n := 1; n < len(msg)-1; n += 2 {
		sum += int(msg[n])*256 + int(msg[n+1])
	}
	sum = (sum >> 16) + (sum & 0xffff)
	sum += (sum >> 16)
	var answer uint16 = uint16(^sum)
	return answer
}
  • 实际运行时,会导致代码阻塞在n, err := conn.Read(msg[0:]),运行结果和书中描述的预期不一致
  • 我去网上搜了一下其他的实现方法,大部分如下:
func checkSum(data []byte) uint16 {
	var (
		sum    uint32
		length = len(data)
		index  int
	)
	for length > 1 {
		sum += uint32(data[index])<<8 + uint32(data[index+1])
		index += 2
		length -= 2
	}
	if length > 0 {
		sum += uint32(data[index])
	}
	sum += sum >> 16
	return uint16(^sum)
}
  • 将checkSum替换成使用这种方法实现,程序是可以正常运行的,和书中描述的预期一致
@k0njac
Copy link

k0njac commented Sep 8, 2021

的确 会一直阻塞 还以为代码敲错。如果额外开一个bash 然后用系统自带的ping 就会收到数据包

@k0njac
Copy link

k0njac commented Sep 8, 2021

func checkSum(msg []byte) uint16 {
	sum := 0

	//假设为偶数
	for n := 1; n < len(msg)-1; n += 2 {
		sum += int(msg[n])*256 + int(msg[n+1])
	}
	sum = (sum >> 16) + (sum & 0xffff)
	sum += (sum >> 16)
	var answer uint16 = uint16(^sum)
	fmt.Println(answer)
	return answer
}

62207
阻塞

func checkSum(data []byte) uint16 {
	var (
		sum    uint32
		length = len(data)
		index  int
	)
	for length > 1 {
		sum += uint32(data[index])<<8 + uint32(data[index+1])
		index += 2
		length -= 2
	}
	if length > 0 {
		sum += uint32(data[index])
	}
	sum += sum >> 16
	var answer uint16 = uint16(^sum)
	fmt.Println(answer)
	return answer
}

63437
成功

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants