我想连接linux服务器和Windows客户端 这些是linux服务器和Windows客户端的简单(基本)示例
这些代码在(Linux服务器,Linux客户端)和(Windows服务器,Windows客户端)中运行良好
(因为是本地的?)
如何连接linux服务器和Windows客户端?
(在Linux下,我在VirtualBox中执行了代码)
如果客户端使用端口55000(IP 127.0.0.1)输入,则它们将交互并更改 一些消息
client.c
(窗口)
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#pragma comment(lib, "ws2_32.lib")
#include <winsock2.h>
#include <stdio.h>
#define PORT 55000
#define BUFFER_SIZE 100
int main() {
WSADATA wsdata;
if (WSAStartup(MAKEWORD(2, 2), &wsdata) != 0) {
printf("Fail to initiate ws2_d2.dll \n\n");
return 0;
}
printf("Success to initiate ws_32.dll\n\n");
SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, 0);
SOCKADDR_IN serverAddress;
ZeroMemory(&serverAddress, sizeof(serverAddress));
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(PORT);
****************//VirtualBox IP '10.0.2.15'********************
serverAddress.sin_addr.s_addr = inet_addr("10.0.2.15");
if ((connect(clientSocket, (SOCKADDR*)(&serverAddress), sizeof(serverAddress)) != 0)) {
printf("Fail to connect.\n\n");
return 0;
}
printf("connected!!! \n\n");
char toServer[BUFFER_SIZE];
strcpy(toServer, "Hello Server!!! I'm client!");
send(clientSocket, toServer, strlen(toServer) + 1, 0);
printf("Data to server : %s\n\n", toServer);
char fromServer[BUFFER_SIZE + 1];
recv(clientSocket, fromServer, BUFFER_SIZE, 0);
printf("received data from server : %s\n", fromServer);
closesocket(clientSocket);
WSACleanup();
printf("Exit ws_32.dll\n\n");
return 0;
}
server.c
(Linux)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#define PORT 55000
int main(){
int server_socket;
int client_socket;
struct sockaddr_in server_address={0,};
struct sockaddr_in client_address={0,};
int client_address_size;
char toClient[] = "Hello Client!!\n";
char fromClient[100];
server_socket = socket(AF_INET, SOCK_STREAM, 0);
printf("Server Socket Create!!!\n");
memset(&server_address, 0, sizeof(server_address));
server_address.sin_family=AF_INET;
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
server_address.sin_port = htons(PORT);
bind(server_socket,(struct sockaddr*)&server_address,
sizeof(server_address));
listen(server_socket, 5);
printf("Wait Client...\n");
client_address_size = sizeof(client_address);
client_socket = accept(server_socket, (struct sockaddr*)%client_address
&client_address_size)
printf("Client Connect!!!\n");
read(client_socket, fromClient, sizeof(fromClient));
printf("From Client Message: %s\n", fromClient);
write(client_socket, toClient, sizeof(toClient));
printf("To Client Message: %s\n", toClient);
close(client_socket);
return 0;
}