基于C语言的一个本地socket的简单示例程序
时间: 2023-07-30 15:09:42 浏览: 12
下面是一个基于C语言的本地socket的简单示例程序,它创建了一个本地套接字并进行了简单的通信:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#define SOCKET_PATH "/tmp/mysocket"
int main()
{
int sockfd, client_sockfd;
struct sockaddr_un server_addr, client_addr;
socklen_t client_len;
char buf[1024];
// 创建本地套接字
sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
if (sockfd == -1) {
perror("socket");
exit(EXIT_FAILURE);
}
// 绑定本地套接字
server_addr.sun_family = AF_UNIX;
strcpy(server_addr.sun_path, SOCKET_PATH);
unlink(SOCKET_PATH);
if (bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("bind");
exit(EXIT_FAILURE);
}
// 监听连接
if (listen(sockfd, 5) == -1) {
perror("listen");
exit(EXIT_FAILURE);
}
printf("Server is listening...\n");
// 接受客户端连接
client_len = sizeof(client_addr);
client_sockfd = accept(sockfd, (struct sockaddr *)&client_addr, &client_len);
if (client_sockfd == -1) {
perror("accept");
exit(EXIT_FAILURE);
}
printf("Client is connected...\n");
// 读取客户端数据并回复
while (1) {
memset(buf, 0, sizeof(buf));
if (read(client_sockfd, buf, sizeof(buf)) == -1) {
perror("read");
exit(EXIT_FAILURE);
}
printf("Received: %s", buf);
if (write(client_sockfd, buf, strlen(buf)) == -1) {
perror("write");
exit(EXIT_FAILURE);
}
}
// 关闭套接字
close(client_sockfd);
close(sockfd);
unlink(SOCKET_PATH);
return 0;
}
```
该程序首先创建了一个本地套接字,然后绑定到指定的路径上,接着监听连接并等待客户端的连接请求。一旦有客户端连接,它就会读取客户端发送的数据并进行回复。需要注意的是,在读取和发送数据时,我们使用了read和write函数,这些函数在套接字编程中非常常用,可以实现简单的数据通信。