数値文字列からのIPv4アドレスの生成例
def numeric_string_to_ipv4(numeric_string): """Converts a numeric string to an IPv4 address. Args: numeric_string: The numeric string representing the IP address. Returns: The IPv4 address as a string in dotted-decimal notation, or None if the input is invalid. """ try: ip_int = int(numeric_string) if not 0 <= ip_int <= 0xFFFFFFFF: # Check if the integer is within the valid IPv4 range return None octets = [] for i in range(4): octet = (ip_int >> (8 * (3 - i))) & 0xFF # Extract each octet using bitwise operations octets.append(str(octet)) return ".".join(octets) except ValueError: return None # Example usage numeric_ip = "3232235777" ipv4_address = numeric_string_to_ipv4(numeric_ip) if ipv4_address: print(f"The IPv4 address for {numeric_ip} is: {ipv4_address}") else: print(f"Invalid numeric string: {numeric_ip}") numeric_ip = "4294967296" # Example of an invalid input (too large) ipv4_address = numeric_string_to_ipv4(numeric_ip) if ipv4_address: print(f"The IPv4 address for {numeric_ip} is: {ipv4_address}") else: print(f"Invalid numeric string: {numeric_ip}")
-1)。 これにより、数値が有効な32ビットの符号なし整数を表します。これは、ビットワイズ操作(上記の例に示す)またはModuloおよびInteger Divisionのいずれかを使用して達成できます。 192.168.1.1)。上記の例では、効率と明確さのためにPythonのビットワイズ演算子を使用しています。 他の言語はさまざまなアプローチを使用する場合がありますが、コアロジックは同じままです。数値文字列からIPv4アドレスを生成するときに避けるべき一般的な落とし穴は何ですか?
などのコマンドラインネットワークユーティリティは、整数と点線の系形式間の変換を含むIPアドレス計算も実行できます。 これらのツールは、迅速な変換または検証に役立ちます。
以上が数値文字列の例からIPv4アドレスを生成しますの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。