Click to See Complete Forum and Search --> : what error happen?


hjc
December 31st, 2002, 01: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;
}

DanM
December 31st, 2002, 01:21 AM
I think you are missing the initial WSAStartup call.
My suggestions are :

1) Always check the return code of a function.
2) If there is an error, call GetLastError (or WSAGetLastError in this case).
3) Read the documentation. You will find the answer to your problem much easier. Here is the link:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winsock/winsock/gethostname_2.asp

Dan

hjc
December 31st, 2002, 01:37 AM
thanks for Dan

my program's function 'CalcLocalIP' always return 0,because function's local variable 'he' always same to NULL,and gethostname function can not return right 'name'.

and i link library use static library 'ws2_32.lib';WSAStartup function initiates use of WS2_32.DLL .

DanM
December 31st, 2002, 01:43 AM
I think you are a little bit confused about libraries and DLLs.
Anyway, just call WSAStartup before using gethostname.
Read the dosumentation ! it clearly says:

A successful WSAStartup call must occur before using this function.

Dan

hjc
December 31st, 2002, 01:46 AM
thanks for Dan

my program's function 'CalcLocalIP' always return 0,because function's local variable 'he' always same to NULL,and gethostname function can not return right 'name'.

and i link library use static library 'ws2_32.lib';WSAStartup function initiates use of WS2_32.DLL .

hjc
December 31st, 2002, 01:49 AM
thanks for Dan

use your method ,the error has been redressed,thanks for you

DanM
December 31st, 2002, 02:35 AM
Cool :)

Dan