【Linux】TCP套接字编程
在Linux中,TCP套接字编程通常涉及以下步骤:
- 创建套接字(socket)。
- 绑定套接字到一个特定的地址和端口(bind)。
- 监听连接请求(listen)。
- 接受连接(accept)。
- 发送/接收数据(send/recv)。
- 关闭套接字(close)。
以下是一个简单的TCP服务器和客户端示例代码:
TCP 服务器端示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main() {
int server_fd, new_socket;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};
const char *greeting = "Hello from server";
// 创建套接字
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// 绑定套接字到地址和端口
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(8080);
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// 监听连接请求
if (listen(server_fd, 3) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
// 接受连接
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
// 发送数据
send(new_socket, greeting, strlen(greeting), 0);
// 接收数据
if (recv(new_socket, buffer, 1024, 0) == 0) {
printf("Client disconnected\n");
} else {
printf("Received message: %s\n", buffer);
}
// 关闭套接字
close(new_socket);
close(server_fd);
return 0;
}
TCP 客户端示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main(int argc, char *argv[]) {
int sock;
struct sockaddr_in serv_addr;
char buffer[1024] = {0};
if (argc < 2) {
printf("Please provide the server ip address as first argument\n");
return 1;
}
// 创建套接字
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("Socket creation error");
return 1;
}
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(8080);
if (inet_pton(AF_INET, argv[1], &serv_addr.sin_addr) <= 0) {
per
评论已关闭