[libc-commits] [libc] [libc] implement `inet_aton` (PR #162651)
Connector Switch via libc-commits
libc-commits at lists.llvm.org
Fri Oct 10 20:40:21 PDT 2025
================
@@ -0,0 +1,54 @@
+//===-- Implementation of inet_aton function ------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "src/arpa/inet/inet_aton.h"
+#include "src/__support/common.h"
+#include "src/__support/endian_internal.h"
+#include "src/__support/str_to_integer.h"
+
+namespace LIBC_NAMESPACE_DECL {
+
+LLVM_LIBC_FUNCTION(int, inet_aton, (const char *cp, in_addr *inp)) {
+ unsigned long parts[4] = {0};
+ int dot_num = 0;
+
+ for (; dot_num < 4; ++dot_num) {
+ auto result = internal::strtointeger<unsigned long>(cp, 0);
+ parts[dot_num] = result;
+
+ if (result.has_error() || result.parsed_len == 0)
+ return 0;
+ char next_char = *(cp + result.parsed_len);
+ if (next_char != '.' && next_char != '\0')
+ return 0;
+ else if (next_char == '\0')
+ break;
+ else
+ cp += (result.parsed_len + 1);
+ }
+
+ if (dot_num > 3)
+ return 0;
+
+ unsigned long result = 0;
+ for (int i = 0; i <= dot_num; ++i) {
+ unsigned long max_part =
+ i == dot_num ? (0xffffffffUL >> (8 * dot_num)) : 0xffUL;
+ if (parts[i] > max_part)
+ return 0;
+ int shift = i == dot_num ? 0 : 8 * (3 - i);
----------------
c8ef wrote:
```c++
case 0:
if (parts[0] > 0xffffffff)
return 0;
result = parts[0];
break;
case 1:
if (parts[0] > 0xff || parts[1] > 0xffffff)
return 0;
result = (parts[0] << 24) | parts[1];
break;
case 2:
if (parts[0] > 0xff || parts[1] > 0xff || parts[2] > 0xffff)
return 0;
result = (parts[0] << 24) | (parts[1] << 16) | parts[2];
break;
case 3:
if (parts[0] > 0xff || parts[1] > 0xff || parts[2] > 0xff ||
parts[3] > 0xff)
return 0;
result = (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3];
break;
```
It's basically a direct translation of the switch code above. The idea is that the last part doesn't need to be shifted, while the left part needs to be shifted to the higher bits. Perhaps we should use a constant like `MAX_DOT_NUM=3` throughout this function. I'll make this change tonight.
https://github.com/llvm/llvm-project/pull/162651
More information about the libc-commits
mailing list