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)
&
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.
I forgot to include
require 'ipaddr'
, but the code ran fine without it (using Ruby v2.5.1). I then noticed thatipaddr
is a "default gem" in Ruby v2.5.1, but not in v2.4. Does that meanrequire 'ipaddr'
is not needed in v2.5.1+?– Cary Swoveland
Sep 12 '18 at 5:29