DEVC++需要加入ws2_32库
#include <iostream>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
void sendData(const char* ip, int port, const char* data) {
WSADATA wsaData;
SOCKET sockfd;
struct sockaddr_in server_addr;
// 初始化Winsock
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
std::cerr << "WSAStartup failed" << std::endl;
return;
}
// 创建socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == INVALID_SOCKET) {
std::cerr << "Error creating socket" << std::endl;
WSACleanup();
return;
}
// 设置服务器地址
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
server_addr.sin_addr.s_addr = inet_addr(ip);
// 连接服务器
if (connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == SOCKET_ERROR) {
std::cerr << "Connection failed" << std::endl;
closesocket(sockfd);
WSACleanup();
return;
}
// 发送数据
if (send(sockfd, data, strlen(data), 0) == SOCKET_ERROR) {
std::cerr << "Send failed" << std::endl;
} else {
std::cout << "Data sent successfully" << std::endl;
}
// 关闭socket
closesocket(sockfd);
WSACleanup();
}
int main() {
const char* ip = "127.0.0.1"; // 替换为目标服务器的IP地址
int port = 5009; // 替换为目标服务器的端口
const char* data = "Hello, Server!";
sendData(ip, port, data);
return 0;
}