fork download
  1. #include <stdio.h>
  2.  
  3. #include <sys/socket.h>
  4. #include <netinet/in.h>
  5. #include <arpa/inet.h>
  6.  
  7. int enterAddress(struct in_addr* in)
  8. {
  9. char buffer[32];
  10. int i= 0;
  11. memset(in, 0, sizeof(*in));
  12. printf("Enter the IP address: ");
  13. do {
  14. int ch= getchar();
  15. if (ch == EOF) {
  16. return 0;
  17. }
  18. buffer[i]= ch;
  19. if (ch != '\n') {
  20. printf("%c", buffer[i]);
  21. }
  22. fflush(stdout);
  23. } while (buffer[i] > 0 && buffer[i] != '\n' && ++i < sizeof(buffer)-1);
  24. buffer[i]= 0;
  25. printf("\n");
  26.  
  27. if (inet_aton(buffer, in) == -1) {
  28. return 0;
  29. }
  30. // Here you could check that IP is not 0.0.0.0
  31. return i > 0;
  32. }
  33.  
  34. void printAddress(struct in_addr* in)
  35. {
  36. printf("You entered IP address: %s\n\n\n", inet_ntoa(*in));
  37. }
  38.  
  39. int main(void)
  40. {
  41. struct in_addr dir;
  42.  
  43. while (enterAddress(&dir)) {
  44. printAddress(&dir);
  45. }
  46.  
  47. // your code goes here
  48. return 0;
  49. }
  50.  
Success #stdin #stdout 0s 9424KB
stdin
127.0.0.1
10.244.255.1
300.300.300.300

stdout
Enter the IP address: 127.0.0.1
You entered IP address: 127.0.0.1


Enter the IP address: 10.244.255.1
You entered IP address: 10.244.255.1


Enter the IP address: 300.300.300.300
You entered IP address: 0.0.0.0


Enter the IP address: