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

2

6

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.

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);
Clone answered 17/3, 2013 at 19:19 Comment(0)
A
6

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;
Appendage answered 17/3, 2013 at 19:29 Comment(0)
L
0

Try to follow this:

inet_ntop(AF_INET, (void *)hent->h_addr_list[0],servIP,16);

inet_pton(AF_INET, hostIP, &(sa->sin_addr));
Lattie answered 10/12, 2015 at 6:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.