Exercise: Use socket to implement communication between Linux and Windows, and use socketlinux

Source: Internet
Author: User
Tags socket connect htons

Exercise: Use socket to implement communication between Linux and Windows, and use socketlinux

In daily life, most people generally use windows systems. However, for R & D personnel, development, compilation, and other work is usually based on linux machines. As a matter of fact, Linux, UNIX, and Windows Server account for a majority of the market share. In the aspect of supercomputer, replacing Unix with Linux has become the largest operating system.

Communication is a major task of computers and operating systems. Through ftp, ping, ssh, and other methods, people can easily connect to the server. Two programs on a large network exchange data through a two-way communication connection. one end of the connection is called a socket. Windows uses windows socket, while linux uses posix socket. Today, combined with some classic online routines, we wrote a simple socket code to implement communication between Ubuntu (in a virtual machine) and Windows.

Implementation Code of the client on Windows:

# Include <stdio. h> # include <Windows. h> # pragma comment (lib, "ws2_32.lib") # define Port 5000 # define IP_ADDRESS "172.30.70.95" int main (int argc, char * argv []) // argc is the total number of parameters in the command line {WSADATA s; // It is used to store the Windows Sockets initialization information returned by calling the AfxSocketInit global function SOCKET ClientSocket; struct sockaddr_in ClientAddr; // A addr_in struct object int ret = 0; char SendBuffer [MAX_PATH]; // MAX_PATH of Windows is 260 by default // initialize Windows Socket // The WSAStartup function initializes the Winsock service if (WSAStartup (MAKEWORD (2, 2), & s )! = 0) // connect two given unsigned parameters. The first parameter is low byte {printf ("Init Windows Socket Failed! Error: % d \ n ", GetLastError (); getchar (); return-1;} while (1) {// create a set of interfaces // if such an interface uses connect () to connect to a specified port // send () and recv () are available () send and receive data packets with this port // when the session ends, call closesocket () ClientSocket = socket (AF_INET, // only supports the ARPA Internet address format SOCK_STREAM, // The type description of the new interface IPPROTO_TCP); // The protocol used by the interface if (ClientSocket = INVALID_SOCKET) {printf ("Create Socket Failed! Error: % d \ n ", GetLastError (); getchar (); return-1;} ClientAddr. sin_family = AF_INET; ClientAddr. sin_addr.s_addr = inet_addr (IP_ADDRESS); // defines the IP address ClientAddr. sin_port = htons (Port); // converts the unsigned short integer number of the host to the network byte sequence memset (ClientAddr. sin_zero, 0X00, 8); // The function usually initializes the newly applied memory // connects Socket ret = connect (ClientSocket, (struct sockaddr *) & ClientAddr, sizeof (ClientAddr); if (ret = SOCKET_ERROR) {printf ("Socke T Connect Failed! Error: % d \ n ", GetLastError (); getchar (); return-1;} else {printf (" Socket Connect Succeed! ");} Printf (" Input Data: "); while (1) {scanf (" % s ", & SendBuffer ); // send data to the server ret = send (ClientSocket, SendBuffer, (int) strlen (SendBuffer), // return the length of the sending buffer DATA 0); if (ret = SOCKET_ERROR) {printf ("Send Information Failed! Error: % d \ n ", GetLastError (); getchar (); break;} // close socket closesocket (ClientSocket ); if (SendBuffer [0] = 'q') // exit {printf ("Quit! \ N "); break ;}} WSACleanup (); getchar (); return 0 ;}

My linux (Ubuntu) Network Information:

Server code on the linux (Ubuntu) platform:

# Include <unistd. h> # include <stdio. h> # include <i386-linux-gnu/sys/socket. h> # include <netinet/in. h> # include <i386-linux-gnu/sys/types. h> # include <stdlib. h> # include <string. h> # define SERVER_PORT 5000 # define LENGTH_OF_LISTEN_QUEUE 20 # define BUFFER_SIZE 10int main () // (int argc, char * argv []) {struct sockaddr_in server_addr; int server_socket; int opt = 1; bzero (& server_addr, sizeof (server_addr ));// Set the first n Bytes of the byte string to 0, including '\ 0' server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htons (INADDR_ANY); // to small-end, INADDR_ANY is the address server_addr.sin_port = htons (SERVER_PORT) with the specified address 0.0.0.0; // create a Socket server_socket = socket (PF_INET, SOCK_STREAM, 0); if (server_socket <0) {printf ("Create Socket Failed! \ N "); exit (1) ;}// bind a socket setsockopt (server_socket, SOL_SOCKET, SO_REUSEADDR, & opt, sizeof (opt); if (bind (server_socket, (struct sockaddr *) & server_addr, sizeof (server_addr) {printf ("Server Bind Port: % d Failed! \ N ", SERVER_PORT); exit (1) ;}// listen to Socket if (Listen (server_socket, LENGTH_OF_LISTEN_QUEUE) {printf (" Server listen Failed! \ N "); exit (1) ;}while (1) {struct sockaddr_in client_addr; int client_socket; socklen_t length; char Buffer [BUFFER_SIZE]; // connect to the client Socket length = sizeof (client_addr); client_socket = accept (server_socket, (struct sockaddr *) & client_addr, & length); if (client_socket <0) {printf ("Server Accept Failed! \ N "); break;} // receives data from the client while (1) {bzero (Buffer, BUFFER_SIZE); length = recv (client_socket, Buffer, BUFFER_SIZE, 0 ); if (length <0) {printf ("Server Recieve Data Failed! \ N "); break;} if ('q' = Buffer [0]) {printf (" Quit! \ N "); break;} printf (" % s \ n ", Buffer); break;} close (client_socket);} close (server_socket); return 0 ;}

When you open the client, make sure that the server is in the listening status; otherwise, the connection fails:

Open the server program as follows:

Data transmission successful:

This small experiment Only takes a little time to debug, and can only send data in one way. The single function is purely a small exercise. In socket programming debugging, the main focus is on the error value returned when a program error occurs, code vulnerabilities can often be quickly identified.

Reference: http://blog.csdn.net/feixiaoxing/article/details/8567162

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.