Java的inet_aton inet_ntoa

本文提供了两种IPv4地址转换的方法:一种是从长整型转换为点分十进制字符串(inet_ntoa),另一种是从点分十进制字符串或InetAddress对象转换为长整型(inet_aton)。文中详细解释了每种方法的实现细节。
	public static String inet_ntoa(long add) {
		return ((add & 0xff000000) >> 24) + "." + ((add & 0xff0000) >> 16)
				+ "." + ((add & 0xff00) >> 8) + "." + ((add & 0xff));
	}

	public static long inet_aton(Inet4Address add) {
		byte[] bytes = add.getAddress();
		long result = 0;
		for (byte b : bytes) {
			if ((b & 0x80L) != 0) {
				result += 256L + b;
			} else {
				result += b;
			}
			result <<= 8;
		}
		result >>= 8;
		return result;
	}

	/**
	 * significantly faster than parse the string into long
	 */
	public static long inet_aton(String add) {
		long result = 0;
		// number between a dot
		long section = 0;
		// which digit in a number
		int times = 1;
		// which section
		int dots = 0;
		for (int i = add.length() - 1; i >= 0; --i) {
			if (add.charAt(i) == '.') {
				times = 1;
				section <<= dots * 8;
				result += section;
				section = 0;
				++dots;
			} else {
				section += (add.charAt(i) - '0') * times;
				times *= 10;
			}
		}
		section <<= dots * 8;
		result += section;
		return result;
	}
没有找到好的java版,在大规模使用的时候还是有些差距的。
`inet_aton` 和 `inet_ntoa` 是用于在 IP 地址的点分十进制字符串表示形式和 32 位二进制整数之间进行转换的标准函数,常用于网络编程中处理 IPv4 地址。这两个函数属于 POSIX 标准库中的 `<arpa/inet.h>` 头文件(在 Linux/Unix 系统中)。 ### `inet_aton` 该函数将 IPv4 地址从字符串表示形式(如 `"192.168.1.1"`)转换为网络字节序的 32 位二进制整数(即 `in_addr_t` 类型)。其原型如下: ```c int inet_aton(const char *cp, struct in_addr *inp); ``` - `cp`:指向一个以点分十进制格式表示的 IPv4 地址字符串。 - `inp`:指向一个 `struct in_addr` 结构体的指针,用于存储转换后的二进制地址。 返回值: - 成功时返回 1; - 输入无效则返回 0。 示例代码: ```c #include <stdio.h> #include <arpa/inet.h> int main() { struct in_addr ip; int success = inet_aton("192.168.1.1", &ip); if (success) { printf("Binary representation: %u\n", ip.s_addr); } else { printf("Invalid address.\n"); } return 0; } ``` ### `inet_ntoa` 该函数的作用与 `inet_aton` 相反,它将网络字节序的 32 位 IPv4 地址转换为点分十进制字符串形式。其原型如下: ```c char *inet_ntoa(struct in_addr in); ``` - `in`:包含网络字节序的 IPv4 地址的 `struct in_addr` 结构体。 返回值是一个静态分配的字符串,表示转换后的 IP 地址[^1]。 示例代码: ```c #include <stdio.h> #include <arpa/inet.h> int main() { struct in_addr ip; inet_aton("192.168.1.1", &ip); char *ip_str = inet_ntoa(ip); printf("IP Address: %s\n", ip_str); return 0; } ``` ### 注意事项 - `inet_ntoa` 返回的是一个静态缓冲区的指针,因此在多线程环境中或多次调用时需要注意数据覆盖问题。 - 这两个函数仅支持 IPv4 地址。对于 IPv6 地址,应使用 `inet_pton` 和 `inet_ntop` 函数来替代。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值