nettest.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <sys/socket.h> /* AF_INET */
  5. #include <netinet/in.h> /* sockaddr_in */
  6. #include <netdb.h> /* gethostbyname */
  7. #ifdef __PSP2__
  8. #include <arpa/inet.h>
  9. #include <sys/select.h>
  10. #else
  11. #endif
  12. #ifdef __PSP2__
  13. #define SERVER "www.yahoo.co.jp"
  14. #else
  15. #define SERVER "soft8-pc.rd.scei.sony.co.jp"
  16. #endif
  17. #define PORT 80
  18. #define REQUEST "GET / HTTP/1.0\r\n\r\n"
  19. #define BUF_LEN 1024
  20. int do_nettest()
  21. {
  22. struct hostent *hostent;
  23. struct sockaddr_in server;
  24. int sock;
  25. char buf[BUF_LEN]; /* receive buffer */
  26. hostent = gethostbyname(SERVER); /* lookup IP */
  27. if (hostent == NULL ) {
  28. printf("Cannot resolve %s.\n", SERVER);
  29. return 0;
  30. }
  31. memset((void*)(&server), 0, sizeof(server));
  32. server.sin_family = AF_INET;
  33. /* server.sin_addr = hostent->h_addr */
  34. memcpy(&server.sin_addr, hostent->h_addr_list[0], hostent->h_length);
  35. server.sin_port = htons(PORT);
  36. if ( ( sock = socket(AF_INET, SOCK_STREAM, 0) ) < 0) {
  37. fprintf(stderr, "Cannot make socket.\n");
  38. return 0;
  39. }
  40. if ( connect(sock, (struct sockaddr *)&server, sizeof(server)) == -1) {
  41. printf("Cannot connect.\n");
  42. return 0;
  43. }
  44. printf("Connected to %s. sock = %08x\n", SERVER, (int)sock);
  45. send(sock, REQUEST, strlen(REQUEST), 0);
  46. if (1)
  47. {
  48. /* select */
  49. fd_set fds;
  50. while (1)
  51. {
  52. FD_ZERO(&fds);
  53. FD_SET(sock, &fds);
  54. int res = select(sock+1, &fds, NULL, NULL, NULL);
  55. printf("select %d\n", res);
  56. if (FD_ISSET(sock, &fds))
  57. {
  58. memset(buf, 0, BUF_LEN);
  59. int recv_size = recv(sock, buf, BUF_LEN, 0);
  60. if (recv_size > 0) {
  61. printf("%s", buf);
  62. } else {
  63. printf("recv -> %08x\n", recv_size);
  64. break;
  65. }
  66. }
  67. }
  68. }
  69. else
  70. {
  71. /* Receive data */
  72. memset(buf, 0, BUF_LEN);
  73. while (recv(sock, buf, BUF_LEN, 0) > 0) {
  74. printf("%s", buf);
  75. memset(buf, 0, BUF_LEN);
  76. }
  77. }
  78. #ifdef __PSP2__
  79. closesocket(sock);
  80. #else
  81. close(sock);
  82. #endif
  83. return 0;
  84. }
  85. #ifndef __PSP2__
  86. int main()
  87. {
  88. do_nettest();
  89. }
  90. #endif