Refactor mg_ntoa and mg_straddr

This commit is contained in:
cpq 2020-12-24 08:05:54 +00:00
parent 25bc13ef1e
commit c8826e8f9c
2 changed files with 30 additions and 32 deletions

View File

@ -1950,26 +1950,25 @@ int mg_printf(struct mg_connection *c, const char *fmt, ...) {
}
char *mg_straddr(struct mg_connection *c, char *buf, size_t len) {
if (c->peer.is_ip6) {
uint16_t *p = (uint16_t *) c->peer.ip6;
snprintf(buf, len, "[%x:%x:%x:%x:%x:%x:%x:%x]:%hu", mg_htons(p[0]),
mg_htons(p[1]), mg_htons(p[2]), mg_htons(p[3]), mg_htons(p[4]),
mg_htons(p[5]), mg_htons(p[6]), mg_htons(p[7]),
mg_ntohs(c->peer.port));
} else {
unsigned char *p = (unsigned char *) &c->peer.ip;
snprintf(buf, len, "%d.%d.%d.%d:%hu", p[0], p[1], p[2], p[3],
mg_ntohs(c->peer.port));
}
char tmp[100];
const char *fmt = c->peer.is_ip6 ? "[%s]:%d" : "%s:%d";
mg_ntoa(&c->peer, tmp, sizeof(tmp));
snprintf(buf, len, fmt, tmp, (int) mg_ntohs(c->peer.port));
return buf;
}
char *mg_ntoa(const struct mg_addr *addr, char *buf, size_t len) {
uint8_t p[4];
memcpy(p, &addr->ip, sizeof(p));
snprintf(buf, len, "%d.%d.%d.%d", (int) p[0], (int) p[1], (int) p[2],
(int) p[3]);
if (addr->is_ip6) {
uint16_t *p = (uint16_t *) addr->ip6;
snprintf(buf, len, "%x:%x:%x:%x:%x:%x:%x:%x", mg_htons(p[0]),
mg_htons(p[1]), mg_htons(p[2]), mg_htons(p[3]), mg_htons(p[4]),
mg_htons(p[5]), mg_htons(p[6]), mg_htons(p[7]));
} else {
uint8_t p[4];
memcpy(p, &addr->ip, sizeof(p));
snprintf(buf, len, "%d.%d.%d.%d", (int) p[0], (int) p[1], (int) p[2],
(int) p[3]);
}
return buf;
}

View File

@ -20,26 +20,25 @@ int mg_printf(struct mg_connection *c, const char *fmt, ...) {
}
char *mg_straddr(struct mg_connection *c, char *buf, size_t len) {
if (c->peer.is_ip6) {
uint16_t *p = (uint16_t *) c->peer.ip6;
snprintf(buf, len, "[%x:%x:%x:%x:%x:%x:%x:%x]:%hu", mg_htons(p[0]),
mg_htons(p[1]), mg_htons(p[2]), mg_htons(p[3]), mg_htons(p[4]),
mg_htons(p[5]), mg_htons(p[6]), mg_htons(p[7]),
mg_ntohs(c->peer.port));
} else {
unsigned char *p = (unsigned char *) &c->peer.ip;
snprintf(buf, len, "%d.%d.%d.%d:%hu", p[0], p[1], p[2], p[3],
mg_ntohs(c->peer.port));
}
char tmp[100];
const char *fmt = c->peer.is_ip6 ? "[%s]:%d" : "%s:%d";
mg_ntoa(&c->peer, tmp, sizeof(tmp));
snprintf(buf, len, fmt, tmp, (int) mg_ntohs(c->peer.port));
return buf;
}
char *mg_ntoa(const struct mg_addr *addr, char *buf, size_t len) {
uint8_t p[4];
memcpy(p, &addr->ip, sizeof(p));
snprintf(buf, len, "%d.%d.%d.%d", (int) p[0], (int) p[1], (int) p[2],
(int) p[3]);
if (addr->is_ip6) {
uint16_t *p = (uint16_t *) addr->ip6;
snprintf(buf, len, "%x:%x:%x:%x:%x:%x:%x:%x", mg_htons(p[0]),
mg_htons(p[1]), mg_htons(p[2]), mg_htons(p[3]), mg_htons(p[4]),
mg_htons(p[5]), mg_htons(p[6]), mg_htons(p[7]));
} else {
uint8_t p[4];
memcpy(p, &addr->ip, sizeof(p));
snprintf(buf, len, "%d.%d.%d.%d", (int) p[0], (int) p[1], (int) p[2],
(int) p[3]);
}
return buf;
}