LoginSignup
Hiromi1623
@Hiromi1623

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

IPv6アドレスの条件分岐

Q&AClosed

解決したいこと

pythonでIPv6アドレスの中に0-9,a-f,: を含む場合はtrue、それ以外が含まれている場合にfalseを返したいです。

0-9,a-fはその中のどれか1文字が入っていればtrueではなく、
アドレス全体で0-9,a-fの範囲の文字を含んでいる場合にtrueを返したいです。

自分が作成したコードではIPv6アドレスを一文字ずつ分割して条件分岐を行っています。

よろしくお願いいたします。

発生している問題・エラー

コードをうまく作成できない

自作コード

def ipv6address(address="1234:abcd:56ef:78ab:cd90:12ef:3456:abcd")

  ipv6=list(address)

  if any(char in ipv6 for char in "[^0-9a-f:]"):
    return "true"
  else:
    return "false"
    
0

2Answer

要件に縛りが無いのであれば標準モジュールのipaddressを使った方がスマートです。

import ipaddress

def is_ipv6(address) -> bool:
    ip = ipaddress.ip_address(address)
    return (ip.version == 6)

print(is_ipv6('1234:abcd:56ef:78ab:cd90:12ef:3456:abcd'))
print(is_ipv6('127.0.0.1'))

あとreturn "true"return "false"と言った書き方は、何か理由があってワザとこういう書き方をしていますか?
真偽値として扱うなら正しい型で返しましょう。

3

以下ChatGPT4生成コード

import re

def validate_ipv6(ip):
    """
    Validate an IPv6 address using regular expressions.
    """
    # Regular expression for validating an IPv6 address
    ipv6_pattern = re.compile(r"""
    ^                                     # Start of string
    (\[[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4}){7}\])  # 8 groups of 1-4 hexadecimal digits
    |                                     # OR
    ([0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4}){7})      # 8 groups of 1-4 hexadecimal digits
    |                                     # OR
    (([0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4}){0,5})?  # 0-6 groups of 1-4 hexadecimal digits
    ::                                    # Double colon
    ([0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4}){0,5}))   # 0-6 groups of 1-4 hexadecimal digits
    $                                     # End of string
    """, re.VERBOSE)

    # Match the IP against the pattern
    match = ipv6_pattern.match(ip)

    # Return True if match is found, else False
    return bool(match)

# Test the function with some examples
test_ips = [
    "2001:0db8:85a3:0000:0000:8a2e:0370:7334",  # Valid IPv6
    "2001:db8:85a3::8a2e:370:7334",             # Valid IPv6 with :: abbreviation
    "2001:0db8:85a3:0000:0000:8a2e:0370:7334:1234",  # Invalid (too many groups)
    "2001:0db8:85a3:0000:0000:8a2e:037g:7334"   # Invalid (non-hexadecimal)
]

# Check each test IP
for ip in test_ips:
    print(f"{ip}: {validate_ipv6(ip)}")

0

Your answer might help someone💌