Simple example of C language socket network programming under Linux

Source: Internet
Author: User
Tags htons

Transferred from: http://blog.csdn.net/kikilizhm/article/details/7858405

This gives an example of a simple socket network programming under Linux, communicates with the TCP protocol, listens on the server, sends the data to the client after receiving the client's connection, and the client prints and closes after receiving the data. There are detailed instructions in the program, in which the specific structure and functions of the implementation can refer to other information.

Program Description: Here the server port number and IP address using fixed settings, the migration can be changed according to the specific circumstances, can be rewritten as a parameter to pass better, here for convenience, use fixed.

The server can be run without changes at the time of migration, the client will change IP to the address of the servers, and then compile and run. You can use Netstat to view the appropriate run status.

[CPP]View Plaincopyprint?
  1. /*************************************
  2. File name: server.c
  3. A simple example of Linux socket network programming-service-side program
  4. The server port is set to 0x8888 (ports and addresses can be changed depending on the situation, or passed in with parameters)
  5. Server address set to 192.168.1.104
  6. Author: kikilizhm#163.com (change # to @)
  7. */
  8. #include <stdlib.h>
  9. #include <sys/types.h>
  10. #include <stdio.h>
  11. #include <sys/socket.h>
  12. #include <linux/in.h>
  13. #include <string.h>
  14. int main ()
  15. {
  16. int SFP,NFP; / * Define two descriptors * /
  17. struct sockaddr_in s_add,c_add;
  18. int sin_size;
  19. unsigned short portnum=0x8888; / * Use port on server * /
  20. printf ("hello,welcome to my server!\r\n");
  21. SFP = socket (af_inet, sock_stream, 0);
  22. if ( -1 = = SFP)
  23. {
  24. printf ("socket fail!  \ r \ n ");
  25. return-1;
  26. }
  27. printf ("socket OK!\r\n");
  28. /* Populate the server port address information so that the following address and port are used for monitoring */
  29. Bzero (&s_add,sizeof (struct sockaddr_in));
  30. S_add.sin_family=af_inet;
  31. S_add.sin_addr.s_addr=htonl (Inaddr_any); / * This address uses full 0, i.e. all * /
  32. S_add.sin_port=htons (Portnum);
  33. /* Bind port with bind */
  34. if ( -1 = = Bind (SFP, (struct sockaddr *) (&s_add), sizeof (struct sockaddr)))
  35. {
  36. printf ("bind fail!\r\n");
  37. return-1;
  38. }
  39. printf ("bind OK!\r\n");
  40. /* Start listening to the appropriate port */
  41. if ( -1 = = Listen (sfp,5))
  42. {
  43. printf ("Listen Fail!\r\n");
  44. return-1;
  45. }
  46. printf ("Listen ok\r\n");
  47. while (1)
  48. {
  49. Sin_size = sizeof (struct sockaddr_in);
  50. /* Accept the service side using the function, the call will enter the blocking state, waiting for the user to connect, when no client to connect, the program stopped here,
  51. You will not see the subsequent print, and when a client makes a connection, the program executes once and then loops back here to continue waiting.
  52. The second parameter of the accept here is used to obtain the port and address information for the client.
  53. */
  54. NFP = Accept (SFP,struct sockaddr *) (&c_add), &sin_size);
  55. if ( -1 = = NFP)
  56. {
  57. printf ("Accept fail!\r\n");
  58. return-1;
  59. }
  60. printf ("Accept ok!\r\nserver start get connect from% #x:% #x \ r \ n", Ntohl (C_ADD.SIN_ADDR.S_ADDR), Ntohs (c_add.sin_  Port));
  61. /* Use write to send a message to the client, or you can try using another function to implement */
  62. if ( -1 = = Write (NFP,"hello,welcome to my server \ r \ n", +))
  63. {
  64. printf ("Write fail!\r\n");
  65. return-1;
  66. }
  67. printf ("Write ok!\r\n");
  68. Close (NFP);
  69. }
  70. Close (SFP);
  71. return 0;
  72. }

[CPP]View Plaincopyprint?
  1. /*************************************
  2. File name: client.c
  3. Simple example of Linux socket network programming-client program
  4. The server port is set to 0x8888 (ports and addresses can be changed depending on the situation, or passed in with parameters)
  5. Server address set to 192.168.1.104
  6. Author: kikilizhm#163.com (change # to @)
  7. */
  8. #include <stdlib.h>
  9. #include <sys/types.h>
  10. #include <stdio.h>
  11. #include <sys/socket.h>
  12. #include <linux/in.h>
  13. #include <string.h>
  14. int main ()
  15. {
  16. int CFD; / * File descriptor * /
  17. int recbytes;
  18. int sin_size;
  19. Char buffer[1024]={0}; / * Accept buffer * /
  20. struct sockaddr_in s_add,c_add; / * Storage server and local IP, port and other information structures */
  21. unsigned short portnum=0x8888; /* The communication port used by the server can be changed to be the same as the server */
  22. printf ("Hello,welcome to Client!\r\n");
  23. /* Build sockets using the Internet, TCP streaming */
  24. CFD = socket (af_inet, sock_stream, 0);
  25. if ( -1 = = CFD)
  26. {
  27. printf ("socket fail!  \ r \ n ");
  28. return-1;
  29. }
  30. printf ("socket OK!\r\n");
  31. /* Constructs the server side IP and port information, the concrete structure may check the data * *
  32. Bzero (&s_add,sizeof (struct sockaddr_in));
  33. S_add.sin_family=af_inet;
  34. S_add.sin_addr.s_addr= inet_addr ("192.168.1.104"); / * IP is converted to 4-byte shaping and needs to be changed according to the server IP when using * /
  35. S_add.sin_port=htons (Portnum); / * Here htons is to convert the short data byte sequence from the host type to the network type, actually is
  36. Two bytes of 2 bytes of data are switched, and the corresponding Ntohs effect, the same substance, but the name is different. Htonl and Ntohl are
  37. The 4-byte shaping of the operation. Change the 0x12345678 to 0x78563412, the name is different, the content 22 is the same, in general, the network is big-endian,
  38. PPC CPU is big, x86 CPU for small end, arm can configure the size of the end, need to ensure that the byte sequence is correct when received.
  39. */
  40. printf ("s_addr =% #x, port:% #x \ r \ n", s_add.sin_addr.s_addr,s_add.sin_port); / * The small end is printed here
  41. Contrary to what we normally see. */
  42. /* Client Connection server, parameters are socket file descriptor, address information, address structure size */
  43. if ( -1 = = Connect (CfD, (struct sockaddr *) (&s_add), sizeof (struct sockaddr)))
  44. {
  45. printf ("Connect fail!\r\n");
  46. return-1;
  47. }
  48. printf ("Connect OK!\r\n");
  49. /* Connection succeeded, receive characters from server */
  50. if ( -1 = = (Recbytes = read (cfd,buffer,1024)))
  51. {
  52. printf ("read data fail!\r\n");
  53. return-1;
  54. }
  55. printf ("read ok\r\nrec:\r\n");
  56. buffer[recbytes]=' + ';
  57. printf ("%s\r\n", buffer);
  58. GetChar (); / * This sentence is for the program to pause here, you can use Netstat to view the current connection * /
  59. Close (CFD); / * Close the connection, this communication is complete * /
  60. return 0;
  61. }

Simple example of C language socket network programming under Linux

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.