gpt4 book ai didi

c - 如何使用接收到的IP地址和端口号建立套接字连接

转载 作者:行者123 更新时间:2023-11-30 19:12:42 25 4
gpt4 key购买 nike

如何使用 inet_addr() 为变量 a、b、c 和 d 分配 IP 地址这样我就可以发送数据:

a=rcvsdheader->Option.IPv4Address>>24;
//printf("the msb of ipv4 is %d\n",a);
b=rcvsdheader->Option.IPv4Address>>16&0x000000FF;
//printf("the msb of ipv4 is %d\n",b);
c=rcvsdheader->Option.IPv4Address>>8&0x000000FF;
//printf("the msb of ipv4 is %d\n",c);
d=rcvsdheader->Option.IPv4Address&0x000000FF;
//printf("the msb of ipv4 is %d\n",d);
if(rcvsdheader->Option.Protocol==UDP)
printf("The Type of Protocol is UDP\n");
printf("The PortNumber i%d\n",rcvsdheader->Option.Portnumber);
e=rcvsdheader->Option.Portnumber;
if ( (s=socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
die("socket");
}

someipServeraddr.sin_family = AF_INET;
someipServeraddr.sin_addr.s_addr=inet_addr();
someipServeraddr.sin_port = htons(e);

最佳答案

inet_addr将包含 IPv4 地址文本表示形式的字符串作为参数:

in_addr_t inet_addr(const char *cp);

The inet_addr() function converts the Internet host address cp from IPv4 numbers-and-dots notation into binary data in network byte order. If the input is invalid, INADDR_NONE (usually -1) is returned. Use of this function is problematic because -1 is a valid address (255.255.255.255). Avoid its use in favor of inet_aton(), inet_pton(3), or getaddrinfo(3), which provide a cleaner way to indicate error return.

因此,我们可以使用sprintf制作一个:

char buf[16];
sprintf(buf, "%u.%u.%u.%u", a, b, c, d);
someipServeraddr.sin_addr.s_addr = inet_addr(buf);

然而这一切都是毫无意义的。 s_addr类型为in_addr_t这是 typedef对于 uint32_t在 POSIX 上,因此您可以使用 rcvsdheader->Option.IPv4Address直接:

someipServeraddr.sin_addr.s_addr = htonl(rcvsdheader->Option.IPv4Address);

( 如果 htonl 包含主机字节顺序的地址,则需要 IPv4Address ,例如作为整数环回 0x7F000001 ;如果您知道您的地址是网络顺序的,请执行以下操作不使用 htonl )。

关于c - 如何使用接收到的IP地址和端口号建立套接字连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36591539/

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