CS558 Sylabus

### Converting "dotted-decimal-format" to (binary) IP address

• "Dotted Decimal Notations" ===> binary IP addresses conversion

• Converting a "Dotted Decimal Notation" string (such as "170.140.151.110") to a binary IP address :

 Input: a string with a dotted decimal IP address (e.g.: "170.140.151.110") Output: the binary IP address in network byte order Returns −1 if the input string does not contain a dotted decimal IP address

Example:

 ``` struct sockaddr_in dest_addr; dest_addr.sin_addr.s_addr = inet_addr("170.140.151.110"); ```

• Important note:

• Do not use htonl(  ) on the output of inet_addr( ):

 ``` struct sockaddr_in dest_addr; dest_addr.sin_addr.s_addr = htonl( inet_addr("170.140.151.110") ); ```

Because:

 the output of inet_addr( ) is already in network byte ordering !!!

• (Binary) IP address ====> "dotted-decimal" conversion

• Converting a binary IP address back to a "Dotted Decimal Notation" string (such as "170.140.151.110"):

• char * inet_ntoa(int)

• Input: a binary IP address in network byte ordering

 Make sure the ordering is: network byte ordering !!!

• Output: the string containing dotted decimal representation of the input IP address

Example:

 ``` char IPaddr[100]; strcpy(IPaddr, inet_ntoa(dest_addr.sin_addr.s_addr); ```

• Graphical illustration of the operation of the inet_addr() and inet_ntoa() functions:

• Example program:

 ``` int main(int argc, char *argv[]) { int x; /* 4 bytes */ char *s, *p; struct in_addr in; x = inet_addr("31.42.53.64"); printf("Addr: 31.42.53.64\n"); s = (char *) &x; printf("Byte 1: %d, Byte 2: %d, Byte 2: %d, Byte 4: %d\n\n\n", s[0], s[1], s[2], s[3]); /* -------------------------------------------------- */ s = (char *) & in; s[0] = 11; s[1] = 22; s[2] = 33; s[3] = 44; printf("Byte 1: %d, Byte 2: %d, Byte 2: %d, Byte 4: %d\n\n\n", s[0], s[1], s[2], s[3]); p = inet_ntoa( in ); printf("Dotted decimal: %s\n", p); } ```

Output:

 ``` Addr: 31.42.53.64 Byte 1: 31, Byte 2: 42, Byte 2: 53, Byte 4: 64 ------------------------- Byte 1: 11, Byte 2: 22, Byte 2: 33, Byte 4: 44 Dotted decimal: 11.22.33.44 ```

• Example Program: (Demo above code)

• Network programming using dotted decimal IP address

• The UDP sender using dotted decimal IP address to specify the receiver:

 ``` int main(int argc, char **argv) { struct sockaddr_in dest_addr; /* Destination socket address */ ... /* ============================================================= argv[1] is the string containg the dotted decimal IP address ============================================================= */ if ( ( dest_addr.sin_addr.s_addr = inet_addr( argv[1] ) ) == -1 ) { printf("Dotted IP-address must be of the form a.b.c.d\n"); exit(1); } ... } ```

• Example Program: (Demo above code)