Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting IP Address input by using inet_ntop() & inet_pton() (C PROGRAMMING)

Tags:

c

sockets

inet

i'm trying to convert an IP address that's inputted by a user so that I can perform some bitwise operations on it and a address already stored in a structure. My problem is however that when the IP address is converted back the output is always 255.255.255.255. For example a input of 10.0.0.1 or 192.16.2.1 always returns 255.255.255.255.

Any help would be appreciated. THANKS

  {
        struct sockaddr_in sa;
        char ipinput[INET_ADDRSTRLEN];

        fputs("Enter an IP Address: ", stdout);
        fflush(stdout);
        fgets(ipinput, sizeof ipinput, stdin);
        inet_pton(AF_INET, ipinput, &(sa.sin_addr));
        inet_ntop(AF_INET, &(sa.sin_addr), ipinput, INET_ADDRSTRLEN);
        printf("IP Address = \%s\ \n", ipinput);
        }
like image 730
A CSc Student---- Avatar asked Mar 17 '13 19:03

A CSc Student----


People also ask

What is Inet_ntop?

The inet_ntop() function converts from an Internet address in binary format, specified by src, to standard text format, and places the result in dst, when size, the space available in dst, is sufficient. The argument af specifies the family of the Internet address.

What is the use of Inet_pton?

The inet_pton() function converts an Internet address in its standard text format into its numeric binary form. The argument af specifies the family of the address.

Which of the following function is used to convert a string into an Internet address stored in a structure?

in_addr_t inet_addr(const char *strptr) This function call converts the specified string in the Internet standard dot notation to an integer value suitable for use as an Internet address.


1 Answers

You're not checking the value returned by inet_pton, you would have noticed it fails. As it turns out, it doesn't like the newline left in by fgets. Trim it:

ipinput[strlen(ipinput) - 1] = 0;
like image 127
cnicutar Avatar answered Sep 28 '22 10:09

cnicutar