阅读量:0
在Linux网络编程中,sendmsg函数是用于向指定的套接字发送数据的函数。下面是一些实际案例分析:
- 发送UDP数据包:
struct sockaddr_in serv_addr; int sockfd = socket(AF_INET, SOCK_DGRAM, 0); memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(PORT); inet_pton(AF_INET, SERVER_IP, &serv_addr.sin_addr); struct msghdr msg = { 0 }; struct iovec iov[1]; char buffer[BUF_SIZE] = "Hello, world!"; iov[0].iov_base = buffer; iov[0].iov_len = strlen(buffer); msg.msg_name = &serv_addr; msg.msg_namelen = sizeof(serv_addr); msg.msg_iov = iov; msg.msg_iovlen = 1; sendmsg(sockfd, &msg, 0);
- 发送TCP数据流:
struct sockaddr_in serv_addr; int sockfd = socket(AF_INET, SOCK_STREAM, 0); memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(PORT); inet_pton(AF_INET, SERVER_IP, &serv_addr.sin_addr); struct msghdr msg = { 0 }; struct iovec iov[1]; char buffer[BUF_SIZE] = "Hello, world!"; iov[0].iov_base = buffer; iov[0].iov_len = strlen(buffer); msg.msg_name = &serv_addr; msg.msg_namelen = sizeof(serv_addr); msg.msg_iov = iov; msg.msg_iovlen = 1; sendmsg(sockfd, &msg, 0);
- 发送文件描述符:
struct sockaddr_in serv_addr; int sockfd = socket(AF_INET, SOCK_STREAM, 0); memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(PORT); inet_pton(AF_INET, SERVER_IP, &serv_addr.sin_addr); struct msghdr msg = { 0 }; struct iovec iov[1]; char buffer[BUF_SIZE] = "Hello, world!"; iov[0].iov_base = buffer; iov[0].iov_len = strlen(buffer); msg.msg_name = &serv_addr; msg.msg_namelen = sizeof(serv_addr); msg.msg_iov = iov; msg.msg_iovlen = 1; int fd = open("file.txt", O_RDONLY); struct cmsghdr *cmsg; size_t cmsglen = CMSG_LEN(sizeof(int)); cmsg = (struct cmsghdr *)malloc(cmsglen); cmsg->cmsg_len = CMSG_LEN(sizeof(int)); cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = SCM_RIGHTS; *((int *)CMSG_DATA(cmsg)) = fd; msg.msg_control = cmsg; msg.msg_controllen = cmsglen; sendmsg(sockfd, &msg, 0);
这些案例展示了sendmsg函数的不同用法,包括发送UDP数据包、发送TCP数据流以及发送文件描述符等情况。在实际的网络编程中,sendmsg函数可以根据具体的需求进行灵活应用,为程序的网络通信提供了更多的选择和控制。