static VALUE
sock_s_getnameinfo(int argc, VALUE *argv)
{
VALUE sa, af = Qnil, host = Qnil, port = Qnil, flags, tmp;
char *hptr, *pptr;
char hbuf[1024], pbuf[1024];
int fl;
struct addrinfo hints, *res = NULL, *r;
int error;
struct sockaddr_storage ss;
struct sockaddr *sap;
sa = flags = Qnil;
rb_scan_args(argc, argv, "11", &sa, &flags);
fl = 0;
if (!NIL_P(flags)) {
fl = NUM2INT(flags);
}
tmp = rb_check_sockaddr_string_type(sa);
if (!NIL_P(tmp)) {
sa = tmp;
if (sizeof(ss) < (size_t)RSTRING_LEN(sa)) {
rb_raise(rb_eTypeError, "sockaddr length too big");
}
memcpy(&ss, RSTRING_PTR(sa), RSTRING_LEN(sa));
if ((size_t)RSTRING_LEN(sa) != SS_LEN(&ss)) {
rb_raise(rb_eTypeError, "sockaddr size differs - should not happen");
}
sap = (struct sockaddr*)&ss;
goto call_nameinfo;
}
tmp = rb_check_array_type(sa);
if (!NIL_P(tmp)) {
sa = tmp;
MEMZERO(&hints, struct addrinfo, 1);
if (RARRAY_LEN(sa) == 3) {
af = RARRAY_PTR(sa)[0];
port = RARRAY_PTR(sa)[1];
host = RARRAY_PTR(sa)[2];
}
else if (RARRAY_LEN(sa) >= 4) {
af = RARRAY_PTR(sa)[0];
port = RARRAY_PTR(sa)[1];
host = RARRAY_PTR(sa)[3];
if (NIL_P(host)) {
host = RARRAY_PTR(sa)[2];
}
else {
/*
* 4th element holds numeric form, don't resolve.
* see rsock_ipaddr().
*/
hints.ai_flags |= AI_NUMERICHOST;
}
}
else {
rb_raise(rb_eArgError, "array size should be 3 or 4, %ld given",
RARRAY_LEN(sa));
}
/* host */
if (NIL_P(host)) {
hptr = NULL;
}
else {
strncpy(hbuf, StringValuePtr(host), sizeof(hbuf));
hbuf[sizeof(hbuf) - 1] = '\0';
hptr = hbuf;
}
/* port */
if (NIL_P(port)) {
strcpy(pbuf, "0");
pptr = NULL;
}
else if (FIXNUM_P(port)) {
snprintf(pbuf, sizeof(pbuf), "%ld", NUM2LONG(port));
pptr = pbuf;
}
else {
strncpy(pbuf, StringValuePtr(port), sizeof(pbuf));
pbuf[sizeof(pbuf) - 1] = '\0';
pptr = pbuf;
}
hints.ai_socktype = (fl & NI_DGRAM) ? SOCK_DGRAM : SOCK_STREAM;
/* af */
hints.ai_family = NIL_P(af) ? PF_UNSPEC : rsock_family_arg(af);
error = rb_getaddrinfo(hptr, pptr, &hints, &res);
if (error) goto error_exit_addr;
sap = res->ai_addr;
}
else {
rb_raise(rb_eTypeError, "expecting String or Array");
}
call_nameinfo:
error = rb_getnameinfo(sap, SA_LEN(sap), hbuf, sizeof(hbuf),
pbuf, sizeof(pbuf), fl);
if (error) goto error_exit_name;
if (res) {
for (r = res->ai_next; r; r = r->ai_next) {
char hbuf2[1024], pbuf2[1024];
sap = r->ai_addr;
error = rb_getnameinfo(sap, SA_LEN(sap), hbuf2, sizeof(hbuf2),
pbuf2, sizeof(pbuf2), fl);
if (error) goto error_exit_name;
if (strcmp(hbuf, hbuf2) != 0|| strcmp(pbuf, pbuf2) != 0) {
freeaddrinfo(res);
rb_raise(rb_eSocket, "sockaddr resolved to multiple nodename");
}
}
freeaddrinfo(res);
}
return rb_assoc_new(rb_str_new2(hbuf), rb_str_new2(pbuf));
error_exit_addr:
if (res) freeaddrinfo(res);
rsock_raise_socket_error("getaddrinfo", error);
error_exit_name:
if (res) freeaddrinfo(res);
rsock_raise_socket_error("getnameinfo", error);
}