从 ifaddrs 结构分配 IPv4 地址到 sockaddr_in 结构

问题描述 投票:0回答:1

我正在开发一个 UDP 服务器应用程序。
我希望将我的服务器套接字绑定到特定接口(从配置文件中读取)。在这种情况下

eth0
.
我正在使用
getifaddrs
阅读有关当前网络接口的所有信息。
然后我遍历返回的链表
getifaddrs
并根据我想要的接口检查每个接口的名称。
找到匹配项后,我计划从
struct ifaddrs
中提取IPv4地址并将其分配给
struct sockaddr_in
对象。
目前我不确定如何将
struct ifaddrs->ifa_addr->sa_data
传递给
struct sockaddr_in.sin_addr.s_addr
或者我正在遵循的正确/推荐方法。

代码:

bool start_server(void)
{
    struct sockaddr_in  server_address;
    struct ifaddrs      *ifaddr;
    int                 return_value;
    try
    {
        this->sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
        if (this->sock_fd < 0) 
        {
            //TODO : Log Error
            return false;
        }

        // Initialize and configure struct sockaddr_in server_address
        std::memset(&server_address, sizeof(sockaddr_in), 0); // Initialize struct sockaddr_in server_address to 0
        server_address.sin_family = AF_INET;
        server_address.sin_port = htons(6666); //We are using the port 6666

        //Get IP address from the interface (eth0 currently) -> Interface name to be read from the configuration file
        return_value = getifaddrs(&ifaddr);
        if (return_value < 0) //On error, -1 is returned
        {
            //TODO : Log Error
            return false;
        }
        for (struct ifaddrs *ifa; ifa != nullptr; ifa = ifaddr->ifa_next)//ifa stand for interface address
        {
            if (std::strcmp(ifa->ifa_name, "eth0") == 0) //We check the interface name in the linked Strings are exact match
            {
                if (ifa->ifa_addr == nullptr)
                {
                    //TODO : Log Error - Selected interface doesn't have an assoiciated IP address
                    break; 
                }
                else
                {
                    server_address.sin_addr.s_addr = inet_addr(ifa->ifa_addr->sa_data); //I am unsure will this work or if this is the right approach
                    break;
                }

            }
        }
        freeifaddrs(ifaddr); //Free up memeory allocated by getifaddrs. Prevents Memory Leaks
}
c++ sockets vxworks
1个回答
0
投票

ifa_addr
成员是一个指向
struct sockaddr
的指针。首先,您要通过检查
sa_family
是否设置为
AF_INET
来确保它用于 IPv4 地址,如果是这样,您可以使用
memcpy
将其复制到
struct sockadr_in
.

    for (struct ifaddrs *ifa = ifaddr; ifa != nullptr; ifa = ifaddr->ifa_next)
    {
        if (std::strcmp(ifa->ifa_name, "eth0") == 0)
        {
            if (ifa->ifa_addr == nullptr)
            {
                //TODO : Log Error - 
                //Selected interface doesn't have an assoiciated IP address
                break; 
            }
            else if (ifa->ifa_addr->sa_family == AF_INET)
            {
                memcpy(&server_address.sin_addr, ifa->ifa_addr, 
                       sizeof(server_address.sin_addr));
                break;
            }

        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.