1. /*./client serv_ip serv_port */
    2. #include "net.h"
    3. void usage (char *s)
    4. {
    5. printf ("\n%s serv_ip serv_port", s);
    6. printf ("\n\t serv_ip: server ip address");
    7. printf ("\n\t serv_port: server port(>5000)\n\n");
    8. }
    9. int main (int argc, char **argv)
    10. {
    11. int fd = -1;
    12. int port = -1;
    13. struct sockaddr_in sin;
    14. if (argc != 3) {
    15. usage (argv[0]);
    16. exit (1);
    17. }
    18. /* 1. 创建socket fd */
    19. if ((fd = socket (AF_INET, SOCK_STREAM, 0)) < 0) {
    20. perror ("socket");
    21. exit (1);
    22. }
    23. port = atoi (argv[2]);
    24. if (port < 5000) {
    25. usage (argv[0]);
    26. exit (1);
    27. }
    28. /*2.连接服务器 */
    29. /*2.1 填充struct sockaddr_in结构体变量 */
    30. bzero (&sin, sizeof (sin));
    31. sin.sin_family = AF_INET;
    32. sin.sin_port = htons (port); //网络字节序的端口号
    33. #if 0
    34. sin.sin_addr.s_addr = inet_addr (SERV_IP_ADDR);
    35. #else
    36. if (inet_pton (AF_INET, argv[1], (void *) &sin.sin_addr) != 1) {
    37. perror ("inet_pton");
    38. exit (1);
    39. }
    40. #endif
    41. if (connect (fd, (struct sockaddr *) &sin, sizeof (sin)) < 0) {
    42. perror ("connect");
    43. exit (1);
    44. }
    45. printf ("Client staring...OK!\n");
    46. /*3. 读写数据 */
    47. char buf[BUFSIZ];
    48. int ret = -1;
    49. while (1) {
    50. bzero (buf, BUFSIZ);
    51. if (fgets (buf, BUFSIZ - 1, stdin) == NULL) {
    52. continue;
    53. }
    54. do {
    55. ret = write (fd, buf, strlen (buf));
    56. } while (ret < 0 && EINTR == errno);
    57. if (!strncasecmp (buf, QUIT_STR, strlen (QUIT_STR))) { //用户输入了quit字符
    58. printf ("Client is exiting!\n");
    59. break;
    60. }
    61. }
    62. /*4.关闭套接字 */
    63. close (fd);
    64. }