在Linux环境下,使用socket进行编程主要涉及到客户端和服务器端。以下是一个简单的例子,展示了如何使用socket编程在Linux下创建TCP连接。
服务器端代码(server.c):
#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 addrlen = sizeof(address);
char buffer[1024];
int opt = 1;
int client_sent;
// 创建socket文件描述符
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// 绑定socket到地址和端口
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);
}
// 监听socket
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);
}
// 接收客户端消息
while ((client_sent = recv(new_socket, buffer, 1024, 0)) > 0) {
printf("Buffer: %s\n", buffer);
// 发送消息回客户端
if (send(new_socket, buffer, client_sent, 0) < 0) {
perror("send");
}
}
// 关闭socket
close(new_socket);
close(server_fd);
return 0;
}
客户端代码(client.c):
#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];
int n;
if (argc < 2) {
printf("Please provide the server ip address as first argument\n");
return 1;
}
// 创建socket
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// 设置服务器地址
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) {
perror("inet_pton error