hjc
December 31st, 2002, 02:13 AM
i write the program,link ws2_32.lib and link success,but run it can not work right.
i trace it ,find gethostname function can not return right name
can somebody help me?
thanks
program:
#include <stdlib.h>
#include <stdio.h>
#include <winsock2.h>
unsigned long CalcLocalIP()
{
struct hostent *he;
char name[256];
unsigned long ip;
bool done;
int i,j;
::gethostname(name,255);
name[255] = 0;
he = ::gethostbyname(name);
if (he == NULL)
return 0;
ip = 0;
i = 0;
done = false;
while (!done)
{
if (he->h_addr_list[i] == NULL)
done = true;
else
{
ip = 0;
for (j = 0 ; j < 4 ; j++)
ip |= ((unsigned long)((unsigned char)he->h_addr_list[i][j])<<((3-j)*8));
if (he->h_addr_list[i][0] != 127 && he->h_addr_list[i][0] != 0)
done = true;
else
i++;
}
}
return ip;
}
int main()
{
unsigned long destip;
destip = CalcLocalIP();
if (destip == INADDR_NONE)
{
printf("Bad IP address specified\n");
return -1;
}
printf("destip =%ld \n",destip);
destip = ntohl(destip);
printf("destip =%ld \n",destip);
return 0;
}
i trace it ,find gethostname function can not return right name
can somebody help me?
thanks
program:
#include <stdlib.h>
#include <stdio.h>
#include <winsock2.h>
unsigned long CalcLocalIP()
{
struct hostent *he;
char name[256];
unsigned long ip;
bool done;
int i,j;
::gethostname(name,255);
name[255] = 0;
he = ::gethostbyname(name);
if (he == NULL)
return 0;
ip = 0;
i = 0;
done = false;
while (!done)
{
if (he->h_addr_list[i] == NULL)
done = true;
else
{
ip = 0;
for (j = 0 ; j < 4 ; j++)
ip |= ((unsigned long)((unsigned char)he->h_addr_list[i][j])<<((3-j)*8));
if (he->h_addr_list[i][0] != 127 && he->h_addr_list[i][0] != 0)
done = true;
else
i++;
}
}
return ip;
}
int main()
{
unsigned long destip;
destip = CalcLocalIP();
if (destip == INADDR_NONE)
{
printf("Bad IP address specified\n");
return -1;
}
printf("destip =%ld \n",destip);
destip = ntohl(destip);
printf("destip =%ld \n",destip);
return 0;
}