comparison src/lib/net.c @ 22639:da6cf4b7caf4

lib: net_addr2ip() - Optimize for parsing IPv4 addresses
author Timo Sirainen <timo.sirainen@dovecot.fi>
date Sat, 04 Nov 2017 01:43:41 +0200
parents 7d5634889da8
children cb108f786fb4
comparison
equal deleted inserted replaced
22638:7d5634889da8 22639:da6cf4b7caf4
950 (ip4 & 0x0000ff00) >> 8, 950 (ip4 & 0x0000ff00) >> 8,
951 (ip4 & 0x000000ff)); 951 (ip4 & 0x000000ff));
952 #endif 952 #endif
953 } 953 }
954 954
955 static bool net_addr2ip_inet4_fast(const char *addr, struct ip_addr *ip)
956 {
957 uint8_t *s_addr = (void *)&ip->u.ip4.s_addr;
958 unsigned int i, num;
959
960 if (str_parse_uint(addr, &num, &addr) < 0)
961 return FALSE;
962 if (*addr == '\0' && num <= 0xffffffff) {
963 /* single-number IPv4 address */
964 ip->u.ip4.s_addr = htonl(num);
965 ip->family = AF_INET;
966 return TRUE;
967 }
968
969 /* try to parse as a.b.c.d */
970 i = 0;
971 for (;;) {
972 if (num >= 256)
973 return FALSE;
974 s_addr[i] = num;
975 if (i == 3)
976 break;
977 i++;
978 if (*addr != '.')
979 return FALSE;
980 addr++;
981 if (str_parse_uint(addr, &num, &addr) < 0)
982 return FALSE;
983 }
984 if (*addr != '\0')
985 return FALSE;
986 ip->family = AF_INET;
987 return TRUE;
988 }
989
955 int net_addr2ip(const char *addr, struct ip_addr *ip) 990 int net_addr2ip(const char *addr, struct ip_addr *ip)
956 { 991 {
957 int ret; 992 int ret;
993
994 if (net_addr2ip_inet4_fast(addr, ip))
995 return 0;
958 996
959 if (strchr(addr, ':') != NULL) { 997 if (strchr(addr, ':') != NULL) {
960 /* IPv6 */ 998 /* IPv6 */
961 #ifdef HAVE_IPV6 999 #ifdef HAVE_IPV6
962 T_BEGIN { 1000 T_BEGIN {