c++初始化socket并实现TCP连接
时间: 2023-08-21 15:04:15 浏览: 156
要初始化socket并实现TCP连接,需要以下步骤:
1. 引入头文件
```c++
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
#include <iostream>
```
2. 创建TCP socket
```c++
int client_socket = socket(AF_INET, SOCK_STREAM, 0);
```
3. 设置服务器地址和端口
```c++
struct sockaddr_in server_address;
memset(&server_address, 0, sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_port = htons(port); // port为服务器端口
server_address.sin_addr.s_addr = inet_addr(ip); // ip为服务器IP地址
```
4. 连接服务器
```c++
if (connect(client_socket, (struct sockaddr*)&server_address, sizeof(server_address)) != 0) {
std::cout << "connect error" << std::endl;
close(client_socket);
return -1;
}
```
完整代码示例:
```c++
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
#include <iostream>
int main() {
int client_socket = socket(AF_INET, SOCK_STREAM, 0);
if (client_socket == -1) {
std::cout << "create socket error" << std::endl;
return -1;
}
struct sockaddr_in server_address;
memset(&server_address, 0, sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_port = htons(8000);
server_address.sin_addr.s_addr = inet_addr("127.0.0.1");
if (connect(client_socket, (struct sockaddr*)&server_address, sizeof(server_address)) != 0) {
std::cout << "connect error" << std::endl;
close(client_socket);
return -1;
}
// 连接成功,可以开始进行数据交互
close(client_socket);
return 0;
}
```
阅读全文