在C++中連接網絡通常使用Socket編程來實現。以下是一個簡單的示例代碼,演示如何使用Socket連接網絡:
#include <iostream>
#include <string>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
int main() {
// 初始化Winsock
WSADATA wsData;
WORD ver = MAKEWORD(2, 2);
int wsResult = WSAStartup(ver, &wsData);
if (wsResult != 0) {
std::cerr << "Can't start Winsock, Error #" << wsResult << std::endl;
return 1;
}
// 創建Socket
SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == INVALID_SOCKET) {
std::cerr << "Can't create socket, Error #" << WSAGetLastError() << std::endl;
WSACleanup();
return 1;
}
// 連接服務器
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(80); // 端口號
hint.sin_addr.S_un.S_addr = inet_addr("192.168.1.1"); // 服務器IP地址
int connResult = connect(sock, (sockaddr*)&hint, sizeof(hint));
if (connResult == SOCKET_ERROR) {
std::cerr << "Can't connect to server, Error #" << WSAGetLastError() << std::endl;
closesocket(sock);
WSACleanup();
return 1;
}
std::cout << "Connected to server!" << std::endl;
// 關閉Socket和清理Winsock
closesocket(sock);
WSACleanup();
return 0;
}
在上面的代碼中,我們通過Winsock庫來初始化網絡連接,并創建一個Socket來連接指定的服務器IP地址和端口號。如果連接成功,就會輸出"Connected to server!",否則輸出錯誤信息。最后,記得關閉Socket和清理Winsock。