gpt4 book ai didi

c++ - 获取传入 UDP 数据包的目标端口

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:20:34 27 4
gpt4 key购买 nike

我已经通读了 ip 手册页和 socket 手册页,我所能找到的只是 header 中 IP_PKTINFO 控制消息中的目标 IP 地址,似乎没有办法从数据包的 header 中提取目标端口。或者有吗?

如果不是,有没有办法从数据包到达的套接字中获取端口?

最佳答案

由于您使用的是普通套接字,因此可以在套接字 fd 上使用 recvfrom。 recvfrom 的手册页:

RECV(2)

NAME

   recv, recvfrom, recvmsg - receive a message from a socket

SYNOPSIS

        #include <sys/types.h>
#include <sys/socket.h>

ssize_t recv(int sockfd, void *buf, size_t len, int flags);

ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,
struct sockaddr *src_addr, socklen_t *addrlen);

ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags);

DESCRIPTION

   The  recv(),  recvfrom(),  and recvmsg() calls are used to receive messages from a socket.  They
may be used to receive data on both connectionless and connection-oriented sockets.

recvfrom() recvfrom() places the received message into the buffer buf. The caller must specify the size of the buffer in len.

   If src_addr is not NULL, and the underlying protocol provides the source address of the message,
that source address is placed in the buffer pointed to by src_addr. In this case, addrlen is a
value-result argument. Before the call, it should be initialized to the size of the buffer
associated with src_addr. Upon return, addrlen is updated to contain the actual size of the
source address. The returned address is truncated if the buffer provided is too small; in this
case, addrlen will return a value greater than was supplied to the call.

If the caller is not interested in the source address, src_addr and addrlen should be specified
as NULL.

beej 指南中的示例:

// datagram sockets and recvfrom()

struct addrinfo hints, *res;
int sockfd;
int byte_count;
socklen_t fromlen;
struct sockaddr_storage addr;
char buf[512];
char ipstr[INET6_ADDRSTRLEN];

// get host info, make socket, bind it to port 4950
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // use IPv4 or IPv6, whichever
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE;
getaddrinfo(NULL, "4950", &hints, &res);
sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
bind(sockfd, res->ai_addr, res->ai_addrlen);

// no need to accept(), just recvfrom():

fromlen = sizeof addr;
byte_count = recvfrom(sockfd, buf, sizeof buf, 0, &addr, &fromlen);

printf("recv()'d %d bytes of data in buf\n", byte_count);
printf("from IP address %s\n",
inet_ntop(addr.ss_family,
addr.ss_family == AF_INET?
((struct sockadd_in *)&addr)->sin_addr:
((struct sockadd_in6 *)&addr)->sin6_addr,
ipstr, sizeof ipstr);

Example of recvfrom , man page of recvfrom

希望对你有帮助

关于c++ - 获取传入 UDP 数据包的目标端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43676179/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com