我必须开发的应用程序的客户端有问题。
我必须实施的第一阶段是“扫描”网络,搜索其他用户。我决定使用 UDP 套接字,它们工作正常。如果我使用广播 IP 地址 (getnamebyhost("192.168.1.255")) 它工作正常。问题是应用程序必须在不同的网络上工作,而且我不知道 IP 地址(192.168 或 10.0 或其他)。我要学习地址,所以我在网上找到使用getifaddr()。这是代码:
#include <stdio.h>
#include <sys/types.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#include <string.h>
int FindMyIp();
int IsConnected();
char *myIpAddr, *myMask, *myBroad;
int main (int argc, const char * argv[]) {
int checkConnection=0;
checkConnection = IsConnected();
while (checkConnection == 0) {
printf("Checking again..\n");
checkConnection = IsConnected();
sleep(2);
}
checkConnection=0;
printf("\nConnected to a new network..\n");
while (checkConnection == 0) {
checkConnection = FindMyIp();
if (checkConnection==0) { sleep(2); }
}
printf("My IP is %s\n", myIpAddr);
printf("My Mask is %s\n", myMask);
printf("The Broadcast IP is %s\n", myBroad);
return 0;
}
int IsConnected()
{
if (system("ping -c 1 www.google.com")){
return 0;
}
else {
return 1;
}
}
int FindMyIp()
{
struct ifaddrs * ifAddrStruct=NULL;
struct ifaddrs * ifa=NULL;
void * tmpAddrPtr=NULL;
printf("Acquiring interface information.. ");
getifaddrs(&ifAddrStruct);
printf("Checking for wanted interface..\n");
int i=0, connected=0;
ifa = ifAddrStruct;
while (i!=1) {
if ((ifa ->ifa_addr->sa_family==AF_INET)&&(ifa->ifa_name[0]=='e')&&(ifa->ifa_name[1]=='n')&&(ifa->ifa_name[2]=='1')) {
i=1;
connected=1;
}
else {
if (ifa->ifa_next == NULL) {
printf("error");
return connected;
}
ifa = ifa->ifa_next;
}
}
char addressBuffer1[INET_ADDRSTRLEN];
char addressBuffer2[INET_ADDRSTRLEN];
char addressBuffer3[INET_ADDRSTRLEN];
tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
inet_ntop(AF_INET, tmpAddrPtr, addressBuffer1, INET_ADDRSTRLEN);
myIpAddr = addressBuffer1;
tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_netmask)->sin_addr;
inet_ntop(AF_INET, tmpAddrPtr, addressBuffer2, INET_ADDRSTRLEN);
myMask = addressBuffer2;
tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_broadaddr)->sin_addr;
inet_ntop(AF_INET, tmpAddrPtr, addressBuffer3, INET_ADDRSTRLEN);
myBroad = addressBuffer3;
return connected;
}
所以在myBroad中我应该保存广播IP地址,我可以用printf打印它,但是当我将它传递给套接字时: struct hostent *hptr = gethostbyname(myBroad); 它行不通!错误在哪里?
谢谢