linux下tcp socket编程实例
时间: 2023-06-05 21:47:56 浏览: 146
下面是一个简单的 Linux 下 TCP Socket 编程实例:
1. 创建 Socket
```c
int sockfd = socket(AF_INET, SOCK_STREAM, );
if (sockfd < ) {
perror("socket");
exit(EXIT_FAILURE);
}
```
2. 绑定 Socket
```c
struct sockaddr_in addr;
memset(&addr, , sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) < ) {
perror("bind");
exit(EXIT_FAILURE);
}
```
3. 监听 Socket
```c
if (listen(sockfd, backlog) < ) {
perror("listen");
exit(EXIT_FAILURE);
}
```
4. 接受连接
```c
struct sockaddr_in client_addr;
socklen_t client_len = sizeof(client_addr);
int clientfd = accept(sockfd, (struct sockaddr *)&client_addr, &client_len);
if (clientfd < ) {
perror("accept");
exit(EXIT_FAILURE);
}
```
5. 发送数据
```c
char *msg = "Hello, world!";
if (send(clientfd, msg, strlen(msg), ) < ) {
perror("send");
exit(EXIT_FAILURE);
}
```
6. 接收数据
```c
char buf[1024];
int n = recv(clientfd, buf, sizeof(buf), );
if (n < ) {
perror("recv");
exit(EXIT_FAILURE);
} else if (n == ) {
printf("Connection closed by peer.\n");
} else {
buf[n] = '\';
printf("Received: %s\n", buf);
}
```
7. 关闭 Socket
```c
close(clientfd);
close(sockfd);
```
阅读全文