我正在开发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
}