inet: refactor getpeername to allocate the struct on the stack

This commit is contained in:
Paul Aurich 2011-07-03 14:28:12 -07:00 committed by Sam Roberts
parent 8393c76180
commit 7893d9ece2

View File

@ -169,27 +169,37 @@ static int inet_global_gethostname(lua_State *L)
\*-------------------------------------------------------------------------*/
int inet_meth_getpeername(lua_State *L, p_socket ps)
{
struct sockaddr *peer;
struct sockaddr_storage peer;
struct sockaddr *p = (struct sockaddr *)&peer;
socklen_t peer_len = sizeof(struct sockaddr_storage);
char ipaddr[INET6_ADDRSTRLEN];
peer = (struct sockaddr *) malloc(peer_len);
if (!peer || (getpeername(*ps, (SA *) peer, &peer_len) < 0)) {
if (getpeername(*ps, p, &peer_len) < 0) {
lua_pushnil(L);
lua_pushstring(L, "getpeername failed");
} else {
if (peer->sa_family == AF_INET)
inet_ntop(AF_INET, &((struct sockaddr_in *)peer)->sin_addr,
char ipaddr[INET6_ADDRSTRLEN] = "";
unsigned short port = 0;
switch (p->sa_family) {
case AF_INET:
inet_ntop(AF_INET, &((struct sockaddr_in *)&peer)->sin_addr,
ipaddr, sizeof(ipaddr));
else if (peer->sa_family == AF_INET6)
inet_ntop(AF_INET6, &((struct sockaddr_in6 *)peer)->sin6_addr,
port = ntohs(((struct sockaddr_in *)&peer)->sin_port);
break;
case AF_INET6:
inet_ntop(AF_INET6, &((struct sockaddr_in6 *)&peer)->sin6_addr,
ipaddr, sizeof(ipaddr));
port = ntohs(((struct sockaddr_in6 *)&peer)->sin6_port);
break;
default:
lua_pushnil(L);
lua_pushstring(L, "Unknown address family");
return 2;
break;
}
lua_pushstring(L, ipaddr);
if (peer->sa_family == AF_INET)
lua_pushnumber(L, ntohs(((struct sockaddr_in *)peer)->sin_port));
else if (peer->sa_family == AF_INET6)
lua_pushnumber(L, ntohs(((struct sockaddr_in6 *)peer)->sin6_port));
free(peer);
lua_pushnumber(L, port);
}
return 2;
}