#include <stdio.h> #include <errno.h> #include <netinet/in.h> #include <sys/types.h> #include <sys/socket.h> void main() { int fd; struct sockaddr_in6 sockaddr; int fd_got; struct sockaddr_in6 sockaddr_got; int sockaddr_got_len = sizeof(struct sockaddr_in6); fd = socket(AF_INET6, SOCK_STREAM, 0); if (fd == -1) { printf("socket err: %d\n", errno); return; } sockaddr.sin6_family = AF_INET6; sockaddr.sin6_addr = in6addr_any; sockaddr.sin6_port = htons(2121); if(bind(fd, (struct sockaddr *) &sockaddr, sizeof(struct sockaddr_in6)) == -1) { printf("bind err: %d\n", errno); return; } if (listen(fd, 50) == -1) { printf("listen err: %d\n", errno); return; } fd_got = accept(fd, (struct sockaddr *) &sockaddr_got, &sockaddr_got_len); if (fd_got == -1) { return; } printf("socket: accepted, fd=%d\n", fd_got); close(fd_got); close(fd); }
运行
# ./socket_ipv6_test0
socket: accepted, fd=4
通过telnet连接:
在本地可以直接通过ipv4的回路地址localhost进行连接
# telnet localhost 2121
Trying ::1...
Connected to localhost.
Escape character is '^]'.
Connection closed by foreign host.
在本地也可以通过ipv6的回路地址::1进行连接
# telnet ::1 2121
Trying ::1...
Connected to ::1.
Escape character is '^]'.
Connection closed by foreign host.
通过ipv6地址进行连接
# telnet -8 fe80::20c:29ff:fe12:7803%eth0 2121
Trying fe80::20c:29ff:fe12:7803%eth0...
Connected to fe80::20c:29ff:fe12:7803%eth0.
Escape character is '^]'.
Connection closed by foreign host.