Get IPv4 out of a Ruby string that contains both IPv4 and IPv6?

Get IPv4 out of a Ruby string that contains both IPv4 and IPv6?



I have a string from the X-Forwarded-For header that contains both IPv4 and IPv6 addresses.


X-Forwarded-For



I need to pull just the IPv4 address from the string.



It's comma-separated, but the order of them changes so I can't just split and pull the second item.



Example: header = 2600:1740:8540:cff9:1c50:617:c9c5:63f7, 165.154.107.112


header = 2600:1740:8540:cff9:1c50:617:c9c5:63f7, 165.154.107.112



I ultimately just want 165.154.107.112.


165.154.107.112



I'm using Ruby 2.5.1 (and this happens to be inside a Rails 5.2.0 app, for what it's worth).




2 Answers
2



Assuming your header is always as you've posted:


require 'ipaddr'

header = "165.154.107.112, 2600:1740:8540:cff9:1c50:617:c9c5:63f7"

ip = header.split(', ').select ip if IPAddr.new(ip).ipv4? .pop

# => "165.154.107.112"


header = "2600:1740:8540:cff9:1c50:617:c9c5:63f7, 165.154.107.112, 166.155.108.113"

header.split(/s?,s?/).find IPAddr.new(s).ipv4?
#=> "165.154.107.112"



or


header.split(/,s+/).select IPAddr.new(s).ipv4?
#=> ["165.154.107.112", "166.155.108.113"]



See IPAddr::new and IPAddr#ipv4?.



If "header = " is part of the string str, replace header.split with str[/d.+/].split.


"header = "


str


header.split


str[/d.+/].split



If the string may contain text that is not a valid IP address, you could write the following.


header.split(/s?,s?/).find (IPAddr.new(s) rescue nil)&.ipv4?



IPAddr.new('cat'), for example, raises the exception IPAddr::InvalidAddressError (invalid address). & is Ruby's safe navigation operator, which made it's debut in v2.3.


IPAddr.new('cat')


IPAddr::InvalidAddressError (invalid address)


&






I forgot to include require 'ipaddr', but the code ran fine without it (using Ruby v2.5.1). I then noticed that ipaddr is a "default gem" in Ruby v2.5.1, but not in v2.4. Does that mean require 'ipaddr' is not needed in v2.5.1+?

– Cary Swoveland
Sep 12 '18 at 5:29


require 'ipaddr'


ipaddr


require 'ipaddr'



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)