用cplusplus语言举例说明通信中的三次握手程序代码
时间: 2024-01-02 11:03:58 浏览: 71
TCP/IP协议三次握手
以下是使用C++语言实现的基本的三次握手程序代码:
客户端代码:
```c++
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <cstring>
#include <unistd.h>
using namespace std;
int main(int argc, char *argv[]) {
const char *server_address = "127.0.0.1";
int server_port = 8888;
// 创建套接字
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
cerr << "Failed to create socket." << endl;
return -1;
}
// 连接服务器
struct sockaddr_in server_addr;
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(server_port);
inet_pton(AF_INET, server_address, &server_addr.sin_addr);
if (connect(sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
cerr << "Failed to connect server." << endl;
return -1;
}
// 发送SYN
char syn_msg[] = "SYN";
send(sockfd, syn_msg, strlen(syn_msg), 0);
// 接收SYN+ACK
char syn_ack_msg[10];
recv(sockfd, syn_ack_msg, 10, 0);
if (strncmp(syn_ack_msg, "SYN+ACK", 7) != 0) {
cerr << "Error message received from server." << endl;
return -1;
}
// 发送ACK
char ack_msg[] = "ACK";
send(sockfd, ack_msg, strlen(ack_msg), 0);
// 关闭套接字
close(sockfd);
return 0;
}
```
服务端代码:
```c++
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <cstring>
#include <unistd.h>
using namespace std;
int main(int argc, char *argv[]) {
const char *server_address = "127.0.0.1";
int server_port = 8888;
// 创建套接字
int listenfd = socket(AF_INET, SOCK_STREAM, 0);
if (listenfd < 0) {
cerr << "Failed to create socket." << endl;
return -1;
}
// 绑定地址和端口
struct sockaddr_in server_addr;
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(server_port);
inet_pton(AF_INET, server_address, &server_addr.sin_addr);
if (bind(listenfd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
cerr << "Failed to bind address and port." << endl;
return -1;
}
// 监听连接
if (listen(listenfd, 5) < 0) {
cerr << "Failed to listen." << endl;
return -1;
}
// 接收连接
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
int connfd = accept(listenfd, (struct sockaddr *) &client_addr, &client_addr_len);
if (connfd < 0) {
cerr << "Failed to accept connection." << endl;
return -1;
}
// 接收SYN
char syn_msg[10];
recv(connfd, syn_msg, 10, 0);
if (strncmp(syn_msg, "SYN", 3) != 0) {
cerr << "Error message received from client." << endl;
return -1;
}
// 发送SYN+ACK
char syn_ack_msg[] = "SYN+ACK";
send(connfd, syn_ack_msg, strlen(syn_ack_msg), 0);
// 接收ACK
char ack_msg[10];
recv(connfd, ack_msg, 10, 0);
if (strncmp(ack_msg, "ACK", 3) != 0) {
cerr << "Error message received from client." << endl;
return -1;
}
// 关闭套接字
close(connfd);
close(listenfd);
return 0;
}
```
阅读全文