sendmsg

send,sendto以及sendmsg系統調用用於傳送訊息到另一個套接字。send函式在套接字處於連線狀態時方可使用。

sendto和sendmsg在任何時候都可使用 。

基本介紹

  • 外文名:sendmsg
  • 含義:傳送訊息到另一個套接字
  • 使用方法:在套接字處於連線狀態時
  • 性質:函式
sendmsg介紹,演示用法,

sendmsg介紹

send,sendto,sendmsg方法用於從套接字傳送訊息。
ssize_t send (int s, const void *msg, size_t len, int flags);
ssize_t sendto (int s, const void *msg, size_t len, int flags, const struct sockaddr *to,
socklen_t tolen);
ssize_t sendmsg (int s, const struct msghdr *msg, int flags);
sendsendto以及sendmsg系統調用用於傳送訊息到另一個套接字send函式在套接字處於連線狀態時方可使用。
sendtosendmsg在任何時候都可使用。

演示用法

下面的代碼片段演示了sendsendto,sendmsg函式的用法:
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
void Recv()
{
struct sockaddr_in serv_addr;
int sock_fd;
char line[15] = "Hello world!";
int size = 13;
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
serv_addr.sin_port = htons(5000);
sock_fd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
connect(sock_fd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
send(sock_fd, line, size, 0);
close(sock_fd);
}
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
void Sendto()
{
sockaddr_in receiver_addr;
int sock_fd;
char line[15] = "Hello World!";
sock_fd = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
receiver_addr.sin_family = AF_INET;
receiver_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
receiver_addr.sin_port = htons(5000);
sendto(sock_fd, line, 13, 0,(struct sockaddr*)&receiver_addr,sizeof(receiver_addr));
close(sock_fd);
}
#include <sys/socket.h> #include <netinet/in.h>
#include <unistd.h>
void sendmsg()
{
struct sockaddr_in receiver_addr;
int sock_fd;
char line[15] = "Hello World!";
struct msghdr msg;
struct iovec iov;
sock_fd = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
receiver_addr.sin_family = AF_INET;
receiver_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
receiver_addr.sin_port = htons(5000);
msg.msg_name = &receiver_addr;
msg.msg_namelen = sizeof(receiver_addr);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_iov->iov_base = line;
msg.msg_iov->iov_len = 13;
msg.msg_control = 0;
msg.msg_controllen = 0;
msg.msg_flags = 0;
sendmsg(sock_fd,&msg,0);
close(sock_fd);
}

相關詞條

熱門詞條

聯絡我們