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:

• Output:

 The corresponding 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( )

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

• Output:

 A string containing dotted decimal representation of the input IP address

Example:

 ``` Suppose: struct sockaddr_in dest_addr; contains an IP address in network byte order char IPaddr[100]; strcpy(IPaddr, inet_ntoa(dest_addr.sin_addr.s_addr) ); ```

• The following figure summarizes the operation of the inet_addr() and inet_ntoa() functions:

• 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)