Converting a numeric IPv4 address to dotted format string


#1

hi,

I have tried using Ruby filter to convert a decimal IP address to the dotted format. For some reason, it just fails. I have tried many ways, found with google, but not succeeded.

The filter just throws a rubyexception.

This is my lates version of ruby code:

code => 'event.set("[sourceipv4]",[event.get("sourceipv4")).to_i].pack("N").unpack("C4").join("."))'

Any hint on what is wrong here? I can't find out how to get an error message from ruby so that I would know what to try.


Convert mapped IPv6 to IPv4
Convert mapped IPv6 to IPv4
(Paris Mermigkas) #2

The code does work, though you have a typo (an extra bracket in event.get("sourceipv4")).
Other than that, possible causes for rubyexceptions could be failures to typecast to int or nil vaules.

Any relevant log entries? Can you check events tagged with rubyexception for abnormal values?

Sidenote: You can use built-in modules to avoid manually converting the IPs, like so

ruby {
    init => "require 'ipaddr'"
    code => '
        event.set("sourceipv4",IPAddr.new(event.get("sourceipv4").strip.to_i, Socket::AF_INET).to_s)
    '
}

#3

Thanks for your reply. I got it working; I accidentally found the place where there was a more detailed error message. The sourceipv4 was a Fixnum, and this seems to work:

code => 'event.set("sourceipv4",[event.get("sourceipv4")].pack("N").unpack("C4").join("."))'

... and now to ipv6, which seems to be some kind of a blob...

Btw. The problem with using the IPAddr.new method is that it does not seem to know how to handle cases, where the most significant bit of the address is 1 (i.e. numbers that seem to be negative, but are just unsigned integers that are interpreted wrongly earlier in logstash)


#4

I just noticed that the line I used did not work, either. I modified it this way:

code => ' 
              ip =event.get("sourceipv4") 
              if ip.instance_of? Fixnum 
                 ip = ip & 0x7FFFFFFF 
              else 
                ip = ip & 0xFFFFFFFF 
              end 
              event.set("sourceipv4",[ip].pack("N").unpack("C4").join(".")).to_s' 

The problem is the 8th bit of Fixnum type; it seems to be set when it should not.


(system) #5

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.