ubuntu系统下socket编程
时间: 2023-11-08 22:05:08 浏览: 139
在Ubuntu系统下进行socket编程,需要使用C语言中的socket编程接口。以下是一个简单的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
int main()
{
int socket_desc, client_sock, c, read_size;
struct sockaddr_in server, client;
char client_message[2000];
// 创建socket
socket_desc = socket(AF_INET, SOCK_STREAM, 0);
if (socket_desc == -1)
{
printf("Could not create socket");
}
// 绑定IP地址和端口号
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(8888);
if (bind(socket_desc, (struct sockaddr *)&server, sizeof(server)) < 0)
{
printf("bind failed");
return 1;
}
printf("bind done");
// 监听连接
listen(socket_desc, 3);
// 等待连接
printf("Waiting for incoming connections...\n");
c = sizeof(struct sockaddr_in);
client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c);
if (client_sock < 0)
{
printf("accept failed");
return 1;
}
printf("Connection accepted");
// 接收客户端消息并回复
while ((read_size = recv(client_sock, client_message, 2000, 0)) > 0)
{
printf("Received message: %s\n", client_message);
write(client_sock, client_message, strlen(client_message));
memset(client_message, 0, 2000);
}
if (read_size == 0)
{
printf("Client disconnected");
}
else if (read_size == -1)
{
printf("recv failed");
}
return 0;
}
```
这是一个简单的TCP服务器示例代码,它监听本地IP地址的8888端口,等待客户端连接请求。当客户端连接成功后,服务器会接收客户端发送的消息,并回复同样的消息。
阅读全文