gpt4 book ai didi

c - 当::1 在接口(interface) 1 上时,为什么我可以将此套接字绑定(bind)到::1%2?

转载 作者:可可西里 更新时间:2023-11-01 02:42:43 26 4
gpt4 key购买 nike

我试图了解 sin6_scope_id 在 UNIX C 套接字编程中如何用于 IPv6 地址。具体来说,我编写了这个试图绑定(bind)到 ::1%2 的程序(所以接口(interface) 2 上的环回地址,如果我没看错的话)即使我的环回地址实际上在接口(interface) 1 上。

我预计这会失败。但是绑定(bind)成功。为什么?

这是 ifconfig -a 返回的前 3 个接口(interface):

$ ifconfig -a

lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384
options=3<RXCSUM,TXCSUM>
inet6 ::1 prefixlen 128
inet 127.0.0.1 netmask 0xff000000
inet6 fe80::1%lo0 prefixlen 64 scopeid 0x1
nd6 options=1<PERFORMNUD>
gif0: flags=8010<POINTOPOINT,MULTICAST> mtu 1280
stf0: flags=0<> mtu 1280

你可以编译这个程序:

cc -Wall -Wextra main.c

这是评论来源:

#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
// Allow any IP address on the interface with scope ID of 2.
const char *hostname = "::1%2";

// Say we want to bind on port 80 (for http).
const char *servname = "1337";

// Store some information about the IP address wanted.
struct addrinfo hints;

// Save addresses in here.
struct addrinfo *addr_list_item = NULL;

// Tell `getaddrinfo` that we want an address for IPv6 TCP.
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET6;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
if (getaddrinfo(hostname, servname, &hints, &addr_list_item) != 0) {
printf("Could not read addresses.\n");
exit(1);
}

// Create a socket and bind it to the address we found before. This should fail
// but for some reason I don't understand it doesn't.
if (addr_list_item) {
int sock = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
if (sock != -1) {
if (bind(sock, addr_list_item->ai_addr, addr_list_item->ai_addrlen) != -1) {
printf("Binded succesfully!\n");
} else {
perror(NULL);
}
close(sock);
}
}

// Release memory.
freeaddrinfo(addr_list_item);

return (0);
}

最佳答案

根据您的 unix 版本,%2 可能会被忽略。

关于一些IBM systems ,文档说:

The above IPv6 text forms may include an appended zone indicator (if preceded by a % character) and/or an appended prefix length (if preceded by a / character). In these cases, the % or / will be treated the same as a null terminator.

关于c - 当::1 在接口(interface) 1 上时,为什么我可以将此套接字绑定(bind)到::1%2?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26781497/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com