阅读量:0
在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。