用c语言写一个socket服务器
时间: 2023-03-21 17:03:16 浏览: 111
用C语言实现socket通信
你好,以下是使用C语言编写一个Socket服务器的简单示例代码:
```
#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* hello = "Hello from server";
// 创建Socket文件描述符
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// 设置Socket选项
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
perror("setsockopt failed");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(8888);
// 绑定Socket文件描述符到IP地址和端口号
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// 监听连接请求
if (listen(server_fd, 3) < 0) {
perror("listen failed");
exit(EXIT_FAILURE);
}
// 接受连接请求并发送数据
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
perror("accept failed");
exit(EXIT_FAILURE);
}
send(new_socket, hello, strlen(hello), 0);
printf("Hello message sent\n");
// 关闭Socket文件描述符
close(new_socket);
close(server_fd);
return 0;
}
```
这段代码创建了一个Socket服务器,并监听端口号为8888的连接请求。当有客户端连接时,服务器会发送一条消息“Hello from server”给客户端,并关闭连接。
阅读全文