determine client ipv4 or ipv6

45 views
Skip to first unread message

kang joni

unread,
Sep 18, 2016, 10:46:16 PM9/18/16
to libuv
how to check if client is connected using ipv4 or ipv6 in libuv?
I have this code,

struct sockaddr_storage cp;
int ilen=sizeof(cp);
uv_tcp_getpeername((uv_tcp_t*)client, (struct sockaddr*)&cp,&ilen);
int ret=uv_ip6_name((const struct sockaddr_in6*)&cp,(char*)ipname,sizeof(ipname));
//I don't think this is correct, but I haven't any clues
if (retip<0 || std::string("::")==ipname)
{
retip=uv_ip4_name((const struct sockaddr_in*)&cp,(char*)ipname, sizeof(ipname));

}

any corrections ? thanks

Ben Noordhuis

unread,
Sep 19, 2016, 3:23:51 AM9/19/16
to li...@googlegroups.com
You can simply check if ilen == sizeof(struct sockaddr_in) or ilen ==
sizeof(struct sockaddr_in6) but a more thorough solution is to check
the address family:

struct sockaddr *sa = (struct sockaddr *) &cp;
switch (sa->sa_family) {
case AF_INET: /* ... */; break;
case AF_INET6: /* ... */; break;
}

kang joni

unread,
Sep 19, 2016, 5:57:48 AM9/19/16
to li...@googlegroups.com
using second AF_INETXx seems more robust approach, thank you.
> --
> You received this message because you are subscribed to a topic in the
> Google Groups "libuv" group.
> To unsubscribe from this topic, visit
> https://groups.google.com/d/topic/libuv/npXnJIDdKMo/unsubscribe.
> To unsubscribe from this group and all its topics, send an email to
> libuv+un...@googlegroups.com.
> To post to this group, send email to li...@googlegroups.com.
> Visit this group at https://groups.google.com/group/libuv.
> For more options, visit https://groups.google.com/d/optout.
>
Reply all
Reply to author
Forward
0 new messages