IPv6 Socket Program Problem

徘徊边缘 提交于 2019-12-05 22:49:32

hp = gethostbyname(host);

How do you know this returns an IPv6 address if you pass it "localhost" ? It probably returns the IPv4 address, and things go belly up if you try to copy that into servaddr.sin6_addr

Use getaddrinfo() and explicitly look for an AF_INET6 address (or better yet, make your program independent of the actual address types, see here), or use the global in6addr_loopback as the server address, for testing with localhost.

I can see a few issues of varying degrees:

  1. Don't declare errno yourself - use the headers. It may be a macro instead of an int
  2. (per @Boofhead) don't bind the client socket
  3. Use getaddrinfo() instead of gethostbyname() in the client to get the server's address. gethostbyname() doesn't portably support IPv6

The last of the 3 is actually the real problem. I've tested your code on MacOS X and CentOS 5 and gethostbyname() only returns an IPv4 address.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!