recv函数用法

阅读: 评论:0

2024年2月8日发(作者:)

recv函数用法

recv函数用法

在 C 语言中,`recv`函数是一个用于接收网络数据的函数。它通常用于网络编程中,用于从套接字(socket)接收数据。

函数原型:

```c

int recv(int socket, void *buffer, int length, int flags);

```

参数说明:

- `socket`:套接字描述符,用于指定要接收数据的套接字。

- `buffer`:指向接收数据缓冲区的指针。

- `length`:要接收的字节数。

- `flags`:可以是 0 或以下值的组合:

- `MSG_PEEK`:查看数据而不从缓冲区中移除数据。

- `MSG_OOB`:接收带外数据。

返回值:

- 成功接收的字节数。

- 如果发生错误,返回-1 并设置相应的错误代码。

下面是一个示例,演示了如何使用`recv`函数接收数据:

```c

#include

#include

#include

#include

#include

#include

#define SERVER_ADDRESS "127.0.0.1"

#define SERVER_PORT 8080

void receiveData(int socket) {

char buffer[1024];

int receivedBytes;

// 接收数据

while ((receivedBytes = recv(socket, buffer, sizeof(buffer), 0)) > 0) {

printf("Received %d bytes: %sn", receivedBytes, buffer);

}

if (receivedBytes == 0) {

printf("Connection closedn");

} else if (receivedBytes < 0) {

perror("recv");

exit(1);

}

}

int main() {

int socket, clientAddressLength;

struct sockaddr_in serverAddress, clientAddress;

char clientAddressString[INET_ADDRSTRLEN];

// 创建一个 TCP 套接字

if ((socket = socket(AF_INET, SOCK_STREAM, 0)) == -1) {

perror("socket");

exit(1);

}

// 填充服务器地址结构体

_family = AF_INET;

_addr.s_addr = inet_addr(SERVER_ADDRESS);

_port = htons(SERVER_PORT);

// 将服务器地址绑定到套接字

if (bind(socket, (struct sockaddr *)&serverAddress, sizeof(serverAddress))

< 0) {

perror("bind");

exit(1);

}

// 开始监听连接

if (listen(socket, 1) < 0) {

perror("listen");

exit(1);

}

// 等待客户端连接

clientAddressLength = sizeof(clientAddress);

if ((int)accept(socket, (struct sockaddr *)&clientAddress, (socklen_t

*)&clientAddressLength)) < 0) {

perror("accept");

exit(1);

}

// 获取客户端地址字符串

if (inet_ntop(AF_INET, &(_addr.s_addr),

clientAddressString, INET_ADDRSTRLEN) == NULL) {

perror("inet_ntop");

exit(1);

}

printf("Connected to client: %sn", clientAddressString);

// 接收数据

receiveData(socket);

// 关闭套接字

close(socket);

return 0;

}

```

在上面的示例中,我们创建了一个 TCP 服务器,然后在一个无限循环中使用`recv`函数接收客户端发送的数据。每次接收到数据后,我们打印出接收到的字节数和数据内容。

需要注意的是,`recv`函数可能会阻塞程序的执行,直到有数据可用或者发生错误。如果你需要非阻塞的接收数据,可以使用`recvfrom`或`recvmsg`函数,并将其最后一个参数设置为`MSG_DONTWAIT`。

希望这个示例对你有帮助。如果你有任何其他问题,请随时提问。

recv函数用法

本文发布于:2024-02-08 07:14:37,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170734767766905.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:数据   函数   接收   用于   接收数据   示例   地址
留言与评论(共有 0 条评论)
   
验证码:
排行榜

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23