netclient.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /**
  2. * Simple TCP connection check
  3. * (c) 1993-2008 OSI
  4. *
  5. * Proprietary unpublished code
  6. *
  7. * WARNING: contains various assumptions regarding the use of IPv4
  8. * This is NOT production-quality code, just a quick debug test
  9. */
  10. #include "sys/socket.h"
  11. #include "netinet/in.h"
  12. #include "arpa/inet.h"
  13. #include "netdb.h"
  14. #include "stdio.h"
  15. // HOST "profile.microscopy-analysis.com"
  16. // PORT 8080
  17. //
  18. #define MAX_BUF 100
  19. /**
  20. * Dump client socket info for IPv4
  21. */
  22. int showServ(struct sockaddr_in *sn)
  23. {
  24. printf("IP Dump\n");
  25. printf(" Family [%d]\n", sn->sin_family);
  26. printf(" Host [%s]\n", inet_ntoa(sn->sin_addr));
  27. printf(" Port [%d]\n", ntohs(sn->sin_port));
  28. }
  29. /**
  30. * Return the last IP in the resolution list for host name
  31. */
  32. char *getServIp(char *name)
  33. {
  34. struct hostent *he = gethostbyname(name);
  35. int i;
  36. static char addr[MAX_BUF];
  37. struct in_addr *pin;
  38. if (he == NULL)
  39. return NULL;
  40. printf("Host check:\n Name %s\n Canonical name %s\n Addr len %d\n Family %d\n",
  41. name, he->h_name, he->h_length, he->h_addrtype);
  42. i = 0;
  43. while (he->h_addr_list[i] != NULL)
  44. {
  45. pin = (struct in_addr *) he->h_addr_list[i];
  46. strcpy(addr, inet_ntoa(*pin));
  47. printf(" IP %s\n", addr);
  48. i++;
  49. }
  50. return addr;
  51. }
  52. /**
  53. * Main function
  54. */
  55. int main (int argc, char **argv)
  56. {
  57. int sockd;
  58. int count;
  59. struct sockaddr_in serv_name;
  60. char buf[MAX_BUF];
  61. int status;
  62. char *ip;
  63. if (argc != 3)
  64. {
  65. fprintf(stderr, "Syntax, %s <host> <port>\n", argv[0]);
  66. exit(1);
  67. }
  68. strcpy(buf, argv[1]);
  69. ip = getServIp(buf); // warning: static result, overwritten by each call
  70. sockd = socket(AF_INET, SOCK_STREAM, 0);
  71. if (sockd == -1)
  72. {
  73. perror("Socket creation");
  74. exit(2);
  75. }
  76. serv_name.sin_family = AF_INET;
  77. /* fprintf(stderr, "Inet_aton on %s returns %d\n", */ ip, inet_aton(ip, &serv_name.sin_addr);
  78. serv_name.sin_port = htons(atoi(argv[2]));
  79. showServ(&serv_name);
  80. fprintf(stderr, "Trying to connect to %s:%d\n", argv[1], atoi(argv[2]));
  81. status = connect(sockd, (struct sockaddr *) &serv_name, sizeof(serv_name));
  82. if (status == -1)
  83. {
  84. perror("Connection error");
  85. exit(3);
  86. }
  87. fputs("Connection successful, closing\n", stderr);
  88. shutdown(sockd, 1);
  89. close(sockd);
  90. return 0;
  91. }