(8) Socket communication instance under Linux (client) and Windows (server side)

Source: Internet
Author: User
Tags new set socket connect htons

Examples of socket traffic under Linux (client) and Windows (server side):

(1) The first is windows to do the client, Linux to do the service-side program

Windows Client Side

  1. #include <stdio.h>
  2. #include <Windows.h>
  3. #pragma comment (lib, "Ws2_32.lib")
  4. #define PORT 5000
  5. #define IP_Address "192.168.1.30"//server address
  6. int main ()//ARGC is the total number of arguments on the command line
  7. {
  8. Wsadata s; Used to store the Windows Sockets initialization information returned by calling the AfxSocketInit global function
  9. SOCKET Clientsocket;
  10. struct sockaddr_in clientaddr; A sockaddr_in type of structure object
  11. int ret = 0;
  12. Char Sendbuffer[max_path]; Windows MAX_PATH Default is 260
  13. Initialize the Windows Socket
  14. Initialization of the Winsock service by the WSAStartup function
  15. if (WSAStartup (Makeword (2, 2), &s)! = 0)//By connecting two given unsigned parameters, the first parameter is a low byte
  16. {
  17. printf ("Init Windows Socket failed! Error:%d\n ", GetLastError ());
  18. GetChar ();
  19. return-1;
  20. }
  21. while (1)
  22. {
  23. Create a set of interfaces
  24. If such a socket is connected to a specified port with connect ()
  25. Send () and recv () are available for sending and receiving datagrams with this port
  26. When the session ends, call Closesocket ()
  27. Clientsocket = socket (af_inet,//Only ARPA Internet address format is supported
  28. Sock_stream,//Type description of the new set of interfaces
  29. IPPROTO_TCP); protocol used by the socket interface
  30. if (Clientsocket = = Invalid_socket)
  31. {
  32. printf ("Create Socket failed! Error:%d\n ", GetLastError ());
  33. GetChar ();
  34. return-1;
  35. }
  36. clientaddr.sin_family = af_inet;
  37. CLIENTADDR.SIN_ADDR.S_ADDR = inet_addr (ip_address); Define IP Address
  38. Clientaddr.sin_port = htons (port); Convert the unsigned short number of hosts to network byte order
  39. memset (Clientaddr.sin_zero, 0x00, 8); Function typically initializes the newly requested memory
  40. Connecting sockets
  41. ret = connect (Clientsocket,
  42. (struct sockaddr*) &clientaddr,
  43. sizeof (CLIENTADDR));
  44. if (ret = = socket_error)
  45. {
  46. printf ("Socket Connect failed! Error:%d\n ", GetLastError ());
  47. GetChar ();
  48. return-1;
  49. }
  50. Else
  51. {
  52. printf ("Socket Connect succeed!");
  53. }
  54. printf ("Input Data:");
  55. while (1)
  56. {
  57. scanf ("%s", &sendbuffer);
  58. Sending data to the server
  59. ret = Send (Clientsocket,
  60. Sendbuffer,
  61. (int) strlen (sendbuffer),//return send buffer data length
  62. 0);
  63. if (ret = = socket_error)
  64. {
  65. printf ("Send Information failed! Error:%d\n ", GetLastError ());
  66. GetChar ();
  67. Break
  68. }
  69. Break
  70. }
  71. Close socket
  72. Closesocket (Clientsocket);
  73. if (sendbuffer[0] = = ' Q ')//Set input when the first character is Q to exit
  74. {
  75. printf ("quit!\n");
  76. Break
  77. }
  78. }
  79. WSACleanup ();
  80. GetChar ();
  81. System ("pause");
  82. return 0;
  83. }

Linux Server Side

  1. #include <stdio.h>
  2. #include <sys/socket.h>
  3. #include <sys/types.h>/* See NOTES * *
  4. #include <sys/socket.h>
  5. #include <arpa/inet.h>
  6. #include <string.h>
  7. #include <unistd.h>
  8. #include <cstdlib>
  9. #define SERVER_PORT 5000
  10. #define LENGTH_OF_LISTEN_QUEUE 20
  11. #define BUFFER_SIZE 10
  12. int main ()//(int argc, char* argv[])
  13. {
  14. struct sockaddr_in server_addr;
  15. int server_socket;
  16. int opt = 1;
  17. Bzero (&server_addr, sizeof (SERVER_ADDR)); The first n bytes of a byte string are 0, including '
  18. server_addr.sin_family = af_inet;
  19. SERVER_ADDR.SIN_ADDR.S_ADDR = htons (Inaddr_any); To the small end, Inaddr_any is the address assigned to address 0.0.0.0
  20. Server_addr.sin_port = htons (Server_port);
  21. Create a socket
  22. Server_socket = socket (pf_inet, sock_stream, 0);
  23. if (Server_socket < 0)
  24. {
  25. printf ("Create Socket failed!\n");
  26. Exit (1);
  27. }
  28. Bind a socket
  29. SetSockOpt (Server_socket, Sol_socket, so_reuseaddr, &opt, sizeof (opt));
  30. if (Bind (Server_socket, (struct sockaddr*) &server_addr, sizeof (SERVER_ADDR)))
  31. {
  32. printf ("Server Bind Port:%d failed!\n", server_port);
  33. Exit (1);
  34. }
  35. Monitor socket
  36. if (Listen (Server_socket, Length_of_listen_queue))
  37. {
  38. printf ("Server Listen failed!\n");
  39. Exit (1);
  40. }
  41. while (1)
  42. {
  43. struct sockaddr_in client_addr;
  44. int client_socket;
  45. socklen_t length;
  46. Char Buffer[buffer_size];
  47. Connecting the client socket
  48. length = sizeof (CLIENT_ADDR);
  49. Client_socket = Accept (Server_socket, (struct sockaddr*) &client_addr, &length);
  50. if (Client_socket < 0)
  51. {
  52. printf ("Server Accept failed!\n");
  53. Break
  54. }
  55. Receiving data from the client
  56. while (1)
  57. {
  58. Bzero (Buffer, buffer_size);
  59. Length = recv (Client_socket, Buffer, buffer_size, 0);
  60. if (length < 0)
  61. {
  62. printf ("Server recieve Data failed!\n");
  63. Break
  64. }
  65. if (' q ' = = Buffer[0])
  66. {
  67. printf ("quit!\n");
  68. Break
  69. }
  70. printf ("%s\n", Buffer);
  71. Break
  72. }
  73. Close (Client_socket);
  74. }
  75. Close (Server_socket);
  76. return 0;
  77. }

(2) Windows as server, Linux as client instance

(8) Socket communication instance under Linux (client) and Windows (server side)

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.