How can i convert a hex IP address to dotted decimal notation

0

Hi i have a file with IP addresses stored as

ssIpAddress: AC1AF0F1
.
.
.
ssIpAddress: AC1AF011

and so on,

i am using awk to find and print this as follows,

awk '
/ssIpAddress/ {
str = sprintf("0x%s", $2)
ssIp = strtonum(str)
printf ("%d.%d.%d.%d\t",
rshift(and(ssIp,0xff000000),24),
rshift(and(ssIp,0x00ff0000),16),
rshift(and(ssIp,0x0000ff00),08),
rshift(and(ssIp,0x000000ff),00))
}' <file>

when i try this i get illegal syntax error. Can anyone identify the error with the syntax?

awk
asked on Stack Overflow Mar 13, 2015 by akhan • edited Mar 13, 2015 by John1024

2 Answers

2

I strongly suspect that when you say i get illegal syntax error. you actually got this:

awk: syntax error near line 6
awk: illegal statement near line 6

which means you are using old, broken awk (/bin/awk on Solaris). Never use that awk. Use gawk if you have it, otherwise if on Solaris use /usr/xpg4/bin/awk. nawk is also OK but less close to POSIX (e.g. it doesn't support character classes like [[:space:]]).

strtonum() is a gawk extension by the way as, I believe, are the bitwise operator functions, so you will need to use gawk or change your code.

Next time you have a question make sure to copy/paste any output and/or error messages exactly as-is to remove the guess-work so it's easier for us to help you.

answered on Stack Overflow Mar 13, 2015 by Ed Morton
0

You can use ctf-party (disclaimer: I'm the author)

require 'ctf_party'

'AC1AF0F1'.from_hexip # => "172.26.240.241"
'AC1AF011'.from_hexip # => "172.26.240.17"
'AC1AF0F1'.from_hexip(nibble: :low) # => "241.240.26.172"
'AC1AF011'.from_hexip(nibble: :low) # => "17.240.26.172"

On Unix some files such as /proc/net/tcp use low nibble first (little endian) else in general it's high nibble first (default).

answered on Stack Overflow Mar 17, 2021 by noraj

User contributions licensed under CC BY-SA 3.0