下面的代码,想半天了,不知道哪出了问题。大家帮我看看吧
#include <stdio.h>#include <winsock2.h>int main(){ char buff[255]; WSAData wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData); hostent * hostaddr,*tmp; gethostname(buff, sizeof(buff)); hostaddr=gethostbyname(buff); printf("Host name is: %s\n", buff); printf("ip:%s\n",inet_ntoa(*(struct in_addr *)hostaddr->h_addr)); while (1) { tmp = gethostbyname(buff); if (inet_ntoa(*(struct in_addr *)hostaddr->h_addr) == inet_ntoa(*(struct in_addr *)tmp->h_addr)) puts("ip 未改变"); else printf("ip 改变为:%s\n",inet_ntoa(*(struct in_addr *)tmp->h_addr)); Sleep(3000); } WSACleanup(); return 0;}#include <stdio.h>#include <winsock2.h>int main(){ char buff[255]; WSAData wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData); hostent * hostaddr,*tmp; gethostname(buff, sizeof(buff)); hostaddr=gethostbyname(buff); printf("Host name is: %s\n", buff); printf("ip:%s\n",inet_ntoa(*(struct in_addr *)hostaddr->h_addr));{ // addchar chCurrentIP[256];char *pStr = inet_ntoa(*(struct in_addr *)hostaddr->h_addr);int i = 0;while (pStr[i] != '\0' && i < 256){ chCurrentIP[i] = pStr[i]; i++;}chCurrentIP[i] = '\0';} while (1) { tmp = gethostbyname(buff); if(strcmp(chCurrentIP, inet_ntoa(*(struct in_addr *)tmp->h_addr)) == 0) puts("ip 未改变"); else { printf("ip 改变为:%s\n",inet_ntoa(*(struct in_addr *)tmp->h_addr));{ //add pStr = inet_ntoa(*(struct in_addr *)hostaddr->h_addr);i = 0;while (pStr[i] != '\0' && i < 256){ chCurrentIP[i] = pStr[i]; i++;}chCurrentIP[i] = '\0';} } Sleep(3000); } WSACleanup(); return 0;}
[解决办法]
inet_ntoa
The Windows Sockets inet_ntoa function converts an (Ipv4) Internet network address into a string in Internet standard dotted format.
char FAR * inet_ntoa (
struct in_addr in
);
Parameters
in
[in] A structure that represents an Internet host address.
Remarks
The inet_ntoa function takes an Internet address structure specified by the in parameter and returns an ASCII string representing the address in ".'' (dot) notation as in "a.b.c.d''. The string returned by inet_ntoa resides in memory that is allocated by Windows Sockets. The application should not make any assumptions about the way in which the memory is allocated. The data is guaranteed to be valid until the next Windows Sockets function call within the same thread, but no longer. Therefore, the data should be copied before another Windows Sockets call is made.
Return Values
If no error occurs, inet_ntoa returns a char pointer to a static buffer containing the text address in standard ".'' notation. Otherwise, it returns NULL.
QuickInfo
Windows NT: Yes
Windows: Yes
Windows CE: Use version 1.0 and later.
Header: Declared in winsock2.h.
Import Library: Link with ws2_32.lib.
See Also
inet_addr
[解决办法]