ip_address.anubis 2.81 KB


   *** (15) IP address
   
   
   An IP address is a Word32 which may be displayed numerically by the following function:
      
public define String
  ip_addr_to_string
    (
      Word32 addr
    ) =
  to_decimal(addr&255) + "." +
  to_decimal((addr>>8)&255) + "." +
  to_decimal((addr>>16)&255) + "." +
  to_decimal((addr>>24)&255).

public define String
  ip_addr_to_string
  (
	IpAddress ip_addr
  )=
  if ip_addr is ip_address(w32) then ip_addr_to_string(w32)
  .
   
   The following is used  when the bytes are not in network byte order  (as it is the case
   in RFC 1035 DNS messages).
   
public define String
  reverse_ip_addr_to_string
    (
      Word32 addr
    ) =
  to_decimal((addr>>24)&255) + "." +
  to_decimal((addr>>16)&255) + "." +
  to_decimal((addr>>8)&255) + "." +
  to_decimal((addr)&255).

   
   We can also construct IP addresses with:
   
public define Word32
   ip_address
     (
       (Word8,Word8,Word8,Word8) addr
     ) =
   if addr is (b3,b2,b1,b0) then
   word32(word16(b3,b2),word16(b1,b0)).
   
 define Word32
   word8_to_word32
     (
       Word8 x
     ) =
   word32(word16(x,0),0). 
      
   
   We may also need to transform a string like "123.456.789.123" into an integer IP address. 
   
define inline Bool
   is_digit
     (
       Word8 c
     ) =
   if c +< '0' then false else c +=< '9'. 
   
     
define Maybe((Int,Word8))    // returns the next position for reading and a label. 
   read_label
     (
       String s,
       Int i,
       Word8 so_far
     ) =
   if nth(i,s) is 
     {
       failure then success((i,so_far)),
       success(c) then 
         if c = '.'
         then success((i+1,so_far))
         else if is_digit(c)
              then read_label(s,i+1,10*so_far+c-'0')
              else failure
     }.
   
/**
 * Convert string of form 'xx.xx.xx.xx' (with 'xx' a value between 0 to 255) to an ip address 
 * coded on a Word32 and directly usable with Anubis network functions.
 */
public define Maybe(Word32)
   ip_address
     (
       String s
     ) =
   if read_label(s,0,0) is 
     {
       failure then failure, 
       success(p1) then if p1 is (i2,lab1) then 
         if read_label(s,i2,0) is 
           {
             failure then failure,
             success(p2) then if p2 is (i3,lab2) then 
               if read_label(s,i3,0) is 
                 {
                   failure then failure, 
                   success(p3) then if p3 is (i4,lab3) then 
                     if read_label(s,i4,0) is 
                       {
                         failure then failure, 
                         success(p4) then if p4 is (i4a,lab4) then 
                           if i4a = length(s)
                           then success(word32(word16(lab1,lab2),word16(lab3,lab4)))
                           else failure
                       }
                 }
           }
     }.