码迷,mamicode.com
首页 > 其他好文 > 详细

ipv6

时间:2021-03-03 12:28:42      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:ati   signed   address   stream   cannot   cal   for   amp   soc   

static int tcp_open_socket(unsigned short port, const char *bindaddr,
const char *ifname)
{
int fd = -1, n, af, opt;
struct sockaddr_in si;
struct sockaddr_in6 si6;
struct sockaddr *sa;
socklen_t sa_len;
void *dst;

if (index(bindaddr, ‘:‘)) {
af = AF_INET6;

memset(&si6, 0, sizeof(si6));
si6.sin6_family = af;
si6.sin6_port = htons(port);

dst = &si6.sin6_addr.s6_addr;
sa = (struct sockaddr *)&si6;
sa_len = sizeof(si6);
} else {
af = AF_INET;

si.sin_family = af;
si.sin_port = htons(port);
memset(&si.sin_zero, 0, sizeof(si.sin_zero));

dst = &si.sin_addr.s_addr;
sa = (struct sockaddr *)&si;
sa_len = sizeof(si);
}

n = inet_pton(af, bindaddr, dst);
if (n <= 0) {
logprintf(STDERR_FILENO, "Could not parse the bind address ‘%s‘\n",
bindaddr);
return -1;
}

if (af == AF_INET6) {
if (IN6_IS_ADDR_LINKLOCAL(&si6.sin6_addr)) {
if (!ifname) {
logprintf(STDERR_FILENO,
"Missing interface name for link local address\n");
return -1;
}
n = if_nametoindex(ifname);
if (!n) {
logprintf(STDERR_FILENO,
"Could not convert interface name ‘%s‘ to "
"index: %s\n",
ifname, strerror(errno));
return -1;
}
si6.sin6_scope_id = n;
}
}

fd = socket(af, SOCK_STREAM, 0);
if (fd < 0) {
logprintf(STDERR_FILENO, "Could not open TCP socket\n");
return -1;
}

opt = 1;
n = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
if (n < 0) {
logprintf(STDERR_FILENO,
"Could not set socket option SO_REUSEADDR: %s\n",
strerror(errno));
goto error;
}

n = bind(fd, sa, sa_len);
if (n < 0) {
logprintf(STDERR_FILENO, "Could not open TCP socket: %s\n",
strerror(errno));
goto error;
}

n = listen(fd, 1);
if (n < 0) {
logprintf(STDERR_FILENO, "Cannot listen on TCP socket: %s\n",
strerror(errno));
goto error;
}

return fd;

error:
close(fd);

return -1;
}

ipv6

标签:ati   signed   address   stream   cannot   cal   for   amp   soc   

原文地址:https://www.cnblogs.com/Janly/p/14472898.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!